易丰科技

 找回密码
 立即注册
搜索
热搜: 活动 交友 discuz
查看: 3278|回复: 0
打印 上一主题 下一主题

C# 找到机器上可用的 Port

[复制链接]

111

主题

117

帖子

3588

积分

论坛元老

Rank: 8Rank: 8

积分
3588
跳转到指定楼层
楼主
发表于 2011-10-16 11:59:18 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
加入引用:
  1. using System.Net.NetworkInformation;
  2. using System.Net;
复制代码
获得可以用的 Port
  1. private string GetOpenPort()
  2. {
  3.   int PortStartIndex = 1000;
  4.   int PortEndIndex = 2000;
  5.   IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
  6.   IPEndPoint[] tcpEndPoints = properties.GetActiveTcpListeners();

  7.   List<int> usedPorts = tcpEndPoints.Select(p => p.Port).ToList<int>();
  8.   int unusedPort = 0;

  9.   for (int port = PortStartIndex; port < PortEndIndex; port++)
  10.   {
  11.      if (!usedPorts.Contains(port))
  12.      {
  13.         unusedPort = port;
  14.         break;
  15.      }
  16.   }
  17.   return unusedPort.ToString();
  18. }
复制代码

另一种更好的方法:
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Net;
  4. using System.Net.NetworkInformation;

  5. private string GetOpenPort()
  6. {
  7.     const int PortStartIndex = 1000;
  8.     const int PortEndIndex = 2000;
  9.     IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
  10.     IPEndPoint[] tcpEndPoints = properties.GetActiveTcpListeners();
  11.     IEnumerable<int> query =
  12.           (from n in tcpEndPoints.OrderBy(n => n.Port)
  13.           where (n.Port >= PortStartIndex) && (n.Port <= PortEndIndex)
  14.           select n.Port).ToArray().Distinct();

  15.     int i = PortStartIndex;
  16.     foreach (int p in query)
  17.     {
  18.         if (p != i)
  19.         {
  20.             break;
  21.         }
  22.         i++;
  23.     }
  24.     return i > PortEndIndex ? "0": i.ToString();
  25. }
复制代码


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|易丰科技

GMT+8, 2024-10-14 03:15 , Processed in 0.052720 second(s), 20 queries .

Powered by Discuz! X3

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表