Skip to content

Commit

Permalink
Fix/win32 reuseaddress (#139)
Browse files Browse the repository at this point in the history
* fix reuse address bug under windows platform.

* fix reuse address bug under windows platform.

---------

Co-authored-by: irons.du <irons.du@gmai..com>
  • Loading branch information
IronsDu and irons.du authored Feb 15, 2023
1 parent 9f3dacc commit 3276e1c
Showing 1 changed file with 39 additions and 9 deletions.
48 changes: 39 additions & 9 deletions include/brynet/net/SocketLibFunction.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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;
Expand Down

0 comments on commit 3276e1c

Please sign in to comment.