private bool ISPortUsed(int port) { IList portUsed = PortUsing(); return portUsed.Contains(port); } private IList PortUsing() { //獲取本地計算機的網絡鏈接和通訊統計數據的信息 IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); //返回本地計算機上的全部Tcp監聽程序 IPEndPoint[] ipsTCP = ipGlobalProperties.GetActiveTcpListeners(); //返回本地計算機上的全部UDP監聽程序 IPEndPoint[] ipsUDP = ipGlobalProperties.GetActiveUdpListeners(); //返回本地計算機上的Internet協議版本4(IPV4 傳輸控制協議(TCP)鏈接的信息。 TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections(); List<int> allPorts = new List<int>(); allPorts.AddRange(ipsTCP.Select(n => n.Port)); allPorts.AddRange(ipsUDP.Select(n => n.Port)); allPorts.AddRange(tcpConnInfoArray.Select(n => n.LocalEndPoint.Port)); return allPorts; }
所有源碼下載:https://download.csdn.net/download/hanghangz/11250029網絡