Skip to content

Instantly share code, notes, and snippets.

@coenm
Created October 9, 2022 20:21
Show Gist options
  • Select an option

  • Save coenm/2e384c5ed389a376a2bc8fda5b52494d to your computer and use it in GitHub Desktop.

Select an option

Save coenm/2e384c5ed389a376a2bc8fda5b52494d to your computer and use it in GitHub Desktop.
FreePortLocator
using System.Net;
using System.Net.Sockets;
public static class FreePortLocator
{
private static readonly IPEndPoint _defaultLoopbackEndpoint = new(IPAddress.Loopback, port: 0);
public static int GetAvailablePort()
{
using var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.Bind(_defaultLoopbackEndpoint);
return ((IPEndPoint)socket.LocalEndPoint!).Port;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment