private string GetOpenPort()

{

int PortStartIndex = 1000;

int PortEndIndex = 2000;

IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();

IPEndPoint[] tcpEndPoints = properties.GetActiveTcpListeners();

List<int> usedPorts = tcpEndPoints.Select(p => p.Port).ToList<int>();

int unusedPort = 0;

for (int port = PortStartIndex; port < PortEndIndex; port++)

{

if (!usedPorts.Contains(port))

{

unusedPort = port;

break;

}

}

return unusedPort.ToString();

}

Advertisements