Wednesday, June 19, 2013

getipnodebyname(3SOCKET)

This routine supersedes the traditional gethostbyname(3NSL).
The following sample code demonstrates its usage:

 1 #include <iostream>
 2 #include <cstdlib>
 3
 4 #include <netdb.h>
 5 #include <sys/socket.h>
 6 #include <netinet/in.h>
 7 #include <arpa/inet.h>
 8
 9 int main( int argc, char * argv[] )
10 {
11     if ( argc != 2 )
12     {
13         std::cout << argv[0] << " <hostname>" << std::endl;
14         ::exit( EXIT_FAILURE );
15     }
16
17     int error;
18
19     if ( hostent * hp =
            ::getipnodebyname( argv[1], AF_INET, 0, &error ) )
20     {
21         for ( char ** p = hp->h_addr_list; *p; p++ )
22         {
23             std::cout <<
               ::inet_ntoa( *reinterpret_cast< in_addr * >( *p ) )
               << " " << hp->h_name << std::endl;    
24         }
25     }
26     else
27     {
28         switch ( error )
29         {
30             case HOST_NOT_FOUND:
31                 std::cout <<
                   "Host unknown.";
32                 break;
33    
34             case NO_DATA:
35                 std::cout <<
                   "No address is avaliable.";
36                 break;
37    
38             case NO_RECOVERY:
39                 std::cout <<
                   "Unexpected server failure. "
                   "Unrecoverable.";
40                 break;
41    
42             case TRY_AGAIN:
43                 std::cout <<
                   "No response from authoritative server. "
                   "Retry later.";
44                 break;
45    
46             default:
47                 std::cout <<
                   "Unknown error.";
48         }
49
50         std::cout << std::endl;
51     }
52
53     return 0;
54 }