首页 > 编程知识 正文

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

时间:2023-05-04 10:19:12 阅读:273474 作者:999

之前找到的方法效率太低,找到个更好的,记录下来。
当我们要创建一个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

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。