How does netcat know if a UDP port is open?

In fact, it doesn't. You can check by doing:

$ nc -vz -u 8.8.8.8 53 
Connection to 8.8.8.8 53 port [udp/domain] succeeded!
$ nc -vz -u 8.8.8.8 54
Connection to 8.8.8.8 54 port [udp/*] succeeded!
$ nc -vz -u 8.8.8.8 59
Connection to 8.8.8.8 59 port [udp/*] succeeded!
$ 

So with UDP, it's not something you can really check unless it will give you information back.


Judging by the specific output Connection to Connection to 10.1.0.100 53 port [udp/domain] succeeded! you are using openbsd-netcat.

Looking at the code for that the test is to bind to the UDP socket, i.e. there is an open connection:

              if (vflag || zflag) {
                            /* For UDP, make sure we are connected. */
                            if (uflag) {
                                    if (udptest(s) == -1) {
                                            ret = 1;
                                            continue;
                                    }
                            }

                            /* Don't look up port if -n. */
                            if (nflag)
                                    sv = NULL;
                            else {
                                    sv = getservbyport(
                                        ntohs(atoi(portlist[i])),
                                        uflag ? "udp" : "tcp");
                            }

                            fprintf(stderr,
                                "Connection to %s %s port [%s/%s] "
                                "succeeded!\n", host, portlist[i],
                                uflag ? "udp" : "tcp",
                                sv ? sv->s_name : "*");

udptest issues around 3 writes to the open socket. There is a note that this doesn't work for IPv6 and fails after around 100 ports checked.

So while the other suggestion may be valid, I don't think that's happening in this particular case.


Well I have different opinion:

a:~# nc -luk 10.12.0.12 667 // listen on UDP port 667
b:~# nc -uv 10.12.0.12 667  // check if port is open 
nc: 10.12.0.12 (10.12.0.12) 667 [667] open
I love stackexchange // send a message
a:~# nc -luk 10.12.0.12 667
I love stackexchange // receive the message.

So based on that, you can check if the connection between a and b on that udp port is possible. Later on you can continue checking using tcpdump.

Tags:

Udp

Netcat