Find the next TCP port in .NET

前端 未结 8 796
别跟我提以往
别跟我提以往 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条回答
  •  萌比男神i
    2020-11-29 20:24

    It's a solution comparable to the accepted answer of TheSeeker. Though I think it's more readable:

    using System;
    using System.Net;
    using System.Net.Sockets;
    
        private static readonly IPEndPoint DefaultLoopbackEndpoint = new IPEndPoint(IPAddress.Loopback, port: 0);
    
        public static int GetAvailablePort()
        {
            using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                socket.Bind(DefaultLoopbackEndpoint);
                return ((IPEndPoint)socket.LocalEndPoint).Port;
            }
        }
    

提交回复
热议问题