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网络