| < Day Day Up > |
|
The purpose of the getsockname function is to return the local address of a given socket. Local address refers here to the local IP address and local port number. The prototype for the getsockname function is:
int getsockname( int sock, struct sockaddr *addr, socklen_t *len );
The caller provides an existing socket (either connected or bound), an address structure, and the length of the address structure. Because we’re focusing on AF_INET type sockets, we’ll use the sockaddr_in structure exclusively. The getsockname function returns either 0 on success or –1 if an error occurred (commonly, a bad socket was passed in). An example of this function in use is provided in Listing 4.3.
Listing 4.3 Using getsockname to gather the local address information for a socket.
int socket; struct sockaddr_in localaddr; int la_len, ret; ... la_len = sizeof( localaddr ); ret = getsockname( socket, (struct sockaddr_in *)&localaddr, &la_len ); if (ret == 0) { printf( "Local Address is : %s\n", inet_ntoa( localaddr.sin_addr ) ); printf( "Local Port is : %d\n", localaddr.sin_port ); }
An interesting use of the getsockname function is to identify the interface used by a given socket in a multiport design. For example, if a host contains a number of interfaces, how the socket will connect through those interfaces depends upon the peer address, routing tables, and other factors. The getsockname function can be used to identify which of the local interfaces (localaddr.sin_addr, in this case) the socket has used as its egress.
| < Day Day Up > |
|