9 #include <arpa/inet.h> |
9 #include <arpa/inet.h> |
10 #include <netdb.h> |
10 #include <netdb.h> |
11 |
11 |
12 int main (int argc, char **argv) |
12 int main (int argc, char **argv) |
13 { |
13 { |
14 struct hostent *he; |
14 struct addrinfo hints; |
|
15 struct addrinfo *result, *rp; |
15 |
16 |
16 char *ip; |
17 void *addr = NULL; |
17 |
18 char ip[INET6_ADDRSTRLEN]; |
18 int i = 0; |
|
19 |
19 |
20 if (argc != 2) { |
20 if (argc != 2) { |
21 fprintf (stderr, "Usage: %s <hostname>\n", argv[0]); |
21 fprintf (stderr, "Usage: %s <hostname>\n", argv[0]); |
22 return EXIT_FAILURE; |
22 return EXIT_FAILURE; |
23 } |
23 } |
24 |
24 |
25 he = gethostbyname (argv[1]); |
25 memset (&hints, 0, sizeof (hints)); |
26 ip = NULL; |
26 hints.ai_family = AF_UNSPEC; |
|
27 hints.ai_socktype = SOCK_STREAM; |
27 |
28 |
28 if (he != NULL) { |
29 if (getaddrinfo (argv[1], NULL, &hints, &result) != 0) { |
29 while (he->h_addr_list[i] != NULL) { |
30 perror ("getaddrinfo"); |
30 ip = inet_ntoa (*((struct in_addr *)he->h_addr_list[i])); |
31 return EXIT_FAILURE; |
31 printf ("%s: %s\n", argv[1], ip); |
32 } |
32 i++; |
33 |
|
34 for (rp = result; rp != NULL; rp = rp->ai_next) { |
|
35 if (rp->ai_family == AF_INET6) { |
|
36 struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)rp->ai_addr; |
|
37 addr = &(ipv6->sin6_addr); |
|
38 } else if (rp->ai_family == AF_INET) { |
|
39 struct sockaddr_in *ipv4 = (struct sockaddr_in *)rp->ai_addr; |
|
40 addr = &(ipv4->sin_addr); |
|
41 } |
|
42 if (addr != NULL) { |
|
43 if (inet_ntop (rp->ai_family, addr, ip, sizeof (ip)) != NULL) |
|
44 printf ("%s: %s\n", argv[1], ip); |
33 } |
45 } |
34 } |
46 } |
35 |
47 |
|
48 if (result != NULL) |
|
49 freeaddrinfo (result); |
|
50 |
36 return EXIT_SUCCESS; |
51 return EXIT_SUCCESS; |
37 } |
52 } |