C# 判断端口是否被占用

C# 判断端口是否被占用

命名空间System.Net.NetworkInformation下定义了一个名为IPGlobalProperties的类,我们使用这个类可以获取所有的监听连接,然后判断端口是否被占用,代码如下:

using System.Net.NetworkInformation;
using System.Net;
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;  // 返回true说明端口被占用

}

猜你喜欢

转载自blog.csdn.net/qq_38463737/article/details/121503729