Find the next TCP port in .NET

前端 未结 8 815
别跟我提以往
别跟我提以往 2020-11-29 19:40

I want to create a new net.tcp://localhost:x/Service endpoint for a WCF service call, with a dynamically assigned new open TCP port.

I know that TcpClient will assig

8条回答
  •  佛祖请我去吃肉
    2020-11-29 20:16

    Here is what I was looking for:

    static int FreeTcpPort()
    {
      TcpListener l = new TcpListener(IPAddress.Loopback, 0);
      l.Start();
      int port = ((IPEndPoint)l.LocalEndpoint).Port;
      l.Stop();
      return port;
    }
    

提交回复
热议问题