C#检查TCP端口号是否被占用

本文介绍了一种高效检测本地TCP端口是否被占用的方法。通过使用.NET框架下的System.Net.NetworkInformation命名空间中的IPGlobalProperties类,获取所有活动的TCP监听端口,并检查指定端口是否正在使用中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

之前找到的方法效率太低,找到个更好的,记录下来。

当我们要创建一个Tcp/Ip Server connection ,我们需要一个范围在1000到65535之间的端口。
但是本机一个端口只能一个程序监听,所以我们进行本地监听的时候需要检测端口是否被占用。
命名空间System.Net.NetworkInformation下定义了一个名为IPGlobalProperties的类,我们使用这个类可以获取所有的监听连接,然后判断端口是否被占用,代码如下:
public static bool PortInUse(int port)
{
    bool inUse =false;

    IPGlobalPropertiesipProperties = IPGlobalProperties.GetIPGlobalProperties();
    IPEndPoint[] ipEndPoints= ipProperties.GetActiveTcpListeners();

    foreach (IPEndPointendPoint in ipEndPoints)
    {
       if (endPoint.Port == port)
       {
           inUse =true;
          break;
       }
    }
    return inUse;
}
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;
}


转自脚本之家,http://www.jb51.net/article/44218.htm
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值