关键词搜索

源码搜索 ×
×

c#检测端口是否被占用

发布2020-12-26浏览1822次

详情内容

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

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

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

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

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

 

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载