Skip to content

Commit

Permalink
Fix segfault in SpeedTestClient::mkSocket (taganaka#14)
Browse files Browse the repository at this point in the history
Replace the use of the non-reentrant gethostbyname() function by the
thread-safe gethostbyname_r() one. Those segfaults are more likely
to happen with a high number of threads, which is the case when testing
high-bandwidth connections.

This is also dependent on the libc/compiler, as the program started to
segfault ~100% of the time when attempting to test a Fiber connection
with the program compiled under gcc7 where the same program compiled
under gcc5 was segfaulting ~%5 of the time.
  • Loading branch information
speed47 authored and taganaka committed Oct 9, 2018
1 parent ea36958 commit 4727d08
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions SpeedTestClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -188,17 +188,19 @@ bool SpeedTestClient::mkSocket() {
}

auto hostp = hostport();

struct hostent *server = gethostbyname(hostp.first.c_str());
if (server == nullptr) {
struct hostent server;
char tmpbuf[BUFSIZ];
struct hostent *result;
int errnop;
if (gethostbyname_r(hostp.first.c_str(), &server, (char *)&tmpbuf, BUFSIZ, &result, &errnop)) {
return false;
}

int portno = hostp.second;
struct sockaddr_in serv_addr{};
memset(&serv_addr, 0, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
memcpy(&serv_addr.sin_addr.s_addr, server->h_addr, (size_t)server->h_length);
memcpy(&serv_addr.sin_addr.s_addr, server.h_addr, (size_t)server.h_length);

serv_addr.sin_port = htons(static_cast<uint16_t>(portno));

Expand Down

0 comments on commit 4727d08

Please sign in to comment.