Find the next TCP port in .NET

前端 未结 8 773
别跟我提以往
别跟我提以往 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:30

    Here's a more abbreviated way to implement this if you want to find the next available TCP port within a given range:

    private int GetNextUnusedPort(int min, int max)
    {
        if (max < min)
            throw new ArgumentException("Max cannot be less than min.");
    
        var ipProperties = IPGlobalProperties.GetIPGlobalProperties();
    
        var usedPorts =
            ipProperties.GetActiveTcpConnections()
                .Where(connection => connection.State != TcpState.Closed)
                .Select(connection => connection.LocalEndPoint)
                .Concat(ipProperties.GetActiveTcpListeners())
                .Concat(ipProperties.GetActiveUdpListeners())
                .Select(endpoint => endpoint.Port)
                .ToArray();
    
        var firstUnused =
            Enumerable.Range(min, max - min)
                .Where(port => !usedPorts.Contains(port))
                .Select(port => new int?(port))
                .FirstOrDefault();
    
        if (!firstUnused.HasValue)
            throw new Exception($"All local TCP ports between {min} and {max} are currently in use.");
    
        return firstUnused.Value;
    }
    
    0 讨论(0)
  • 2020-11-29 20:31

    I found the following code from Selenium.WebDriver DLL

    Namespace: OpenQA.Selenium.Internal

    Class: PortUtility

    public static int FindFreePort()
    {
        int port = 0;
        Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        try
        {
            IPEndPoint localEP = new IPEndPoint(IPAddress.Any, 0);
            socket.Bind(localEP);
            localEP = (IPEndPoint)socket.LocalEndPoint;
            port = localEP.Port;
        }
        finally
        {
            socket.Close();
        }
        return port;
    }
    
    0 讨论(0)
提交回复
热议问题