8.7. getpeername()

Return address info about the remote side of the connection


#include <sys/socket.h>

int getpeername(int s, struct sockaddr *addr, socklen_t *len);


Once you have either accept()ed a remote connection, or connect()ed to a server, you now have what is known as a peer. Your peer is simply the computer you're connected to, identified by an IP address and a port. So...

getpeername() simply returns a struct sockaddr_in filled with information about the machine you're connected to.

Why is it called a "name"? Well, there are a lot of different kinds of sockets, not just Internet Sockets like we're using in this guide, and so "name" was a nice generic term that covered all cases. In our case, though, the peer's "name" is it's IP address and port.

Although the function returns the size of the resultant address in len, you must preload len with the size of addr.

Return Value

Returns zero on success, or -1 on error (and errno will be set accordingly.)


int s;
struct sockaddr_in server, addr;
socklen_t len;

// make a socket
s = socket(PF_INET, SOCK_STREAM, 0);

// connect to a server
server.sin_family = AF_INET;
inet_aton("", &server.sin_addr);
server.sin_port = htons(80);

connect(s, (struct sockaddr*)&server, sizeof(server));

// get the peer name
// we know we just connected to, so this should print:
//    Peer IP address:
//    Peer port      : 80

len = sizeof(addr);
getpeername(s, (struct sockaddr*)&addr, &len);
printf("Peer IP address: %s\n", inet_ntoa(addr.sin_addr));
printf("Peer port      : %d\n", ntohs(addr.sin_port));

See Also

gethostname(), gethostbyname(), gethostbyaddr()