Other Miscellaneous Functions

 < Day Day Up > 



Let’s now look at a few miscellaneous functions from the Sockets API and the capabilities they provide. The three function prototypes we discuss in this section are shown in the following code:

struct hostent *gethostbyname( const char *name ); int getsockname( int sock,                     struct sockaddr *name, socklen_t *namelen ); int getpeername( int sock,                     struct sockaddr *name, socklen_t *namelen );

Function gethostbyname provides the means to resolve a host and domain name (otherwise known as a Fully Qualified Domain Name, or FQDN) to an IP address. For example, the FQDN of www.microsoft.com might resolve to the IP address 207.46.249.27. Converting an FQDN to an IP address is important because all of the Sockets API functions work with number IP address (32-bit addresses) rather than FQDNs. An example of the gethostbyname function is shown next:

struct hostent *hptr; hptr = gethostbyname( "www.microsoft.com"); if (hptr == NULL) // can't resolve...   else {     printf( "Binary address is %x\$$\n", hptr->h_addr_list[0] );   }

Function gethostbyname returns a pointer to a structure that represents the numeric IP address for the FQDN (hptr->h_addr_list[0]). Otherwise, gethostbyname returns a NULL, which means that the FQDN could not be resolved by the local resolver. This call blocks while the local resolver communicates with the configured DNS servers.

Function getsockname permits an application to retrieve information about the local socket endpoint. This function, for example, can identify the dynamically assigned ephemeral port number for the local socket. An example of its use is shown in the following code:

 int sock; struct sockaddr localaddr; int laddrlen; // socket for sock created and connected. ... getsockname( sock, (struct sockaddr_in *)&localaddr, &laddrlen ); printf( "local port is %d\n", ntohs(localaddr.sin_port) ); 

The reciprocal function of getsockname is getpeername. This permits us to gather addressing information about the connected peer socket. An example, similar to the getsockname example, is shown in the following code:

int sock; struct sockaddr remaddr; int raddrlen; // socket for sock created and connected. ... getpeername( sock, (struct sockaddr_in *)&remaddr, &raddrlen ); printf( "remote port is %d\$$\n", ntohs(remaddr.sin_port) );

In both examples, the address can also be extracted using the sin_addr field of the sockaddr structure.



 < 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