最近在搞 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;
}
