dnsresolve.c
author Markus Bröker <mbroeker@largo.dyndns.tv>
Fri, 19 Nov 2010 16:43:20 +0100
changeset 161 36f763c8ab16
parent 154 142730cfecee
permissions -rw-r--r--
spell checking: 'cannot set the limit' sounds better... committer: Markus Bröker <mbroeker@largo.homelinux.org>

/**
 * dnsresolve.c
 * Copyright (C) 2008 Markus Broeker
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>

int main (int argc, char **argv)
{
    struct addrinfo hints;
    struct addrinfo *result, *rp;

    void *addr = NULL;
    char ip[INET6_ADDRSTRLEN];

    if (argc != 2) {
        fprintf (stderr, "Usage: %s <hostname>\n", argv[0]);
        return EXIT_FAILURE;
    }

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

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