Commit 38a8b5e5 authored by abousselmi's avatar abousselmi

Use getaddrinfo() instaed of gethostbyname()

Like @louisroyer pointed out, gethostbyname() is deprecated and we
should use getaddrinfo() instead.

Note: the default behavior of getaddrinfo() is not the same as
suggested by the man page when hints is set to null. It doesn't
yield IPv6 addresses, and hints.ai_family seems to be set to
AF_INET and not AF_UNSPEC by default.
parent 5d0664c6
......@@ -251,28 +251,39 @@ std::string GetIp6OfInterface(const std::string &ifName)
std::string GetHostByName(const std::string &name)
{
auto* res = gethostbyname(name.c_str());
if (res == nullptr)
return "";
if (res->h_addr_list == nullptr)
struct addrinfo hints = {};
struct addrinfo *res;
hints.ai_family = AF_UNSPEC;
if (getaddrinfo(name.c_str(), NULL, &hints, &res))
return "";
if (res->h_addrtype == AF_INET)
if (res->ai_family == AF_INET)
{
char str[INET_ADDRSTRLEN] = {0};
if (inet_ntop(AF_INET, res->h_addr_list[0], str, INET_ADDRSTRLEN) == nullptr)
if (inet_ntop(AF_INET, &((struct sockaddr_in*)res->ai_addr)->sin_addr, str, INET_ADDRSTRLEN) == nullptr)
{
freeaddrinfo(res);
return "";
}
freeaddrinfo(res);
return std::string{str};
}
else if (res->h_addrtype == AF_INET6)
else if (res->ai_family == AF_INET6)
{
char str[INET6_ADDRSTRLEN] = {0};
if (inet_ntop(AF_INET6, res->h_addr_list[0], str, INET6_ADDRSTRLEN) == nullptr)
if (inet_ntop(AF_INET6, &((struct sockaddr_in6*)res->ai_addr)->sin6_addr, str, INET6_ADDRSTRLEN) == nullptr)
{
freeaddrinfo(res);
return "";
}
freeaddrinfo(res);
return std::string{str};
}
else
{
freeaddrinfo(res);
return "";
}
}
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment