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端口打开检查
基础教程推荐
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- rabbitmq 的 REST API 2022-01-01