Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Auto-enable SO_REUSE_UNICASTPORT for ConnectEx #54903

Merged
merged 5 commits into from
Jul 8, 2021
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there any test we could/should write to help validate this?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The problem is, it requires an opt-in registry setting.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What about a test that just validates we've configured the socket as best we can? e.g. that we've set SO_REUSE_UNICASTPORT by default?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, that seems worthwhile. @antonfirsov can we add this?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Makes sense, will do.

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