Allow AysncUDPSocket to work without SO_REUSEADDR flag
authorNaizhi Li <naizhi@fb.com>
Fri, 14 Aug 2015 20:16:53 +0000 (13:16 -0700)
committerfacebook-github-bot-9 <folly-bot@fb.com>
Fri, 14 Aug 2015 20:20:27 +0000 (13:20 -0700)
Summary: Today it's hardcoded to use the flag, which could result
in some problem. We should allow callers to choose.

Reviewed By: @djwatson

Differential Revision: D2345036

folly/io/async/AsyncUDPSocket.cpp
folly/io/async/AsyncUDPSocket.h

index 1364ed3fac93deb003a2c75ef07896e22d150838..2101dea2ad335ae29478f51a130c2306fb58934f 100644 (file)
@@ -63,16 +63,18 @@ void AsyncUDPSocket::bind(const folly::SocketAddress& address) {
                               errno);
   }
 
-  // put the socket in reuse mode
-  int value = 1;
-  if (setsockopt(socket,
-                 SOL_SOCKET,
-                 SO_REUSEADDR,
-                 &value,
-                 sizeof(value)) != 0) {
-    throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
-                              "failed to put socket in reuse mode",
-                              errno);
+  if (reuseAddr_) {
+    // put the socket in reuse mode
+    int value = 1;
+    if (setsockopt(socket,
+                  SOL_SOCKET,
+                  SO_REUSEADDR,
+                  &value,
+                  sizeof(value)) != 0) {
+      throw AsyncSocketException(AsyncSocketException::NOT_OPEN,
+                                "failed to put socket in reuse mode",
+                                errno);
+    }
   }
 
   if (reusePort_) {
index 35d8373add6b7ac790cdd6574b83580711e355c4..b8b167d42f2f08927254c1f7f82dc1e382505997 100644 (file)
@@ -150,6 +150,14 @@ class AsyncUDPSocket : public EventHandler {
   void setReusePort(bool reusePort) {
     reusePort_ = reusePort;
   }
+
+  /**
+   * Set SO_REUSEADDR flag on the socket. Default is ON.
+   */
+  void setReuseAddr(bool reuseAddr) {
+    reuseAddr_ = reuseAddr;
+  }
+
  private:
   AsyncUDPSocket(const AsyncUDPSocket&) = delete;
   AsyncUDPSocket& operator=(const AsyncUDPSocket&) = delete;
@@ -172,6 +180,7 @@ class AsyncUDPSocket : public EventHandler {
   // Non-null only when we are reading
   ReadCallback* readCallback_;
 
+  bool reuseAddr_{true};
   bool reusePort_{false};
 };