5

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?

mpontillo
  • 13,559
  • 7
  • 62
  • 90
Marian
  • 85
  • 1
  • 3

2 Answers2

6

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.

MarkR
  • 62,604
  • 14
  • 116
  • 151
  • 1
    Sorry for asking this but how can I see if it sent me the ICMP port-unreachable? Thank you. – Marian Jan 09 '11 at 15:40
  • @Marian: Can you make another question for this? I'd love to know also. – Matt Joiner Jan 09 '11 at 16:03
  • I actually don't think it's worth bothering detecting the ICMP port-unreachable, as it might not arrive. This is especially true of computers which have "personal firewall" products installed which tend to block such useful things for (mostly) misguided security reasons. – MarkR Jan 09 '11 at 16:46
2

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.

Richard Pennington
  • 19,673
  • 4
  • 43
  • 72