c gethostbyname函数使用

1. 使用gethostbyname(char*)函数,拿到struct hostent

2. 使用inet_ntop()转换成ip地址

#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <stdlib.h>
#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>



int main(int argc, char **argv) {
    char *hostname="www.baidu.com";
    struct hostent *hptr;

    if ((hptr = gethostbyname(hostname)) == NULL) {
        printf("gethotbyname error\n");
        return 1;
    }

    printf("offecial hostname:%s\n", hptr->h_name);
    char **aliasPtrList = hptr->h_aliases;
    for (; *aliasPtrList != NULL; aliasPtrList++)
        printf("alias:%s\n", *aliasPtrList);
    char **addressList = hptr->h_addr_list;
    char addressContent[32];
    switch (hptr->h_addrtype) {
        case AF_INET:
        case AF_INET6:
            for(; *addressList != NULL; addressList++) {
                printf("address:%s\n", inet_ntop(hptr->h_addrtype, hptr, addressContent, sizeof(addressContent)));
            }
            printf("first address:%s\n", inet_ntop(hptr->h_addrtype, hptr, addressContent, sizeof(addressContent)));
            break;
        default:
            printf("unkown address type\n");
    }


    return 0;
}

  

猜你喜欢

转载自www.cnblogs.com/luckygxf/p/12313573.html