如何从具有顶级域名的域名中获取IP地址?在此示例中,获取google.com的IP。并且如果可能的话,以正确格式在IPv6中显示。
这是我到目前为止尝试过的:
#include <netdb.h>
using namespace std;
int main()
{
struct hostent* myHostent;
myHostent = gethostbyname("google.com");
cout<<myHostent <<"\n";
//output is a hex code
cout<<myHostent->h_name<<"\n";
//output is google.com
cout<<myHostent->h_aliases;
//output is a hex code
}
域的IP地址(是复数,可以有多个,可以是1以上)在hostent::h_addr_list
字段中,而不是在hostent::h_aliases
字段中,例如:
int main()
{
hostent* myHostent = gethostbyname("google.com");
if (myHostent == NULL)
{
cerr << "gethostbyname() failed" << "\n";
}
else
{
cout << myHostent->h_name << "\n";
char ip[INET6_ADDRSTRLEN];
for (unsigned int i = 0; myHostent->h_addr_list[i] != NULL; ++i)
{
if (inet_ntop(myHostent->h_addrtype, myHostent->h_addr_list[i], ip, sizeof(ip)))
cout << ip << "\n";
}
}
return 0;
}
也就是说,gethostbyname()
已过时,请改用getaddrinfo()
,例如:
int main()
{
addrinfo hints = {};
addrinfo *res;
hints.ai_flags = AI_CANONNAME;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
int ret = getaddrinfo("google.com", "", &hints, &res);
if (ret != 0)
{
cerr << "getaddrinfo() failed: " << gai_strerror(ret) << "\n";
}
else
{
cout << res->ai_canonname << "\n";
char ip[INET6_ADDRSTRLEN];
for(addrinfo addr = res; addr != NULL; addr = addr->ai_next)
{
switch (addr->ai_family)
{
case AF_INET:
if (inet_ntop(AF_INET, &(reinterpret_cast<sockaddr_in*>(addr->ai_addr)->sin_addr), ip, sizeof(ip)))
cout << ip << "\n";
break;
case AF_INET6:
if (inet_ntop(AF_INET, &(reinterpret_cast<sockaddr_in6*>(addr->ai_addr)->sin6_addr), ip, sizeof(ip)))
cout << ip << "\n";
break;
}
}
freeaddrinfo(res);
}
return 0;
}