getpeername Function

 < Day Day Up > 



getpeername Function

The purpose of the getpeername function is to return the peer address of a given socket (also known as the foreign address). Peer address refers here to the peer IP address and peer port number to which the local socket is connected. The prototype for the getpeername function is:

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

The caller provides an existing socket (in an established state), an address structure, and the length of the address structure. Like getsockname, we’re focusing on AF_INET type sockets, we’ll use the sockaddr_in structure exclusively. The getpeername function returns either 0 on success or –1 if an error occurred (commonly, a bad socket was passed in or the socket was not yet connected). An example of this function in use is provided in Listing 4.4.

Listing 4.4 Using getpeername to gather the peer address information for a socket.

start example
int socket; struct sockaddr_in peeraddr; int la_len, ret; ... la_len = sizeof( peeraddr ); ret = getpeername( socket,                     (struct sockaddr_in *)&peeraddr,                     &la_len ); if (ret == 0) {       printf( "Peer Address is : %s\n",                inet_ntoa( peeraddr.sin_addr ) );       printf( "Peer Port is : %d\n", peeraddr.sin_port ); }
end example

The getpeername function is commonly used by servers, as clients would already know this information (because they define to whom they will connect). A server accepts a client connection, and can, at this point, through the accept call also collect the peer address information. If the peer socket information is not collected here, the getpeername function can be used to identify the identity of the peer 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