Lesson 109: nc Command
In this lesson, you'll learn how to use the nc (netcat) command to create network connections, transfer files, scan ports, and test services in Linux.
nc (netcat) is often referred to as the "Swiss army knife of networking". It is a versatile command-line utility for reading from and writing to network connections using TCP or UDP protocols.
It can be used for port scanning, file transfers, banner grabbing, proxying, testing services, and even creating simple chat sessions between hosts.
nc is available on most Linux distributions and is pre-installed on many of them. It comes in two common variants: the traditional netcat and the more feature-rich ncat (from the Nmap project).
Install nc in Linux
$ sudo apt install netcat # Debian, Ubuntu and Mint
$ sudo yum install nc # RHEL/CentOS/Fedora and Rocky/AlmaLinux
$ sudo pacman -S openbsd-netcat # Arch Linux
$ sudo zypper install netcat # OpenSUSE
nc Command Syntax
$ nc [OPTIONS] [HOST] [PORT]
nc Command Options
| Option | Description |
|---|---|
-l |
Listen mode β wait for an incoming connection |
-p PORT |
Specify the source port to use |
-u |
Use UDP instead of TCP (default is TCP) |
-v |
Enable verbose output |
-vv |
Enable more verbose output |
-z |
Zero I/O mode β scan for open ports without sending data |
-w SECS |
Set a timeout in seconds for connections |
-n |
Suppress DNS lookups β use numeric IP addresses only |
-k |
Keep the server listening after a client disconnects |
-e CMD |
Execute a command after connecting (not on all versions) |
1. Test Connectivity to a Remote Host and Port
The most basic use of nc is to check if a specific port on a remote host is open and accepting connections. This is similar to telnet but more flexible.
$ nc -v google.com 80
Connection to google.com 80 port [tcp/http] succeeded!
To test connectivity to an SSH port:
$ nc -v 192.168.0.100 22
Connection to 192.168.0.100 22 port [tcp/ssh] succeeded!
SSH-2.0-OpenSSH_8.9p1 Ubuntu-3ubuntu0.4
2. Scan for Open Ports
Using the -z (zero I/O mode) and -v (verbose) options together, you can use nc as a simple port scanner to check which ports are open on a remote host.
To scan a single port:
$ nc -zv 192.168.0.100 22
Connection to 192.168.0.100 22 port [tcp/ssh] succeeded!
To scan a range of ports:
$ nc -zv 192.168.0.100 20-25
nc: connect to 192.168.0.100 port 20 (tcp) failed: Connection refused
nc: connect to 192.168.0.100 port 21 (tcp) failed: Connection refused
Connection to 192.168.0.100 22 port [tcp/ssh] succeeded!
nc: connect to 192.168.0.100 port 23 (tcp) failed: Connection refused
nc: connect to 192.168.0.100 port 24 (tcp) failed: Connection refused
nc: connect to 192.168.0.100 port 25 (tcp) failed: Connection refused