UDP端口打开检查 [英] UDP port open check

查看:37
本文介绍了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端口打开检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆