From 66c56cb835dc4d9a5a0fecfd9212635a910d7a58 Mon Sep 17 00:00:00 2001 From: Christopher Dykes Date: Thu, 11 Aug 2016 14:26:41 -0700 Subject: [PATCH] Adjust the AsyncSocket TestServer to work with Winsock Summary: Winsock doesn't let you listen to a socket if it hasn't been bound to anything, so bind it to the port first. TestServer was also never closing the file descriptor, causing the socket to leak. Reviewed By: yfeldblum Differential Revision: D3698467 fbshipit-source-id: cca415143009fbee99ebf94d7f46aedc9c59191d --- folly/io/async/test/AsyncSocketTest.h | 32 +++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/folly/io/async/test/AsyncSocketTest.h b/folly/io/async/test/AsyncSocketTest.h index d57080a9..7795792f 100644 --- a/folly/io/async/test/AsyncSocketTest.h +++ b/folly/io/async/test/AsyncSocketTest.h @@ -227,6 +227,32 @@ class TestServer { folly::detail::tfo_enable(fd_, 100); #endif } + + struct addrinfo hints, *res; + memset(&hints, 0, sizeof(hints)); + hints.ai_family = AF_INET; + hints.ai_socktype = SOCK_STREAM; + hints.ai_flags = AI_PASSIVE; + + if (getaddrinfo(nullptr, "0", &hints, &res)) { + throw folly::AsyncSocketException( + folly::AsyncSocketException::INTERNAL_ERROR, + "Attempted to bind address to socket with " + "bad getaddrinfo", + errno); + } + + SCOPE_EXIT { + freeaddrinfo(res); + }; + + if (bind(fd_, res->ai_addr, res->ai_addrlen)) { + throw folly::AsyncSocketException( + folly::AsyncSocketException::INTERNAL_ERROR, + "failed to bind to async server socket for port 10", + errno); + } + if (listen(fd_, 10) != 0) { throw folly::AsyncSocketException( folly::AsyncSocketException::INTERNAL_ERROR, @@ -240,6 +266,12 @@ class TestServer { address_.setFromIpPort("127.0.0.1", address_.getPort()); } + ~TestServer() { + if (fd_ != -1) { + close(fd_); + } + } + // Get the address for connecting to the server const folly::SocketAddress& getAddress() const { return address_; -- 2.34.1