根据域名获取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
");
        return 0;
    }

    printf("hostname:%s
", hptr->h_name);
    
    for(pptr = hptr->h_aliases; *pptr != NULL; pptr++)
        printf(" pptr:%s
",*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
", str);
            }

        break;
    }

    return 0;
}
原文地址:https://www.cnblogs.com/jly594761082/p/10748915.html