最近在搞 socket ,遇到端口占用的问题,程序需要自动检测端口是否占用,提醒服务端的端口更改。
于是,baidu下,发现居然都是,用try——catch 异常去判断是否占用,很是伤心啊。
现贴出下面代码,获取系统在已经使用的端口进行判断。
internal static bool PortInUse(int port)
{
bool inUse = false;
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();
foreach (IPEndPoint endPoint in ipEndPoints)
{
if (endPoint.Port == port)
{
inUse = true;
break;
}
}
return inUse;
}