Determining Peer Information

 < Day Day Up > 



There are many cases in which it is important for a server to know who has connected (either for bookkeeping/logging or for simple authentication). After a connection is made by a client, the server interrogates the client socket to identify its address and port information. This is very easily done with the Sockets API through the use of the getpeername Sockets function. This function simply gathers the peer address and port information and returns it to the user in a sockaddr_in structure. Listing 6.15 illustrates the retrieval and display of the peer information using the getpeername function for a stream socket.

Listing 6.15 Identifying the peer using getpeername.

start example
int sock, len, ret; struct sockaddr_in peeraddr; sock = socket( AF_INET, SOCK_STREAM, 0 ); ... len = sizeof( peeraddr ); ret = getpeername( sock,                      (struct sockaddr_in *)&peeraddr, &len ); printf( "Peer address : %s\n",           inet_ntoa( peeraddr.sin_addr ) ); printf( "Peer port    : %d\n",           ntohs( peeraddr.sin_port ) );
end example

The Sockets application can also use the inverse function, getsockname, to retrieve information about the local socket.



 < Day Day Up > 



BSD Sockets Programming from a Multi-Language Perspective
Network Programming for Microsoft Windows , Second Edition (Microsoft Programming Series)
ISBN: 1584502681
EAN: 2147483647
Year: 2003
Pages: 225
Authors: Jim Ohlund

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net