C#网络/检测某端口是否被占用的方法

来源:互联网 发布:知乎 横渡太平洋 编辑:程序博客网 时间:2024/05/19 16:47

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

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

0 0
原创粉丝点击