<< Prev | Beej's Guide to Network Programming (cloned from beej.us) | Next >> |
Hosted at Teoria dei Segnali.it - Blog - Download - Signal Transmission - Internet Application Layer - Wiki - Newsletter |
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
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("63.161.169.137", &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 63.161.169.137:80, so this should print: // Peer IP address: 63.161.169.137 // 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()
<< Prev | Beej's Guide to Network Programming (cloned from beej.us) | Next >> |