UDP通信 获取可用端口

LifangJelfson 2010-06-03 01:50:22
我仿了一个udp通信程序
里面UDp监听时通过
UDP_server = new UdpClient(localPort);
来指定监听端口。
其中localPort是自己设定的。
有没有什么简单的方法能自动获取当前可用的端口,然后传给localPort,而不需要自己来更改。
...全文
979 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
uvvvw 2010-07-24
  • 打赏
  • 举报
回复
学习中
asight 2010-07-24
  • 打赏
  • 举报
回复
[Quote=引用 5 楼 c325061100 的回复:]

C# code
/// <summary>
/// 获取第一个可用的端口号
/// </summary>
/// <returns></returns>
public static int GetFirstAvailablePort()
{
int MAX_PORT = 65535; //……
[/Quote]
我直接用 内网ip:80 和 255.255.255.255:80,然后开着chrome,连接另一个监听80的UdpClient,没事,UDP不在乎端口占用的,可以通讯,再举个例子,用4001,4002等QQ专用的,还是直接用。我也不知道为什么.........................
mngzilin 2010-06-03
  • 打赏
  • 举报
回复
一般是遍历端口,有时候捷径该放弃
LifangJelfson 2010-06-03
  • 打赏
  • 举报
回复
没有简单点的方法吗
[Quote=引用 5 楼 c325061100 的回复:]
C# code
/// <summary>
/// 获取第一个可用的端口号
/// </summary>
/// <returns></returns>
public static int GetFirstAvailablePort()
{
int MAX_PORT = 6553……
[/Quote]
FtLover 2010-06-03
  • 打赏
  • 举报
回复
引用空间:using System.Net.NetworkInformation;

给分结贴了。
FtLover 2010-06-03
  • 打赏
  • 举报
回复
 /// <summary>
/// 获取第一个可用的端口号
/// </summary>
/// <returns></returns>
public static int GetFirstAvailablePort()
{
int MAX_PORT = 65535; //系统tcp/udp端口数最大是65535
int BEGIN_PORT = 5000;//从这个端口开始检测

for (int i = BEGIN_PORT; i < MAX_PORT; i++)
{
if (PortIsAvailable(i)) return i;
}

return -1;
}

/// <summary>
/// 获取操作系统已用的端口号
/// </summary>
/// <returns></returns>
public static IList PortIsUsed()
{
//获取本地计算机的网络连接和通信统计数据的信息
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();

//返回本地计算机上的所有Tcp监听程序
IPEndPoint[] ipsTCP = ipGlobalProperties.GetActiveTcpListeners();

//返回本地计算机上的所有UDP监听程序
IPEndPoint[] ipsUDP = ipGlobalProperties.GetActiveUdpListeners();

//返回本地计算机上的Internet协议版本4(IPV4 传输控制协议(TCP)连接的信息。
TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();

IList allPorts = new ArrayList();
foreach (IPEndPoint ep in ipsTCP) allPorts.Add(ep.Port);
foreach (IPEndPoint ep in ipsUDP) allPorts.Add(ep.Port);
foreach (TcpConnectionInformation conn in tcpConnInfoArray) allPorts.Add(conn.LocalEndPoint.Port);

return allPorts;
}

/// <summary>
/// 检查指定端口是否已用
/// </summary>
/// <param name="port"></param>
/// <returns></returns>
public static bool PortIsAvailable(int port)
{
bool isAvailable = true;

IList portUsed = PortIsUsed();

foreach (int p in portUsed)
{
if (p == port)
{
isAvailable = false; break;
}
}

return isAvailable;
}
LifangJelfson 2010-06-03
  • 打赏
  • 举报
回复
怎么就没人跟我指点下呢
LifangJelfson 2010-06-03
  • 打赏
  • 举报
回复
那我怎么才能知道得到的可用端口是哪个呢?
[Quote=引用 2 楼 sisen 的回复:]
UDP_server = new UdpClient(0);
当参数为0时,会自动给你一个可用的端口。
[/Quote]
sisen 2010-06-03
  • 打赏
  • 举报
回复
UDP_server = new UdpClient(0);
当参数为0时,会自动给你一个可用的端口。
wangyue4 2010-06-03
  • 打赏
  • 举报
回复
我用try-catch,循环一个端口数组,bind有异常代表端口不可用,去试下一个端口

110,556

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧