根据域名获取ip地址gethostbyname

#include <sys/socket.h>
#include <stdio.h>
#include <netdb.h>

int main(int argc, char **argv)
{
    char   *ptr, **pptr;
    struct hostent *hptr;
    char   str[32];
    ptr = argv[1];

    hptr = gethostbyname(ptr);
    if(NULL == hptr)
    {
        printf(" gethostbyname error\n");
        return 0;
    }

    printf("hostname:%s\n", hptr->h_name);
    
    for(pptr = hptr->h_aliases; *pptr != NULL; pptr++)
        printf(" pptr:%s\n",*pptr);

    switch(hptr->h_addrtype)
    {
        case AF_INET:
        case AF_INET6:
            pptr=hptr->h_addr_list;
            for(; *pptr!=NULL; pptr++)
            {
                inet_ntop(hptr->h_addrtype, *pptr, str, sizeof(str));
                printf("address: %s\n", str);
            }

        break;
    }

    return 0;
}

 

posted @ 2019-04-22 10:58  星星之火可以燎源  阅读(153)  评论(0编辑  收藏  举报