I am making a C program in which I need to check for opened UDP ports on the destination computer. Because UDP is connectionless, I can't check the return value of connect()
like I can with TCP.
send()
and sendto()
return values are also no help. The manual page states:
No indication of failure to deliver is implicit in a send(). Locally
detected errors are indicated by a return value of -1.
How can I tell if I sent a UDP packet to an open port on the destination host?
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.
If the UDP port is open, the packet is accepted, no response packet is sent. If the UDP port is closed, an ICMP packet is sent in response with the appropriate error code such as Destination Unreachable.
In general you can't do it.
In principle, a host with a closed port should send back an ICMP port-unreachable. But they often don't; likewise, a down or inaccessible host will not send such a message. Also, some firewalls will block the message.
Retrieving the error is also problematic. Linux has well-defined, but confusing semantics for retrieving errors on sockets (see the various man pages, socket(7), ip(7) and udp(7) for some info). You will sometimes see a previous error reported when you do an unrelated sendto() for example. Other OSs have slightly differing mechanisms for retrieving specific socket errors.
If it is guaranteed to be a particular protocol on the other port, you can send a packet which should elicit a particular response (if it is your own protocol, you can add an "are you there" message type), then you can use that. But in general, whether a response is generated is up to the application, and you cannot distinguish between a port with nothing listening, and a port with something listening which decides not to respond to you.
Since UDP is connectionless, you have to check the port status in your application code. For example, send a packet to the port, and wait for a response. If you don't get a response in some application specific time, the port isn't available.
You have to design this into both the sending and receiving end, of course.
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