UDP port open check(UDP端口打开检查)
问题描述
检查 UDP 端口是否在同一台机器上打开的最佳方法是什么.我有端口号 7525UDP
如果它是开放的,我想绑定到它.我正在使用此代码:
What is the best way to check if the UDP port is open or not on the same machine. I have got port number 7525UDP
and if it's open I would like to bind to it. I am using this code:
while (true)
{
try {socket.bind()}
catch (Exception ex)
{MessageBox.Show("socket probably in use");}
}
但是是否有指定的函数可以检查 UDP 端口是否打开.如果不扫描 UDP 端口的整个表集也很好.
but is there a specified function that can check if the UDP port is open or not. Without sweeping the entire table set for UDP ports would be also good.
推荐答案
int myport = 7525;
bool alreadyinuse = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners().Any(p => p.Port == myport);
下面的评论建议了一种变体,它将提供第一个空闲的 UDP 端口...但是,建议的代码效率低下,因为它多次调用外部程序集(取决于正在使用的端口数).这是一个更有效的变体,它只会调用一次外部程序集(并且也更具可读性):
A comment below suggested a variation which would supply the first free UDP port... however, the suggested code is inefficient as it calls out to the external assembly multiple times (depending on how many ports are in use). Here's a more efficient variation which will only call the external assembly once (and is also more readable):
var startingAtPort = 5000;
var maxNumberOfPortsToCheck = 500;
var range = Enumerable.Range(startingAtPort, maxNumberOfPortsToCheck);
var portsInUse =
from p in range
join used in System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners()
on p equals used.Port
select p;
var FirstFreeUDPPortInRange = range.Except(portsInUse).FirstOrDefault();
if(FirstFreeUDPPortInRange > 0)
{
// do stuff
Console.WriteLine(FirstFreeUDPPortInRange);
} else {
// complain about lack of free ports?
}
这篇关于UDP端口打开检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:UDP端口打开检查


- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- C# 中多线程网络服务器的模式 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01