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

后端 未结 7 1482
广开言路
广开言路 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:33

    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.

提交回复
热议问题