--- a/dnsresolve.c
+++ b/dnsresolve.c
@@ -11,27 +11,42 @@
int main (int argc, char **argv)
{
- struct hostent *he;
+ struct addrinfo hints;
+ struct addrinfo *result, *rp;
- char *ip;
-
- int i = 0;
+ void *addr = NULL;
+ char ip[INET6_ADDRSTRLEN];
if (argc != 2) {
fprintf (stderr, "Usage: %s <hostname>\n", argv[0]);
return EXIT_FAILURE;
}
- he = gethostbyname (argv[1]);
- ip = NULL;
+ memset (&hints, 0, sizeof (hints));
+ hints.ai_family = AF_UNSPEC;
+ hints.ai_socktype = SOCK_STREAM;
+
+ if (getaddrinfo (argv[1], NULL, &hints, &result) != 0) {
+ perror ("getaddrinfo");
+ return EXIT_FAILURE;
+ }
- if (he != NULL) {
- while (he->h_addr_list[i] != NULL) {
- ip = inet_ntoa (*((struct in_addr *)he->h_addr_list[i]));
- printf ("%s: %s\n", argv[1], ip);
- i++;
+ for (rp = result; rp != NULL; rp = rp->ai_next) {
+ if (rp->ai_family == AF_INET6) {
+ struct sockaddr_in6 *ipv6 = (struct sockaddr_in6 *)rp->ai_addr;
+ addr = &(ipv6->sin6_addr);
+ } else if (rp->ai_family == AF_INET) {
+ struct sockaddr_in *ipv4 = (struct sockaddr_in *)rp->ai_addr;
+ addr = &(ipv4->sin_addr);
+ }
+ if (addr != NULL) {
+ if (inet_ntop (rp->ai_family, addr, ip, sizeof (ip)) != NULL)
+ printf ("%s: %s\n", argv[1], ip);
}
}
+ if (result != NULL)
+ freeaddrinfo (result);
+
return EXIT_SUCCESS;
}