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.
"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.
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.
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.
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.
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?
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With