From 3276e1c754ec80742db5f2a548d584aa5a31baad Mon Sep 17 00:00:00 2001 From: IronsDu Date: Wed, 15 Feb 2023 20:21:13 +0800 Subject: [PATCH] Fix/win32 reuseaddress (#139) * fix reuse address bug under windows platform. * fix reuse address bug under windows platform. --------- Co-authored-by: irons.du --- include/brynet/net/SocketLibFunction.hpp | 48 +++++++++++++++++++----- 1 file changed, 39 insertions(+), 9 deletions(-) diff --git a/include/brynet/net/SocketLibFunction.hpp b/include/brynet/net/SocketLibFunction.hpp index 7a18161..cae95ba 100644 --- a/include/brynet/net/SocketLibFunction.hpp +++ b/include/brynet/net/SocketLibFunction.hpp @@ -81,16 +81,50 @@ static int SocketSetRecvSize(BrynetSocketFD fd, int rd_size) return ::setsockopt(fd, SOL_SOCKET, SO_RCVBUF, (const char*) &rd_size, sizeof(rd_size)); } +static int SocketSetReuseAddr(BrynetSocketFD fd) +{ +#ifdef BRYNET_PLATFORM_WINDOWS + BOOL enable = true; + return ::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*) &enable, sizeof(enable)); +#else + int enable = 1; + return ::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)); +#endif +} + +static int SocketDisableReuseAddr(BrynetSocketFD fd) +{ +#ifdef BRYNET_PLATFORM_WINDOWS + BOOL enable = false; + return ::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*) &enable, sizeof(enable)); +#else + int enable = 0; + return ::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)); +#endif +} + static int SocketSetReusePort(BrynetSocketFD fd) { #ifdef BRYNET_PLATFORM_WINDOWS - return 0; + BOOL enable = true; + return ::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*) &enable, sizeof(enable)); #else int enable = 1; return ::setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &enable, sizeof(enable)); #endif } +static int SocketDisableReusePort(BrynetSocketFD fd) +{ +#ifdef BRYNET_PLATFORM_WINDOWS + BOOL enable = false; + return ::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, (char*) &enable, sizeof(enable)); +#else + int enable = 0; + return ::setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &enable, sizeof(enable)); +#endif +} + static BrynetSocketFD SocketCreate(int af, int type, int protocol) { return ::socket(af, type, protocol); @@ -193,19 +227,15 @@ static BrynetSocketFD Listen(bool isIPV6, const char* ip, int port, int back_num ptonResult = inet_pton(AF_INET, ip, &ip4Addr.sin_addr) > 0; } - const int reuseaddr_value = 1; - if (!ptonResult || - ::setsockopt(socketfd, - SOL_SOCKET, - SO_REUSEADDR, - (const char*) &reuseaddr_value, - sizeof(int)) < 0) + // default aneble SO_REUSEADDR + if (!ptonResult || SocketSetReuseAddr(socketfd) < 0) { SocketClose(socketfd); return BRYNET_INVALID_SOCKET; } - if (enabledReusePort && SocketSetReusePort(socketfd) < 0) + if ((enabledReusePort && SocketSetReusePort(socketfd) < 0) || + (!enabledReusePort && SocketDisableReusePort(socketfd) < 0)) { SocketClose(socketfd); return BRYNET_INVALID_SOCKET;