| < 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.
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 ) );
The Sockets application can also use the inverse function, getsockname, to retrieve information about the local socket.
| < Day Day Up > |
|