Skip to main content

C# function that returns a random unused TCP port.

private static int GetRandomUnusedPort()
{
    var listener = new TcpListener(IPAddress.Loopback, 0);
    listener.Start();

    var port = ((IPEndPoint)listener.LocalEndpoint).Port;
    listener.Stop();

    return port;
}