Skip to content

Instantly share code, notes, and snippets.

@bronumski
Last active August 5, 2020 21:11
Show Gist options
  • Save bronumski/5247135 to your computer and use it in GitHub Desktop.
Save bronumski/5247135 to your computer and use it in GitHub Desktop.
Gets the next available port number
public static class TcpPort
{
public static int NextFreePort()
{
var l = new TcpListener(IPAddress.Loopback, 0);
try
{
l.Start();
return ((IPEndPoint)l.LocalEndpoint).Port;
}
finally
{
l.Stop();
}
}
}
open System.Net
open System.Net.Sockets
let getFreePort = fun _ ->
let l = new TcpListener(IPAddress.Loopback, 0)
let port =
try
l.Start()
let endpoint = l.LocalEndpoint :?> IPEndPoint
endpoint.Port
finally
l.Stop()
port
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment