UDP端口打开检查端口、UDP

2023-09-07 12:56:30 作者:尐棈舂°尐絯紙っっ

检查 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?
    }
 
精彩推荐