getpeername()
PROTOTYPE
#include <sockets.h>
int getpeername(int socket, void *addr, socklen_t *addrlen);
DESCRIPTION
getpeername() outputs the remote address of the connected socket referenced by socket. If there are no errors, an address structure containing the remote address is written to *addr, either type sockaddr_in or sockaddr_in6 according to the connection type. The 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.
getpeername() only succeeds on connected sockets. Since a connected socket’s remote address is either given to connect() or (optionally) output by accept(), getpeername() is not strictly necessary. However, it may be useful when one module receives a connected socket from another module.
If successful, getpeername() 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. |
| ENOTCONN | The socket is not connected. |
| ENOTSOCK | socket is not a valid socket handle. |
EXAMPLE
sockaddr_in addr;
socklen_t addrlen;
/*-------------------------------------------------------------------*/
/* Exercise getpeername(). */
/*-------------------------------------------------------------------*/
addrlen = sizeof(struct sockaddr_in);
getpeername(sock, &addr, &addrlen);
printf("Server IP address is ");
printIP(ntohl(addr.sin_addr));
printf(", port is %d\n", ntohs(addr.sin_port));