getsockname() — Get the name of a socket
Standards
Standards / Extensions | C or C++ | Dependencies |
---|---|---|
XPG4.2 |
both |
Format
#define _XOPEN_SOURCE_EXTENDED 1
#include <sys/socket.h>
int getsockname(int socket, struct sockaddr *__restrict__ name,
socklen_t *__restrict__ namelen);
#define _OE_SOCKETS
#include <sys/types.h>
#include <sys/socket.h>
int getsockname(int socket, struct sockaddr *name,
int *namelen);
General description
The getsockname() call stores the current name for the socket specified by the socket parameter into the structure pointed to by the name parameter. It returns the address to the socket that has been bound. If the socket is not bound to an address, the call returns with the family set, and the rest of the structure set to zero. For example, an unbound socket in the Internet domain would cause the name to point to a sockaddr_in structure with the sin_family field set to AF_INET and all other fields zeroed.
- Parameter
- Description
- socket
- The socket descriptor.
- name
- The address of the buffer into which getsockname() copies the name of socket.
- namelen
- Must initially point to an integer that contains the size in bytes of the storage pointed to by name. On return, that integer contains the size required to represent the address of the connecting socket. If this value is larger than the size supplied on input, then the information contained in sockaddr is truncated to the length supplied on input. If name is NULL, namelen is ignored.
The getsockname() call is often used to discover the port assigned to a socket after the socket has been implicitly bound to a port. For example, an application can call connect() without previously calling bind(). In this case, the connect() call completes the binding necessary by assigning a port to the socket. This assignment can be discovered with a call to getsockname().
Sockets in the AF_INET6 domain: For an AF_INET6 socket, the address is returned in a sockaddr_6 address structure. The sockaddr_in6 structure is defined in the header file netinet/in.h.
Returned value
If successful, getsockname() returns 0.
- Error Code
- Description
- EBADF
- The socket parameter is not a valid socket descriptor.
- EFAULT
- Using the name and namelen parameters as specified would result in an attempt to access storage outside of the caller's address space.
- ENOBUFS
- getsockname() is unable to process the request due to insufficient storage.
- ENOTCONN
- The socket is not in the connected state.
- ENOTSOCK
- The descriptor is for a file, not for a socket.
- EOPNOTSUPP
- The operation is not supported for the socket protocol.