You are on page 1of 1

The getpeername() system call returns the address of the peer socket on a stream socket connection.

This is useful primarily with TCP sockets, if the server wants to find out the address of the client that has
made a connection. This information could also be obtained when the accept() call is performed;
however, if the server was execed by the program that did the accept() (e.g., inetd), then it inherits the
socket file descriptor, but the address information returned by accept() is no longer available. Listing 61-
3 demonstrates the use of getsockname() and getpeername(). This program employs the functions that
we defined in Listing 59-9 (on page 1228), and performs the following steps: 1. Use our inetListen()
function to create a listening socket, listenFd, bound to the wildcard IP address and the port specified in
the program’s sole command-line argument. (The port can be specified numerically or as a service
name.) The len argument returns the length of the address structure for this socket’s domain. This value
is passed in a later call to malloc() to allocate a buffer that is used to return a socket address from calls
to getsockname() and getpeername(). 2. Use our inetConnect() function to create a second socket,
connFd, which is used to send a connection request to the socket created in step 1. 3. Call accept() on
the listening socket in order to create a third socket, acceptFd, that is connected to the socket created in
the previous step. 4. Use calls to getsockname() and getpeername() to obtain the local and peer
addresses for the two connected sockets, connFd and acceptFd. After each of these calls, the program
uses our inetAddressStr() function to convert the socket address into printable form. 5. Sleep for a few
seconds so that we can run netstat in order to confirm the socket address information. (We describe
netstat in Section 61.7.) The following shell session log shows an example run of this program:

You might also like