c#检测端口是否被占用

 当我们要创建一个Tcp/Ip Server connection ,我们需要一个范围在1000到65535之间的端口 。

但是本机一个端口只能一个程序监听,所以我们进行本地监听的时候需要检测端口是否被占用。

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

 1 public static bool PortInUse(int port)
 2 {
 3     bool inUse = false;
 4             
 5     IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
 6     IPEndPoint[] ipEndPoints = ipProperties.GetActiveTcpListeners();
 7             
 8     foreach (IPEndPoint endPoint in ipEndPoints)
 9     {
10         if (endPoint.Port == port)
11         {
12             inUse = true;
13             break;
14         }
15     }
16 
17     return inUse;
18 }

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

 1 static void Main(string[] args)
 2 {
 3     HttpListener httpListner = new HttpListener();
 4     httpListner.Prefixes.Add("http://*:8080/");
 5     httpListner.Start();
 6 
 7     Console.WriteLine("Port: 8080 status: " + (PortInUse(8080) ? "in use" : "not in use"));
 8 
 9     Console.ReadKey();
10 
11     httpListner.Close();
12 }

原文地址:http://www.cnblogs.com/smiler/p/3460462.html

因为原文没有找到收藏的地方,就复制过来了,谢谢啦

原文地址:https://www.cnblogs.com/oracleblogs/p/3465619.html