13.07.2015 Views

Beej's Guide to Network Programming Using Internet Sockets

Beej's Guide to Network Programming Using Internet Sockets

Beej's Guide to Network Programming Using Internet Sockets

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Beej’s <strong>Guide</strong> <strong>to</strong> <strong>Network</strong> <strong>Programming</strong> <strong>Using</strong> <strong>Internet</strong> <strong>Sockets</strong> 498.7. getpeername()Return address info about the remote side of the connectionPro<strong>to</strong>types#include int getpeername(int s, struct sockaddr *addr, socklen_t *len);DescriptionOnce you have either accept()ed a remote connection, or connect()ed <strong>to</strong> a server, you nowhave what is known as a peer. Your peer is simply the computer you’re connected <strong>to</strong>, identified byan IP address and a port. So...getpeername() simply returns a struct sockaddr_in filled with information about themachine you’re connected <strong>to</strong>.Why is it called a “name”? Well, there are a lot of different kinds of sockets, not just <strong>Internet</strong><strong>Sockets</strong> 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 lenwith the size of addr.Return ValueReturns zero on success, or -1 on error (and errno will be set accordingly.)Exampleint s;struct sockaddr_in server, addr;socklen_t len;// make a sockets = socket(PF_INET, SOCK_STREAM, 0);// connect <strong>to</strong> a serverserver.sin_family = AF_INET;inet_a<strong>to</strong>n("63.161.169.137", &server.sin_addr);server.sin_port = h<strong>to</strong>ns(80);connect(s, (struct sockaddr*)&server, sizeof(server));// get the peer name// we know we just connected <strong>to</strong> 63.161.169.137:80, so this should print:// Peer IP address: 63.161.169.137// Peer port : 80len = sizeof(addr);getpeername(s, (struct sockaddr*)&addr, &len);printf("Peer IP address: %s\n", inet_n<strong>to</strong>a(addr.sin_addr));printf("Peer port : %d\n", n<strong>to</strong>hs(addr.sin_port));See Alsogethostname(), gethostbyname(), gethostbyaddr()

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!