From 9d235c31a74b0151a49c6b09296e94017b592d43 Mon Sep 17 00:00:00 2001 From: Johnny Ho Date: Wed, 27 Jul 2016 02:35:02 -0400 Subject: [PATCH] Use getaddrinfo instead of gethostbyname for thread safety --- src/socket.h | 15 ++++++++++----- 1 file changed, 10 insertions(+), 5 deletions(-) diff --git a/src/socket.h b/src/socket.h index f605ab028..83d28e88c 100644 --- a/src/socket.h +++ b/src/socket.h @@ -57,12 +57,17 @@ struct SockAddr { * \param port the port of address */ inline void Set(const char *host, int port) { - hostent *hp = gethostbyname(host); - Check(hp != NULL, "cannot obtain address of %s", host); - memset(&addr, 0, sizeof(addr)); - addr.sin_family = AF_INET; + addrinfo hints; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET; + hints.ai_protocol = SOCK_STREAM; + addrinfo *res = NULL; + int sig = getaddrinfo(host, NULL, &hints, &res); + Check(sig == 0 && res != NULL, "cannot obtain address of %s", host); + Check(res->ai_family == AF_INET, "Does not support IPv6"); + memcpy(&addr, res->ai_addr, res->ai_addrlen); addr.sin_port = htons(port); - memcpy(&addr.sin_addr, hp->h_addr_list[0], hp->h_length); + freeaddrinfo(res); } /*! \brief return port of the address*/ inline int port(void) const {