Skip to content

Commit

Permalink
Auto-enable SO_REUSE_UNICASTPORT for ConnectEx (#54903)
Browse files Browse the repository at this point in the history
Fixes #48219.
  • Loading branch information
antonfirsov authored Jul 8, 2021
1 parent c7ffa32 commit 30d770d
Showing 1 changed file with 25 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -235,9 +235,34 @@ partial void WildcardBindForConnectIfNecessary(AddressFamily addressFamily)

if (NetEventSource.Log.IsEnabled()) NetEventSource.Info(this, csep.IPEndPoint);

if (_socketType == SocketType.Stream && _protocolType == ProtocolType.Tcp)
{
EnableReuseUnicastPort();
}

DoBind(csep.IPEndPoint, csep.SocketAddress);
}

private void EnableReuseUnicastPort()
{
// By enabling SO_REUSE_UNICASTPORT, we defer actual port allocation until the ConnectEx call,
// so it can bind to ports from the Windows auto-reuse port range, if configured by an admin.
// The socket option is supported on Windows 10+, we are ignoring the SocketError in case setsockopt fails.
int optionValue = 1;
SocketError error = Interop.Winsock.setsockopt(
_handle,
SocketOptionLevel.Socket,
SocketOptionName.ReuseUnicastPort,
ref optionValue,
sizeof(int));

if (NetEventSource.Log.IsEnabled() && error != SocketError.Success)
{
error = SocketPal.GetLastSocketError();
NetEventSource.Info($"Enabling SO_REUSE_UNICASTPORT failed with error code: {error}");
}
}

internal unsafe bool ConnectEx(SafeSocketHandle socketHandle,
IntPtr socketAddress,
int socketAddressSize,
Expand Down

0 comments on commit 30d770d

Please sign in to comment.