🔖C++C
2017-01-06 22:21阅读: 2352评论: 0推荐: 0

C++:通过gethostbyname函数,根据服务器的域名,获取服务器IP

  本代码的编译环境为MAC,系统版本为10.11.6:

运行下面代码

复制代码
#include <string.h>
#include <netdb.h>
#include <stdio.h>
#include <arpa/inet.h>
int main(int argc, char *argv[]) {
    char host[] = "www.baidu.com";
    struct  hostent *ht = NULL;
    ht = gethostbyname(host);
    if(ht) {
        printf("type:%s\n", ht->h_addrtype == AF_INET ? "AF_INET" : "AF_INET6");
        printf("length:%d\n",ht->h_length);
        for(int i=0; ;i++) {
            if(ht->h_addr_list[i]!=NULL) {
                printf("IP Address :%s\n",inet_ntoa(*((struct in_addr *)ht->h_addr_list[i])));
            }else{
                break;
            }
        }
        for(int j=0; ;j++) {
            if(ht->h_aliases[j]!=NULL) {
                printf("IP:%s\n",ht->h_aliases[j]);
            }else{
                break;
            }
        }
    }
    return 0;
}
复制代码

  EOF

本文作者:方方和圆圆

本文链接:https://www.cnblogs.com/diligenceday/p/6252259.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   方方和圆圆  阅读(2352)  评论(0编辑  收藏  举报
历史上的今天:
2014-01-06 HTML5的拖拽时间 ondragstart

再过一百年, 我会在哪里?

💬
评论
📌
收藏
💗
关注
👍
推荐
🚀
回顶
收起
点击右上角即可分享
微信分享提示