Ports and connections
nc
Opens a raw TCP or UDP connection, or listens for one: the simplest way to test a port by hand.
nc HOST PORT connects and sends whatever you type; nc -l -p PORT waits for someone to connect. With
-z it only checks whether the port accepts a connection. The three outcomes tell different stories: it
connects (listening, nothing in the way), it is refused at once (reached the device, nothing listening, or a
REJECT rule), it hangs (a firewall drops the packets).
nc command usage
nc [-u] [-v] [-w SECONDS] HOST PORT nc -z -v [-w SECONDS] HOST PORT nc -l -p PORT
Options
-
-z - only check the port, send nothing
-
-v - say what happened
-
-w 2 - give up after 2 seconds
-
-u - UDP instead of TCP
-
-l -p 9000 - listen on port 9000
nc examples
-
nc -zv -w2 10.0.2.10 80 - Checks whether port 80 on 10.0.2.10 accepts TCP connections.
-
echo hi | nc -w1 10.0.2.10 7 - Sends one line to the echo service on port 7 and prints the answer.
-
echo hello | nc -u -w1 10.0.2.10 9999 - Sends one UDP datagram to port 9999.
-
nc -l -p 9000 - Listens on TCP port 9000 and prints whatever a client sends.
-
nc -l 9000 - Listens on port 9000 with OpenBSD nc (Debian, Ubuntu) or ncat (Fedora, RHEL); traditional and BusyBox nc need -l -p 9000.
-
nc 10.0.2.10 9000 - Connects to that listener: each line typed on one side appears on the other.
-
nc -lk 9000 - Keeps listening after a client leaves, for the next one (OpenBSD nc and ncat).
-
nc -zv 10.0.2.10 20-25 - Checks a range of ports, one line each (OpenBSD nc; ncat takes one port).
-
nc -v -w3 10.0.2.10 22 - Connects and prints what the service says first: the SSH server names its version.
Connection to 10.0.2.10 22 port [tcp/ssh] succeeded! SSH-2.0-OpenSSH_9.6
-
printf 'GET / HTTP/1.1\r\nHost: webServer.lab\r\nConnection: close\r\n\r\n' | nc webServer.lab 80 - Sends an HTTP request typed by hand and prints the raw response, headers and all.
-
nc -l 9000 > frr.tgz - Receives a file: whatever the sender pipes in is written to frr.tgz.
-
tar czf - /etc/frr | nc -N 10.0.1.10 9000 - Sends the directory to that listener; -N closes the connection at the end so the receiver stops (OpenBSD nc).
-
nc -u -l 5514 - Listens for UDP on port 5514 and prints each datagram, such as syslog messages.
-
nc -s 10.0.1.50 10.0.2.10 80 - Connects from another of your addresses, to test a rule that matches the source.
-
ncat --ssl bank.lab 443 - Opens a TLS connection and lets you type into it (ncat only).
Reading the output
$ nc -zv -w2 10.0.2.10 80; nc -zv -w2 10.0.2.10 81; echo exit=$? 10.0.2.10 (10.0.2.10:80) open exit=1
open: the connection was accepted.- Port 81 printed nothing and exit 1: refused or timed out. Add
timein front to tell them apart: refused is instant, a drop waits for-w.
Pitfalls
- UDP has no handshake:
nc -u"succeeds" whether or not anything listens. Only a reply proves it arrived.