This routine supersedes the traditional gethostbyaddr(3NSL).
The following sample code demonstrates its usage:
1 #include <iostream>
2 #include <cstdlib>
3 #include <cstdio>
4
5 #include <netdb.h>
6 #include <sys/socket.h>
7 #include <netinet/in.h>
8 #include <arpa/inet.h>
9
10 int main( int argc, char* argv[] )
11 {
12 if ( argc != 2 )
13 {
14 std::cout << argv[0] << " <IPv4 address>" << std::endl;
15 ::exit( EXIT_FAILURE );
16 }
17
18 char address[ INET_ADDRSTRLEN ];
19
20 switch ( ::inet_pton( AF_INET, argv[1], address ) )
21 {
22 case 1:
23 // OK
24 break;
25
26 case 0:
27 std::cout <<
"Invalid IP address." << std::endl;
28 ::exit( EXIT_FAILURE );
29 break;
30
31 case -1:
32 ::perror( 0 );
33 ::exit( EXIT_FAILURE );
34 break;
35
36 default:
37 std::cout <<
"Unknown error." << std::endl;
38 ::exit( EXIT_FAILURE );
39 }
40
41 int error;
42
43 if ( hostent * hp = ::getipnodebyaddr
( address, INET_ADDRSTRLEN, AF_INET, &error ) )
44 {
45 for ( char** p = hp->h_addr_list; *p; p++ )
46 {
47 std::cout <<
::inet_ntoa( *reinterpret_cast< in_addr * >( *p ) )
<< " " << hp->h_name << std::endl;
48 }
49 }
50 else
51 {
52 switch ( error )
53 {
54 case HOST_NOT_FOUND:
55 std::cout <<
"Host unknown.";
56 break;
57
58 case NO_DATA:
59 std::cout <<
"No address is avaliable.";
60 break;
61
62 case NO_RECOVERY:
63 std::cout <<
"Unexpected server failure. "
"Unrecoverable.";
64 break;
65
66 case TRY_AGAIN:
67 std::cout <<
"No response from authoritative server. "
"Retry later.";
68 break;
69
70 default:
71 std::cout <<
"Unknown error.";
72 }
73
74 std::cout << std::endl;
75 }
76
77 return 0;
78 }