0
点赞
收藏
分享

微信扫一扫

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

西曲风 2023-01-29 阅读 101

  本代码的编译环境为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;
}

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

  EOF

天道酬勤



举报

相关推荐

0 条评论