Linux网络程序设计之使用gethostbyname和gethostbyaddr函数
在已知亚马逊主站域名(www.amazon.com)的前提下,通过调用gethostbyname( )函数,来获取IP地址;通过该IP地址调用gethostbyaddr( )来获取亚马逊主站的主机信息,并打印到控制台
#include<string.h> #include<stdio.h> #include<arpa/inet.h> #include<sys/socket.h> int main() { char host[]="www.amazon.com"; struct hostent *ht1=NULL,*ht2=NULL; char str[30]; ht1=hethostbyname(host); if(ht1) { printf("ip:%s\n",inet_ntop(ht1->h_addrtype,ht1->h_addr_list[0],str,30)); } else { printf("error!\n"); } int type=ht1->h_addrtype; ht2=gethostbyaddr(str,30,type); if(ht2) { printf("name:%s\n",ht2->h_name); printf("length:%d\n",ht2->h_length); for(int i=0;;i++) { if(ht2->h_aliases[i]!=NULL){ printf("alias %d:%s\n",i,ht2->h_aliases[i]); } else { break; } } } else { printf("error2!\n"); } return 0; }
posted on 2020-05-07 10:04 BUTTERSCOTCH 阅读(418) 评论(0) 编辑 收藏 举报