#include <netdb.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <iostream>
int main(int argc,char* argv[]){
struct hostent* h;
char buf[64];
for(int i = 0;i < argc-1;++i){
h = gethostbyname(argv[i+1]);
if(!h){
std::cout<<"gethostbyname: "<<argv[i]<<" err,"<<hstrerror(h_errno)<<std::endl;
continue;
}
std::cout<<"offical name: "<<h->h_name<<std::endl;
for(int j = 0; h->h_aliases[j];++j){
std::cout<<"aliases name: "<<h->h_aliases[j]<<std::endl;
}
switch(h->h_addrtype){
case AF_INET:
case AF_INET6:{
for(int j = 0;h->h_addr_list[j];++j){
// 网络字节序的ip数值格式转化为字符串,可以执行AF_INET/AF_INET6的转化,(inet_ntoa已经废弃)
inet_ntop(h->h_addrtype,(void*)h->h_addr_list[j],buf,sizeof(buf));
std::cout<<"ip: "<<buf<<std::endl;
}
break;
}
default:
std::cout<<"unknown type;\n";
break;
}
}
return EXIT_SUCCESS;
}
$ gcc main.cpp -o main
$ ./main www.baidu.com
offical name: www.a.shifen.com
aliases name: www.baidu.com
ip: 61.135.169.125
ip: 61.135.169.121