1. gethostbyname函数
#include <netdb.h>
#include <arpa/inet.h>
#include <iostream>
using namespace std;
int main()
{
struct hostent *hptr;
char szIP[64];
hptr = gethostbyname("www.baidu.com");
if(hptr == nullptr){
cout<<"gethostbyname error"<<endl;
}
cout<<"official hostname: "<<hptr->h_name<<endl;
for(char** pptr=hptr->h_aliases; *pptr!=nullptr; pptr++){
cout<<" alias: "<<*pptr<<endl;
}
if(hptr->h_addrtype == AF_INET){
cout<<"ipv4"<<endl;
for(char** pptr=hptr->h_addr_list; *pptr!=nullptr; pptr++){
//cout<<"ip: "<<*pptr<<endl;
cout<<"ip: "<<inet_ntop(hptr->h_addrtype, *pptr, szIP, sizeof(szIP))<<endl;
}
}
return 0;
}
2. 结果
ld@ld-pc:~/workspace$ ./gethostbyname_demo
official hostname: www.a.shifen.com
alias: www.baidu.com
ipv4
ip: 183.232.231.172
ip: 183.232.231.173
3. nslookup命令
nslookup - query Internet name servers interactively
ld@ld-pc:~/workspace$ nslookup www.baidu.com
Server: 127.0.1.1
Address: 127.0.1.1#53
Non-authoritative answer:
www.baidu.com canonical name = www.a.shifen.com.
Name: www.a.shifen.com
Address: 183.232.231.172
Name: www.a.shifen.com
Address: 183.232.231.173