Return address info about the remote side of the connection
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.
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("18.104.22.168", &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 22.214.171.124:80, so this should print: // Peer IP address: 126.96.36.199 // 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));
gethostname(), gethostbyname(), gethostbyaddr()