netcat (nc) Cheatsheet

Swiss army knife for TCP/UDP networking

Linux
Contents
🔧

Basics

# Connect to host:port
nc host 80

# Verbose mode
nc -v host 80

# UDP mode
nc -u host 53

# Set timeout
nc -w 5 host 80     # 5 sec timeout

# Send data
echo "GET / HTTP/1.0\r\n\r\n" | nc host 80

# Close after EOF
nc -q 0 host 80 < request.txt

# Variants: nc, ncat, netcat, nmap-ncat
👂

Listen Mode

# Listen on a port
nc -l 4444

# Listen (keep listening after disconnect)
nc -lk 4444

# Listen verbose
nc -lv 4444

# Simple chat between 2 machines:
# Machine A (listen):
nc -l 4444
# Machine B (connect):
nc machineA 4444
# Type messages — bidirectional!

# HTTP server (one-shot)
while true; do
  echo -e "HTTP/1.1 200 OK\n\nHello" | nc -l 8080 -q 1
done
📤

File Transfer

# Receiver (listen):
nc -l 9999 > received_file

# Sender:
nc receiver_host 9999 < file_to_send

# Transfer directory (tar + nc):
# Receiver:
nc -l 9999 | tar xvf -
# Sender:
tar cvf - /path/dir | nc receiver 9999

# With compression:
# Receiver:
nc -l 9999 | gunzip > file
# Sender:
gzip -c file | nc receiver 9999

# With progress (pv):
pv file | nc receiver 9999
🔍

Port Scanning

# Scan single port
nc -zv host 80

# Scan port range
nc -zv host 20-100

# Scan common ports
nc -zv host 22 80 443 3306 5432

# Fast scan (low timeout)
nc -zv -w 1 host 1-1000

# UDP port scan
nc -zuv host 53

# Banner grabbing
echo "" | nc -v -w 2 host 22
🔄

Proxy & Relay

# Simple port forwarding (with named pipe)
mkfifo /tmp/pipe
nc -l 8080 < /tmp/pipe | nc target 80 > /tmp/pipe

# Using ncat (nmap version) — better:
ncat -l 8080 --sh-exec "ncat target 80"

# Proxy with socat (alternative):
socat TCP-LISTEN:8080,fork TCP:target:80
💡

Tricks

# Test if port is open
nc -zv google.com 443 && echo "open"

# Send email (SMTP test)
nc mail.server 25
HELO test
MAIL FROM:<a@b.com>
RCPT TO:<c@d.com>
DATA
Subject: Test
Body
.
QUIT

# HTTP request
printf "GET / HTTP/1.1\r\nHost: example.com\r\n\r\n" | \
  nc example.com 80

# Measure connection speed
dd if=/dev/zero bs=1M count=100 | nc -l 9999
nc host 9999 > /dev/null   # on other end