Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[FIX] fix InetAddress compile, and use getaddrinfo instead of gethostbyname_r #709

Open
wants to merge 2 commits into
base: cpp17
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 23 additions & 21 deletions muduo/net/InetAddress.cc
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
#include <muduo/net/SocketsOps.h>

#include <netdb.h>
#include <stddef.h>
#include <netinet/in.h>
#include <sys/socket.h>

// INADDR_ANY use (type)value casting.
#pragma GCC diagnostic ignored "-Wold-style-cast"
Expand Down Expand Up @@ -113,29 +115,29 @@ uint16_t InetAddress::toPort() const
return sockets::networkToHost16(portNetEndian());
}

static __thread char t_resolveBuffer[64 * 1024];

bool InetAddress::resolve(StringArg hostname, InetAddress* out)
{
bool InetAddress::resolve(StringArg hostname, InetAddress *out) {
assert(out != NULL);
struct hostent hent;
struct hostent* he = NULL;
int herrno = 0;
memZero(&hent, sizeof(hent));

int ret = gethostbyname_r(hostname.c_str(), &hent, t_resolveBuffer, sizeof t_resolveBuffer, &he, &herrno);
if (ret == 0 && he != NULL)
{
assert(he->h_addrtype == AF_INET && he->h_length == sizeof(uint32_t));
out->addr_.sin_addr = *reinterpret_cast<struct in_addr*>(he->h_addr);
return true;
// NOTE: we only consider ipv4 addrs
struct addrinfo hints {};
struct addrinfo *res{};
struct addrinfo *p{};
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;

int ret = getaddrinfo(hostname.c_str(), nullptr, &hints, &res);
if (ret != 0) {
LOG_SYSERR << "InetAddress::resolve" << gai_strerror(ret);
return false;
}
else
{
if (ret)
{
LOG_SYSERR << "InetAddress::resolve";

for (p = res; p != nullptr; p = p->ai_next) {
if (p->ai_family == AF_INET) {
struct sockaddr_in *ipv4 = reinterpret_cast<sockaddr_in *>(p->ai_addr);
out->addr_.sin_addr = ipv4->sin_addr;
freeaddrinfo(res);
return true;
}
return false;
}
freeaddrinfo(res);
return false;
}