Adjust the AsyncSocket TestServer to work with Winsock
authorChristopher Dykes <cdykes@fb.com>
Thu, 11 Aug 2016 21:26:41 +0000 (14:26 -0700)
committerFacebook Github Bot 7 <facebook-github-bot-7-bot@fb.com>
Thu, 11 Aug 2016 21:39:04 +0000 (14:39 -0700)
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

index d57080a90278de4f03068fe2b8949d5c34c7d094..7795792f84934056e43efda9dbaa810ddba6f980 100644 (file)
@@ -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_;