Znajdź następny port TCP in.Net

Chcę stworzyć nową sieć.TCP:/ / localhost: x / service endpoint dla wywołania usługi WCF z dynamicznie przypisanym nowym otwartym portem tcp.

Wiem, że TcpClient przypisze Nowy Port po stronie klienta, gdy otworzę połączenie z danym serwerem.

Czy jest prosty sposób na znalezienie następnego otwartego portu TCP w. Net?

Potrzebuję liczby rzeczywistej, aby móc zbudować łańcuch powyżej, 0 nie działa, ponieważ muszę przekazać ten łańcuch do innego procesu, aby móc oddzwonić ten nowy kanał.

Author: TheSeeker, 2008-09-26

6 answers

Oto czego szukałem:

static int FreeTcpPort()
{
  TcpListener l = new TcpListener(IPAddress.Loopback, 0);
  l.Start();
  int port = ((IPEndPoint)l.LocalEndpoint).Port;
  l.Stop();
  return port;
}
 103
Author: TheSeeker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-01 13:16:54

Użyj numeru portu 0. Stos TCP przydzieli następny wolny stos.

 14
Author: Jerub,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-26 06:35:18

Najpierw otwórz port, a następnie podaj poprawny numer portu drugiemu procesowi.

W przeciwnym razie nadal jest możliwe, że inny proces otworzy pierwszy port i nadal masz inny.

 8
Author: jan.vdbergh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-09-26 08:00:45

Jeśli chcesz po prostu podać port startowy i pozwolić mu powrócić do następnego dostępnego portu tcp, użyj kodu w następujący sposób:

public static int GetAvailablePort(int startingPort)
{
    var portArray = new List<int>();

    var properties = IPGlobalProperties.GetIPGlobalProperties();

    // Ignore active connections
    var connections = properties.GetActiveTcpConnections();
    portArray.AddRange(from n in connections
                        where n.LocalEndPoint.Port >= startingPort
                        select n.LocalEndPoint.Port);

    // Ignore active tcp listners
    var endPoints = properties.GetActiveTcpListeners();
    portArray.AddRange(from n in endPoints
                        where n.Port >= startingPort
                        select n.Port);

    // Ignore active udp listeners
    endPoints = properties.GetActiveUdpListeners();
    portArray.AddRange(from n in endPoints
                        where n.Port >= startingPort
                        select n.Port);

    portArray.Sort();

    for (var i = startingPort; i < UInt16.MaxValue; i++)
        if (!portArray.Contains(i))
            return i;

    return 0;
}
 4
Author: zumalifeguard,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-29 03:37:15

Jest to rozwiązanie porównywalne z przyjętą odpowiedzią Theseekera. Chociaż myślę, że jest bardziej czytelny:

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;
        }
    }
 3
Author: Eric Boumendil,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-21 13:55:16

Jeśli chcesz uzyskać wolny port w określonym zakresie inorder, aby użyć go jako lokalnego portu/punktu końcowego:

private int GetFreePortInRange(int PortStartIndex, int PortEndIndex)
    {
        DevUtils.LogDebugMessage(string.Format("GetFreePortInRange, PortStartIndex: {0} PortEndIndex: {1}", PortStartIndex, PortEndIndex));
        try
        {
            IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();

            IPEndPoint[] tcpEndPoints = ipGlobalProperties.GetActiveTcpListeners();
            List<int> usedServerTCpPorts = tcpEndPoints.Select(p => p.Port).ToList<int>();

            IPEndPoint[] udpEndPoints = ipGlobalProperties.GetActiveUdpListeners();
            List<int> usedServerUdpPorts = udpEndPoints.Select(p => p.Port).ToList<int>();

            TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();
            List<int> usedPorts = tcpConnInfoArray.Where(p=> p.State != TcpState.Closed).Select(p => p.LocalEndPoint.Port).ToList<int>();

            usedPorts.AddRange(usedServerTCpPorts.ToArray());
            usedPorts.AddRange(usedServerUdpPorts.ToArray());

            int unusedPort = 0;

            for (int port = PortStartIndex; port < PortEndIndex; port++)
            {
                if (!usedPorts.Contains(port))
                {
                    unusedPort = port;
                    break;
                }
            }
            DevUtils.LogDebugMessage(string.Format("Local unused Port:{0}", unusedPort.ToString()));

            if (unusedPort == 0)
            {
                DevUtils.LogErrorMessage("Out of ports");
                throw new ApplicationException("GetFreePortInRange, Out of ports");
            }

            return unusedPort;
        }
        catch (Exception ex)
        {

            string errorMessage = ex.Message;
            DevUtils.LogErrorMessage(errorMessage);
            throw;
        }
    }



private int GetLocalFreePort()
    {
        int hemoStartLocalPort = int.Parse(DBConfig.GetField("Site.Config.hemoStartLocalPort"));
        int hemoEndLocalPort = int.Parse(DBConfig.GetField("Site.Config.hemoEndLocalPort"));
        int localPort = GetFreePortInRange(hemoStartLocalPort, hemoEndLocalPort);
        DevUtils.LogDebugMessage(string.Format("Local Free Port:{0}", localPort.ToString()));
        return localPort;
    }





public void Connect(string host, int port)
    {
        try
        {
            //Create socket
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

            var localPort = GetLocalFreePort();
            //Create an endpoint for the specified IP on any port
            IPEndPoint bindEndPoint = new IPEndPoint(IPAddress.Any, localPort);

            //Bind the socket to the endpoint
            socket.Bind(bindEndPoint);

            //Connect to host
            socket.Connect(IPAddress.Parse(host), port);                

            socket.Dispose();
        }
        catch (SocketException ex)
        {
            //Get the error message
            string errorMessage = ex.Message;
            DevUtils.LogErrorMessage(errorMessage);
        }
    }


    public void Connect2(string host, int port)
    {
        try
        {
            //Create socket

            var localPort = GetLocalFreePort();
            //Create an endpoint for the specified IP on any port
            IPEndPoint bindEndPoint = new IPEndPoint(IPAddress.Any, localPort);

            var client = new TcpClient(bindEndPoint);
            //client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); //will release port when done   

            //Connect to host
            client.Connect(IPAddress.Parse(host), port);                

            client.Close();             
        }
        catch (SocketException ex)
        {
            //Get the error message
            string errorMessage = ex.Message;
            DevUtils.LogErrorMessage(errorMessage);
        }
    }
 1
Author: yoavs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-17 05:12:09