Opening network connections with nc
- Version
- unversioned
- Review
- Draft
Summary#
nc, or netcat, connects to or listens on TCP, UDP and Unix sockets and copies data between them and the terminal.
Syntax#
nc -vz example.com 443
nc -vz -w 3 db.internal 5432
nc -l 127.0.0.1 8080
printf 'PING\r\n' | nc -N 127.0.0.1 6379
nc -U /run/app.sock
-z only checks whether a connection opens, -v reports the result and -w sets a timeout. -l listens, -N closes the sending side after input ends and -U uses a Unix socket.
Example#
This example uses a Unix socket inside its own directory.
(
set -eu
dir=$(mktemp -d)
server=
trap 'if [ -n "$server" ]; then
kill "$server" 2>/dev/null || true
wait "$server" 2>/dev/null || true
fi
rm -rf -- "$dir"' EXIT
nc -lU "$dir/sock" > "$dir/received" < /dev/null &
server=$!
until [ -S "$dir/sock" ]; do sleep 0.1; done
printf 'hello over a socket\n' | nc -NU "$dir/sock"
wait "$server"
server=
cat "$dir/received"
nc -z -U "$dir/missing" 2>/dev/null || echo 'no listener on the missing socket'
)
Expected output#
hello over a socket
no listener on the missing socket
Common mistakes#
Several programs are called netcat, including the OpenBSD version, a traditional version and Ncat, and their options differ; check nc -h. An open TCP port shows that something accepted the connection, not that the application works. A successful UDP check proves little because UDP has no handshake. nc does not encrypt traffic; use openssl s_client to test TLS. Listening on all addresses exposes the port to the network, so bind to 127.0.0.1 for local tests.
Version applicability#
This entry describes the OpenBSD netcat packaged by Ubuntu and Fedora.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0