How can I create an HttpListener class on a random port in C#?

后端 未结 7 1456
广开言路
广开言路 2020-12-03 16:34

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

相关标签:
7条回答
  • 2020-12-03 17:36

    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.

    0 讨论(0)
提交回复
热议问题