I would like to create an application that serves web pages internally and can be run in multiple instances on the same machine. To do so, I would like to create an H
Here's an answer, derived from Snooganz's answer. It avoids the race condition between testing for availability, and later binding.
public static bool TryBindListenerOnFreePort(out HttpListener httpListener, out int port)
{
// IANA suggested range for dynamic or private ports
const int MinPort = 49215;
const int MaxPort = 65535;
for (port = MinPort; port < MaxPort; port++)
{
httpListener = new HttpListener();
httpListener.Prefixes.Add($"http://localhost:{port}/");
try
{
httpListener.Start();
return true;
}
catch
{
// nothing to do here -- the listener disposes itself when Start throws
}
}
port = 0;
httpListener = null;
return false;
}
On my machine this method takes 15ms on average, which is acceptable for my use case. Hope this helps someone else.