直接上代码
public static bool IsPortInUse(int port) { bool isPortInUse = false; IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); IPEndPoint[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpListeners(); IPEndPoint[] udpConnInfoArray = ipGlobalProperties.GetActiveUdpListeners(); foreach (IPEndPoint endPoint in tcpConnInfoArray) { if (endPoint.Port == port) { isPortInUse = true; break; } } if (!isPortInUse) { foreach (IPEndPoint endPoint in udpConnInfoArray) { if (endPoint.Port == port) { isPortInUse = true; break; } } } return isPortInUse; }
调用方式:
1 int port = 80; // 要检查的端口号 2 bool isPortInUse = PortChecker.IsPortInUse(port); 3 if (isPortInUse) 4 { 5 Console.WriteLine($"端口 {port} 被占用."); 6 } 7 else 8 { 9 Console.WriteLine($"端口 {port} 未被占用."); 10 }
标签:endPoint,isPortInUse,C#,占用,端口,ipGlobalProperties,IPEndPoint,port From: https://www.cnblogs.com/AnYanaha/p/18023726