易丰科技
标题:
C# 找到机器上可用的 Port
[打印本页]
作者:
Calvin
时间:
2011-10-16 11:59
标题:
C# 找到机器上可用的 Port
加入引用:
using System.Net.NetworkInformation;
using System.Net;
复制代码
获得可以用的 Port
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();
}
复制代码
另一种更好的方法:
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
private string GetOpenPort()
{
const int PortStartIndex = 1000;
const int PortEndIndex = 2000;
IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] tcpEndPoints = properties.GetActiveTcpListeners();
IEnumerable<int> query =
(from n in tcpEndPoints.OrderBy(n => n.Port)
where (n.Port >= PortStartIndex) && (n.Port <= PortEndIndex)
select n.Port).ToArray().Distinct();
int i = PortStartIndex;
foreach (int p in query)
{
if (p != i)
{
break;
}
i++;
}
return i > PortEndIndex ? "0": i.ToString();
}
复制代码
欢迎光临 易丰科技 (http://forum.yftek.com/)
Powered by Discuz! X3