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

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

    TcpListener will find a random un-used port to listen on if you bind to port 0.

    public static int GetRandomUnusedPort()
    {
        var listener = new TcpListener(IPAddress.Any, 0);
        listener.Start();
        var port = ((IPEndPoint)listener.LocalEndpoint).Port;
        listener.Stop();
        return port;
    }
    

提交回复
热议问题