Skip to content

Instantly share code, notes, and snippets.

@antonfirsov
Last active February 11, 2021 12:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antonfirsov/e86ddc9ac287b7dd63cd85f78ca125f6 to your computer and use it in GitHub Desktop.
Save antonfirsov/e86ddc9ac287b7dd63cd85f78ca125f6 to your computer and use it in GitHub Desktop.
// The workaround is utilizing ConnectCallback, which is a .NET 5+ feature.
// For more info see:
// https://devblogs.microsoft.com/dotnet/net-5-new-networking-improvements/#socketshttphandler-extension-points
public HttpClient CreateHttpClientWithReusePort()
{
SocketsHttpHandler handler = new SocketsHttpHandler
{
ConnectCallback = ReusePortConnectAsync
};
return new HttpClient(handler);
static async ValueTask<Stream> ReusePortConnectAsync(SocketsHttpConnectionContext context, CancellationToken cancellationToken)
{
// Default socket creation logic
Socket socket = new Socket(SocketType.Stream, ProtocolType.Tcp);
socket.NoDelay = true;
// Enable SO_REUSE_UNICASTPORT:
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseUnicastPort, 1);
try
{
await socket.ConnectAsync(context.DnsEndPoint, cancellationToken).ConfigureAwait(false);
return new NetworkStream(socket, ownsSocket: true);
}
catch
{
socket.Dispose();
throw;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment