getsockname()

PROTOTYPE

#include <sockets.h>

int getsockname(int socket, void *addr, socklen_t *addrlen);

DESCRIPTION

getsockname() outputs the local address of the bound socket referenced by socket. If there are no errors, an address structure containing the local address is written to *addr, either type sockaddr_in or sockaddr_in6 according to the socket type. The IP address and port number are written in network byte order.

On input, *addrlen is the size of the buffer pointed to addr. As output, it is the address structure size, either sizeof(struct sockaddr_in) or sizeof(struct sockaddr_in6). If the buffer size is less than the address structure size, the output is truncated to fit the buffer size.

If the socket is not bound to a local address, POSIX states that the output value is unspecified. In that case, TargetTCP sets the structure’s address family correctly (AF_INET or AF_INET6), but the port number and IP address fields will be zero.

If the port number passed to bind() is zero or connect() or sendto() are called with an unbound socket, an unused local port number is automatically assigned. Similarly, a socket connected by connect() or a listening socket may have its local IP address automatically assigned. In those cases, getsockname() lets applications learn which values were selected, if needed.

If successful, getsockname() outputs the socket address and returns 0. Otherwise, it sets errno and returns -1.

ERROR CODES

EFAULT addr or addrlen is NULL.
EINVAL addrlen is negative.
ENETDOWN TargetTCP has not been initialized.
ENOTSOCK socket is not a valid socket handle.

EXAMPLE

  sockaddr_in addr;
  socklen_t addrlen = sizeof(addr);

  getsockname(sock, &addr, &addrlen);
  printf("Local IP address is ");
  printIP(addr.sin_addr);
  printf(", port is %d\n", ntohs(addr.sin_port));