CSharpUtils.Net.NetworkUtilities.GetAvailableTcpPort C# (CSharp) Метод

GetAvailableTcpPort() публичный статический Метод

public static GetAvailableTcpPort ( ushort StartingPort = 10101 ) : ushort
StartingPort ushort
Результат ushort
		public static ushort GetAvailableTcpPort(ushort StartingPort = 10101)
		{
			var IsPortBusy = new Dictionary<ushort, bool>();

			foreach (var TcpConnectionInfo in IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpConnections())
			{
				IsPortBusy[(ushort)TcpConnectionInfo.LocalEndPoint.Port] = true;
				/*
				Console.WriteLine(
					"{0} -> {1} :: {2}",
					tcpi.LocalEndPoint,
					tcpi.RemoteEndPoint,
					Enum.GetName(typeof(TcpState), tcpi.State)
				);
				*/
			}

			for (int Port = StartingPort; Port < UInt16.MaxValue; Port++)
			{
				if (!IsPortBusy.ContainsKey((ushort)Port))
				{
					var TestTcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), (ushort)Port);
					try
					{
						TestTcpListener.Start();

						return (ushort)Port;
					}
					finally
					{
						TestTcpListener.Stop();
					}
				}
			}

			throw (new KeyNotFoundException("Can't find any free port"));
		}
	}

Usage Example

Пример #1
0
        static public TcpTestServer Create()
        {
            var TcpTestServer = new TcpTestServer();

            {
                var BindIp   = "127.0.0.1";
                var BindPort = NetworkUtilities.GetAvailableTcpPort();
                TcpTestServer.TcpListener = new TcpListener(IPAddress.Parse(BindIp), BindPort);
                TcpTestServer.TcpListener.Start();
                var Event = new ManualResetEvent(false);
                TcpTestServer.TcpListener.BeginAcceptTcpClient((AsyncResult) =>
                {
                    TcpTestServer.LocalTcpClient = TcpTestServer.TcpListener.EndAcceptTcpClient(AsyncResult);
                    Event.Set();
                }, null);
                TcpTestServer.RemoteTcpClient = new TcpClient(BindIp, BindPort);
                Event.WaitOne();
            }
            return(TcpTestServer);
        }
NetworkUtilities