| < 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.
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) ); } }
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 > |
|