UDP端口开支票 [英] UDP port open check
问题描述
什么是检查UDP端口是开放的还是不一样的机器上的最佳途径。我有端口号 7525UDP
,如果它是开放的,我想绑定到它。我使用这个代码:
,而(真)
{
尝试{插座.bind()}
赶上(异常前)
{MessageBox.Show(插座可能都在使用);}
}
< /ç$ç$>
但有特定的功能,可以检查UDP端口是开放与否。如果没有席卷整个表的UDP端口设置会也不错。
INT MyPort上= 7525;
布尔alreadyinuse =(从System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties()p GetActiveUdpListeners(),其中p.Port == MyPort上选择页).Count之间的()== 1;
注释以下建议其将提供第一个空闲的UDP端口的变化......但是,建议代码是低效的,因为它调用该外部组件多次(这取决于许多端口如何都在使用中)。这里有一个更有效的变化,这将只调用外部程序集一次(而且也更易读):
VAR startingAtPort = 5000;
VAR maxNumberOfPortsToCheck = 500;
变种范围= Enumerable.Range(startingAtPort,maxNumberOfPortsToCheck);从范围
p
变种portsInUse =
加入System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties()使用。GetActiveUdpListeners()页上的
等于used.Port
。选择所需磷;
VAR FirstFreeUDPPortInRange = range.Except(portsInUse).FirstOrDefault();
如果(FirstFreeUDPPortInRange大于0)
{
//做的东西
Console.WriteLine(FirstFreeUDPPortInRange);
}其他{
//抱怨缺乏自由端口?
}
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");}
}
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 = (from p in System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners() where p.Port == myport select p).Count() == 1;
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端口开支票的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!