Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UDP port open check

Tags:

c#

port

udp

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.

like image 863
Thomas Avatar asked May 04 '11 06:05

Thomas


People also ask

How do I check if a UDP port is open?

"nc -uvz ip port" isn't somehow accurate, you probably should use "nmap -sU -p port ip" , if the result shows "open" then the udp port probably is open, if it shows "open|filtered" then probably it is closed or filtered.

How do I check if a UDP port is open on public IP?

Use this UDP port scan tool to check what services (dns, tftp, ntp, snmp, mdns, upnp) are running on your server, test if your firewall is working correctly, view open UDP ports. This port scanner runs a UDP scan on an IP address using Nmap port scanner.

How do you check if TCP and UDP ports are open?

Type the command portqry.exe -local to see all open TCP and UDP ports for your machine. It'll show you everything you can see with the NetStat command, plus port mappings and how many ports are in each state.

How do I find my UDP port?

Finding an open TCP or UDP port (For Windows 10, press the Windows button) and type CMD. Now click on Run as Administrator option. When the Command Prompt window opens, type Netstat -ab and press Enter. A list of TCP and UDP ports starts appearing along with the IP address and other details.


1 Answers

int myport = 7525;
bool alreadyinuse = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners().Any(p => p.Port == myport);

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?
    }
like image 161
Nathan Avatar answered Oct 07 '22 22:10

Nathan