如何从包含顶级域名的域名中获取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
}发布于 2020-02-05 03:43:34
域的IP地址(是复数,可以不止1)在hostent::h_addr_list字段中,而不是在hostent::h_aliases字段中,例如:
int main()
{
hostent* myHostent = gethostbyname("google.com");
if (!myHostent)
{
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)
{
cout << inet_ntop(myHostent->h_addrtype, myHostent->h_addr_list[i], ip, sizeof(ip)) << "\n";
}
}
return 0;
}也就是说,gethostbyname()已弃用,请改用getaddrinfo(),例如:
void* getSinAddr(addrinfo *addr)
{
switch (addr->ai_family)
{
case AF_INET:
return &(reinterpret_cast<sockaddr_in*>(addr->ai_addr)->sin_addr);
case AF_INET6:
return &(reinterpret_cast<sockaddr_in6*>(addr->ai_addr)->sin6_addr);
}
return NULL;
}
int main()
{
addrinfo hints = {};
hints.ai_flags = AI_CANONNAME;
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
addrinfo *res;
int ret = getaddrinfo("google.com", NULL, &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; addr = addr->ai_next)
{
cout << inet_ntop(addr->ai_family, getSinAddr(addr), ip, sizeof(ip)) << "\n";
}
freeaddrinfo(res);
}
return 0;
}https://stackoverflow.com/questions/60064172
复制相似问题