2023年2月17日 星期五

檢查網路連接埠是否已被使用

日前使用者反映AP開埠起來會自動消失,看了作業系統的事件檢視器發現是SocketException造成的,因此增加連接埠是否已被使用的檢查邏輯。

備忘囉:
using System.Net.NetworkInformation;

public 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;
}

if (PortInUse(80)) {
    MessageBox.Show("80埠已被占用。");
} ......