How does netcat know if a UDP port is open?

  • So I can use this netcat command to check if a UDP port is open:

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

    Unlike TCP, UDP is connectionless (fire and forget). So at a high level does anyone know how netcat knows the UDP port is open? Does it ask for a reply or something like that?

  • rocky

    rocky Correct answer

    5 years ago

    Judging by the specific output Connection to Connection to 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;
                                /* Don't look up port if -n. */
                                if (nflag)
                                        sv = NULL;
                                else {
                                        sv = getservbyport(
                                            uflag ? "udp" : "tcp");
                                    "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.

    so `udptest` is the function I am looking for and it answers my question. From the link you provided "* udptest() * Do a few writes to see if the UDP port is there"

    Yes, I just checked that and saw the writes as well. Revised answer.

    @PatrickMcMahon - if this answers your question, then accept it by clicking on the large tick.

License under CC-BY-SA with attribution

Content dated before 6/26/2020 9:53 AM