UDP port open check

2019-02-13 09:56发布

问题:

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.

回答1:

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?
    }


标签: c# udp port