域名解析

在/etc/hosts中已经设置了ip与域名的映射关系,通过域名解析函数进行解析(主机名,别名,协议类型,网络地址大小,指向网络IP地址指针等)

部分解析函数:

#include<netdb.h>

struct hostent gethostbyname(const char *hostname);  无法解析IPV6地址,在多线程中会有问题

struct hostent gethostend(void);

 

----------------------------

#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>

void out_addr(struct hostent *h)
{
    printf("hostname: %s\n",h->h_name);
    printf("addrtype: %s\n",
            h->h_addrtype == AF_INET? "IPV4":"IPV6");
    char ip[16];
    memset(ip,0,sizeof(ip));
    inet_ntop(h->h_addrtype,h->h_addr_list[0],ip,sizeof(ip));
    printf("ip address:%s\n",ip);
    
    int i = 0;
    while(h->h_aliases[i] != NULL)
    {
        printf("aliase: %s\n",h->h_aliases[i]);
    }
}

int main(int argc,char *argv[])
{
        if(argc < 2)
        {
            fprintf(stderr,"usage: %s host\n",argv[0]);
            exit(1);
        }
        struct hostent *h;
        while((h=gethostent)!= NULL)
        {
            if(!strcmp(argv[1],h->h_name))
            {
                out_addr(h);
                exit(0);
            }
            else
            {
                int i=0;
                while(h->h_aliases[i] != NULL)
                {
                    if(!strcmp(argv[1],h->h_aliases[i]))
                    {
                        out_addr(h);
                        exit(0);
                    }
                    i++;
                }
            }
        }
        endhostent();
        printf("no %s exist\n",argv[1]);
        
        return 0;
}






 

posted @ 2017-03-05 20:17  lvdh1314  阅读(149)  评论(0编辑  收藏  举报