Reputation: 85
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?
Upvotes: 5
Views: 4943
Reputation: 63616
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.
Upvotes: 6
Reputation: 19975
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.
Upvotes: 2