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端口打开检查
基础教程推荐
- 全局 ASAX - 获取服务器名称 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
