侧边栏壁纸
  • 累计撰写 185 篇文章
  • 累计创建 77 个标签
  • 累计收到 17 条评论

目 录CONTENT

文章目录

C#检测网络端口是否被占用的参考代码

码峰
2022-07-20 / 0 评论 / 0 点赞 / 1,000 阅读 / 233 字 / 正在检测是否收录...
广告 广告

当我们要创建一个TCP/IP的服务时,我们需要一个1000到65535范围的端口,但本机一个端口只能有一个程序监听,所以我们进行本地监听的时候需要检测端口是否被占用。
在C#的命名空间System.Net.NetworkInformation中的IPGlobalProperties类,使用这个类可以获取所有的监听的连接,然后判断端口是否被占用,参考代码如下:

public static bool IsPortInUse(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;
}

我们使用HttpListener类在8080端口启动一个监听,然后测试是否可以被检测出来,参考代码如下:

static void Main(string[] args)
{
    HttpListener httpListner = new HttpListener();
    httpListner.Prefixes.Add("http://*:8080/");
    httpListner.Start();
    Console.WriteLine("Port: 8080 status: " + (IsPortInUse(8080) ? "in use" : "not in use"));
    Console.ReadKey();
    httpListner.Close();
}
0
广告 广告

评论区