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
Since you are using an HttpListener (and therefore TCP connections) you can get a list of active TCP listeners using GetActiveTcpListeners
method of the IPGlobalProperties
object and inspect their Port
property.
The possible solution may look like this:
private static bool TryGetUnusedPort(int startingPort, ref int port)
{
var listeners = IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners();
for (var i = startingPort; i <= 65535; i++)
{
if (listeners.Any(x => x.Port == i)) continue;
port = i;
return true;
}
return false;
}
This code will find first unused port beginning from the startingPort
port number and return true
. In case all ports are already occupied (which is very unlikely) the method returns false
.
Also keep in mind the possibility of a race condition that may happen when some other process takes the found port before you do.