Resolving a Domain Name to an IP Address

 < Day Day Up > 



Although converting a host name to an IP address is not really an advanced topic, code dealing with what could be an FQDN or an IP address in a consistent manner is commonly missing in many Sockets applications. In terms of configuration, an IP address or host name could be present and the application should be able to resolve either of these to a binary network address uniformly.

The code pattern shown in Listing 6.5 illustrates the handling of an unknown address type. Regardless of whether a dotted-notation IP address is provided, or an FQDN, the result is a binary network address (assuming a valid entry or resolvable address).

Listing 6.5 Resolving an unknown type of address.

start example
struct sockaddr_in saddr; char address[]={"192.168.1.1"}; // or char address[]={"www.address.com"}; saddr.sin_addr.s_addr = inet_addr( address ); if ( saddr.sin_addr.s_addr = 0xffffffff ) {   struct hostent *hptr =      (struct hostent *)gethostbyname( address );   if (hptr == NULL) {     /* Can't resolve the address... */   } else {     struct in_addr **addrs;     addrs = (struct in_addr **)hptr->h_addr_list;     memcpy( &saddr.sin_addr, *addrs, sizeof(struct in_addr) );   } }
end example

The code pattern shown in Listing 6.5 is very useful for automatically generating a 32-bit network byte order IP address from a string representing either a string dotted-notation IP address or FQDN.



 < 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