Unix Network Programming, Volume 1: The Sockets Networking API (3rd Edition)
4.10 getsockname and getpeername Functions
These two functions return either the local protocol address associated with a socket ( getsockname ) or the foreign protocol address associated with a socket ( getpeername ).
Notice that the final argument for both functions is a value-result argument. That is, both functions fill in the socket address structure pointed to by localaddr or peeraddr . We mentioned in our discussion of bind that the term " name " is misleading. These two functions return the protocol address associated with one of the two ends of a network connection, which for IPV4 and IPV6 is the combination of an IP address and port number. These functions have nothing to do with domain names (Chapter 11). These two functions are required for the following reasons:
Obviously the Telnet server in this final example must know the value of connfd when it starts. There are two common ways to do this. First, the process calling exec can format the descriptor number as a character string and pass it as a command-line argument to the newly exec ed program. Alternately, a convention can be established that a certain descriptor is always set to the connected socket before calling exec . The latter is what inetd does, always setting descriptors 0, 1, and 2 to be the connected socket. Example: Obtaining the Address Family of a Socket
The sockfd_to_family function shown in Figure 4.19 returns the address family of a socket. Figure 4.19 Return the address family of a socket.
lib/sockfd_to_family.c 1 #include "unp.h" 2 int 3 sockfd_to_family(int sockfd) 4 { 5 struct sockaddr_storage ss; 6 socklen_t len; 7 len = sizeof(ss); 8 if (getsockname(sockfd, (SA *) &ss, &len) < 0) 9 return (-1); 10 return (ss.ss_family); 11 } Allocate room for largest socket address structure
5 Since we do not know what type of socket address structure to allocate, we use a sockaddr_storage value, since it can hold any socket address structure supported by the system. Call getsockname
7 “10 We call getsockname and return the address family. Since the POSIX specification allows a call to getsockname on an unbound socket, this function should work for any open socket descriptor. |