public bool PortInUse(int port)
{
bool inUse = false;
IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();//IP端口
foreach (IPEndPoint endPoint in ipEndPoints)
{
if (endPoint.Port == port)
{
inUse = true;
return inUse;
}
}
ipEndPoints = ipProperties.GetActiveUdpListeners();//UDP端口
foreach (IPEndPoint endPoint in ipEndPoints)
{
if (endPoint.Port == port)
{
inUse = true;
return inUse;
}
}
return inUse;
}
代码已在实际项目中使用绝无后患(windows平台)