From: Naizhi Li Date: Fri, 14 Aug 2015 20:16:53 +0000 (-0700) Subject: Allow AysncUDPSocket to work without SO_REUSEADDR flag X-Git-Tag: v0.54.0~6 X-Git-Url: http://demsky.eecs.uci.edu/git/?a=commitdiff_plain;h=e71c842cc8fa98a0362c3be418646e3af1297495;p=folly.git Allow AysncUDPSocket to work without SO_REUSEADDR flag 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 --- diff --git a/folly/io/async/AsyncUDPSocket.cpp b/folly/io/async/AsyncUDPSocket.cpp index 1364ed3f..2101dea2 100644 --- a/folly/io/async/AsyncUDPSocket.cpp +++ b/folly/io/async/AsyncUDPSocket.cpp @@ -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_) { diff --git a/folly/io/async/AsyncUDPSocket.h b/folly/io/async/AsyncUDPSocket.h index 35d8373a..b8b167d4 100644 --- a/folly/io/async/AsyncUDPSocket.h +++ b/folly/io/async/AsyncUDPSocket.h @@ -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}; };