#include <stdio.h>
#include <stdlib.h>
#include <netdb.h>
#include <sys/socket.h>
/*原型:
struct hostent *gethostbyname(const char *name); //调用失败,返回 NULL
*/
/*结构:
struct hostent {
char *h_name; //主机的规范名
char **h_aliases; //主机的别名,有的主机有多个,为了记忆
int h_addrtype; //主机的IP类型,AF_INET/AF_INET6
int h_length; //主机IP的长度
char **h_addr_list;//主机的IP地址,可能有多个。注意:网络字节序,打印IP,需要调用inet_ntop()
};*/
int main(int argc, char *argv[]){
char ipstring[20],**alias,**iplist;
struct hostent* host;
if( (host=gethostbyname(argv[1])) == NULL ){
printf("gethostbyname error for host\n");
exit(-1);
}
/*打印主机的规范名*/
printf("official hostname:%s\n", host->h_name);
/*主机可能有多个别名*/
for( alias=host->h_aliases; *alias!=NULL;alias++ ){
printf("alias:%s\n", *alias);
}
/*根据地址类型,将地址打印出来*/
switch(host->h_addrtype){
case AF_INET:
case AF_INET6:
for(iplist = host->h_addr_list;*iplist!=NULL;iplist++){
//const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt) :
//返回值 和dst 相同
inet_ntop(host->h_addrtype, *host->h_addr_list, ipstring, sizeof(ipstring));
printf("address:%s\n", ipstring);
}
break;
default:
printf("unknow address\n");
}
return 0;
}
#include <stdlib.h>
#include <netdb.h>
#include <sys/socket.h>
/*原型:
struct hostent *gethostbyname(const char *name); //调用失败,返回 NULL
*/
/*结构:
struct hostent {
char *h_name; //主机的规范名
char **h_aliases; //主机的别名,有的主机有多个,为了记忆
int h_addrtype; //主机的IP类型,AF_INET/AF_INET6
int h_length; //主机IP的长度
char **h_addr_list;//主机的IP地址,可能有多个。注意:网络字节序,打印IP,需要调用inet_ntop()
};*/
int main(int argc, char *argv[]){
char ipstring[20],**alias,**iplist;
struct hostent* host;
if( (host=gethostbyname(argv[1])) == NULL ){
printf("gethostbyname error for host\n");
exit(-1);
}
/*打印主机的规范名*/
printf("official hostname:%s\n", host->h_name);
/*主机可能有多个别名*/
for( alias=host->h_aliases; *alias!=NULL;alias++ ){
printf("alias:%s\n", *alias);
}
/*根据地址类型,将地址打印出来*/
switch(host->h_addrtype){
case AF_INET:
case AF_INET6:
for(iplist = host->h_addr_list;*iplist!=NULL;iplist++){
//const char *inet_ntop(int af, const void *src, char *dst, socklen_t cnt) :
//返回值 和dst 相同
inet_ntop(host->h_addrtype, *host->h_addr_list, ipstring, sizeof(ipstring));
printf("address:%s\n", ipstring);
}
break;
default:
printf("unknow address\n");
}
return 0;
}
结果(多次运行,结果不同,但IP 都是正确的,只是不能同时显示出来(Why?)):
$ ./a.out www.baidu.com
official hostname:www.a.shifen.com
alias:www.baidu.com
address:111.13.100.92
address:111.13.100.92
$ ./a.out www.baidu.com
official hostname:www.a.shifen.com
alias:www.baidu.com
address:111.13.100.91
address:111.13.100.91
$ ./a.out www.baidu.com
official hostname:www.a.shifen.com
alias:www.baidu.com
address:111.13.100.92
address:111.13.100.92