解析域名-笔记

根据域名解析对应IP

#include 
#include 
#include 
#include 
#include 
#include 
#include 

int lookup_host (const char *host)
{
    struct addrinfo hints, *res;
    int errcode;
    char addrstr[100];
    void *ptr;
    
    memset (&hints, 0, sizeof (hints));
    hints.ai_family = PF_UNSPEC;
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags |= AI_CANONNAME;
    
    errcode = getaddrinfo (host, NULL, &hints, &res);
    if (errcode != 0)
    {
        perror ("getaddrinfo");
        return -1;
    }
    
    printf ("Host: %s\n", host);
    while (res)
    {
        inet_ntop (res->ai_family, res->ai_addr->sa_data, addrstr, 100);
        //先判断IPV4 再IPV6
        switch (res->ai_family)
        {
            case AF_INET:
                ptr = &((struct sockaddr_in *) res->ai_addr)->sin_addr;
                break;
            case AF_INET6:
                ptr = &((struct sockaddr_in6 *) res->ai_addr)->sin6_addr;
                break;
        }
        inet_ntop (res->ai_family, ptr, addrstr, 100);
        printf ("IPv%d address: %s (%s)\n", res->ai_family == PF_INET6 ? 6 : 4,
                addrstr, res->ai_canonname);
        res = res->ai_next;
    }
    
    return 0;
}

NSDate *startDate =[NSDate date];
   int re= lookup_host("www.baidu.com");
//查看下解析时间
    NSDate *endDate =[NSDate date];
    NSTimeInterval time = [endDate timeIntervalSinceDate:startDate];
    NSLog(@"-->%lf",time);
解析域名-笔记_第1张图片
测试结果.png

你可能感兴趣的:(解析域名-笔记)