getaddrinfo 进行域名解析 ipv4 and ipv6

/*
 * =====================================================================================
 *
 *       Filename:  getaddrinfo.c
 *
 *    Description: 
 *
 *        Version:  1.0
 *        Created:  03/03/2011 05:29:51 PM
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (),
 *        Company: 
 *
 * =====================================================================================
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
 
#ifndef   NI_MAXHOST
#define   NI_MAXHOST 1025
#endif
 
char *get_ip_str(const struct sockaddr *sa, char *s, size_t maxlen)
{
    switch(sa->sa_family) {
        case AF_INET:
            inet_ntop(AF_INET, &(((struct sockaddr_in *)sa)->sin_addr),
                    s, maxlen);
            break;

        case AF_INET6:
            inet_ntop(AF_INET6, &(((struct sockaddr_in6 *)sa)->sin6_addr),
                    s, maxlen);
            break;

        default:
            strncpy(s, "Unknown AF", maxlen);
            return NULL;
    }

    return s;
}

int main(void)
{
    struct addrinfo *result;
    struct addrinfo *res;
    struct sockaddr_in  *sin;
    struct sockaddr_in6 *sin6;
    char   buf[128];
    int error;
 
    /* resolve the domain name into a list of addresses */
    error = getaddrinfo("www.baidu.com", NULL, NULL, &result);
    if (error != 0)
    {  
        fprintf(stderr, "error in getaddrinfo: %s/n", gai_strerror(error));
        return EXIT_FAILURE;
    }  
 
    printf("get a correct result/n");
    for (res = result; res != NULL; res = res->ai_next)
    {  
        get_ip_str(res->ai_addr, buf, 128);
        printf("%s/n", buf);
    }

    /* loop over all returned results and do inverse lookup */
    for (res = result; res != NULL; res = res->ai_next)
    {  
        char hostname[NI_MAXHOST] = "";
 
        error = getnameinfo(res->ai_addr, res->ai_addrlen, hostname, NI_MAXHOST, NULL, 0, 0);
        if (error != 0)
        {
            fprintf(stderr, "error in getnameinfo: %s/n", gai_strerror(error));
            continue;
        }
        if (*hostname != '/0')
            printf("hostname: %s/n", hostname);
    }  
 
    freeaddrinfo(result);
    return EXIT_SUCCESS;
}

你可能感兴趣的:(struct,list,gcc,null,domain,compiler)