首页 > 其他 > 详细

c gethostbyname函数使用

时间:2020-02-15 21:05:13      阅读:76      评论:0      收藏:0      [点我收藏+]

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;
}

  技术分享图片

 

c gethostbyname函数使用

原文:https://www.cnblogs.com/luckygxf/p/12313573.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!