From 4727d08822907bcdd9873d2f57ef1ed88f251b02 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?St=C3=A9phane=20Lesimple?= Date: Wed, 10 Oct 2018 00:09:15 +0200 Subject: [PATCH] Fix segfault in SpeedTestClient::mkSocket (#14) 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. --- SpeedTestClient.cpp | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/SpeedTestClient.cpp b/SpeedTestClient.cpp index fa58697..017a925 100644 --- a/SpeedTestClient.cpp +++ b/SpeedTestClient.cpp @@ -188,9 +188,11 @@ 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; } @@ -198,7 +200,7 @@ bool SpeedTestClient::mkSocket() { 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(portno));