---
title: "Netcat"
description: "Complete netcat reference covering TCP/UDP connections, file transfers, server testing, port scanning, banner grabbing, and network troubleshooting with practical examples"
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/cheatsheets/nc
---

# Netcat

This comprehensive netcat cheatsheet provides complete coverage of TCP/UDP connections, file transfers, port scanning, banner grabbing, and advanced network operations.

## Getting Started

Introduction to netcat and understanding its capabilities for network operations

### What is Netcat

Understand netcat and its role in network operations and diagnostics

**Keywords:** introduction, what, about, netcat, network, utility

#### Install and verify netcat installation

```bash
# On Debian/Ubuntu systems
sudo apt-get update
sudo apt-get install netcat-openbsd

# Alternative: Traditional netcat
sudo apt-get install netcat

# On CentOS/RHEL systems
sudo yum install nc

# On Fedora systems
sudo dnf install nc

# Verify installation
which nc
nc -h 2>&1 | head -3
```

_exec_
```bash
which nc && echo "Netcat is installed"
```

_output_
```bash
/bin/nc
Netcat is installed
```

Netcat (nc) is available on most Linux systems and comes in different variants. The OpenBSD version is commonly used and recommended for security.

- Multiple netcat implementations exist (GNU, OpenBSD, BusyBox)
- netcat-openbsd is the most secure and widely used variant
- Some systems have nc as a symlink to other utilities
- Verify the version with nc -h or man nc

#### Netcat overview and capabilities

```bash
# Netcat provides:
# - TCP/UDP client and server functionality
# - Port scanning and service testing
# - Banner grabbing and service detection
# - File transfer and bidirectional communication
# - Network proxy and tunnel functionality
# - Debugging and troubleshooting capabilities

# Netcat is called "the Swiss Army knife" of networking
# It reads and writes data across TCP and UDP networks
# Can run as a listening server or connecting client

# Basic usage pattern:
# Client: nc [options] hostname port
# Server: nc -l [options] port
echo "Netcat is ready for network operations"
```

_exec_
```bash
nc -h 2>&1 | grep -E "^\s+-" | head -8
```

_output_
```bash
-4            Use IPv4
-6            Use IPv6
-l            Listen mode
-u            UDP mode (default is TCP)
-v            Verbose output
-z            Scan mode (no I/O)
-e program    Program to exec
```

Netcat provides comprehensive networking capabilities with various flags to handle different network operations efficiently.

- Each flag can be combined with others for advanced operations
- Use -h to see all available options (varies by implementation)
- Netcat output depends on the specific variant installed
- Combine with other tools for powerful network diagnostics

**Best practices:**

- Install netcat-openbsd for security and compatibility
- Always use specific ports (avoid privileged ports when possible)
- Use verbose mode (-v) when debugging network issues
- Combine netcat with pipes for processing network data

**Common errors:**

- **nc command not found**: Install netcat-openbsd or nc package using apt/yum/dnf
- **nc: Address family not supported**: Use -4 for IPv4 or -6 for IPv6, depending on connectivity

### Netcat vs Alternatives

Compare netcat with other networking tools for different use cases

**Keywords:** comparison, alternatives, tools, telnet, curl

#### Netcat vs telnet and curl comparison

```bash
# Netcat advantages over telnet:
# - More versatile (handles UDP, scanning)
# - Better for binary data transfer
# - Supports more protocols and operations
# - More secure implementation

# Netcat advantages over curl:
# - Lower-level network operations
# - No automatic protocol interpretation
# - Better for binary protocols
# - Lightweight and portable

# Use netcat when you need:
# - Raw network communication
# - Port scanning and banner grabbing
# - File transfer over network
# - Custom protocol testing
# - Network debugging and diagnostics

echo "Netcat is ideal for network diagnostics and debugging"
```

_exec_
```bash
echo "Netcat capabilities:"
echo "- TCP/UDP connections"
echo "- Port scanning"
echo "- File transfers"
echo "- Server/Client mode"

```

_output_
```bash
Netcat capabilities:
- TCP/UDP connections
- Port scanning
- File transfers
- Server/Client mode
```

Netcat is a specialized tool for low-level network operations, complementary to higher-level tools like curl or wget.

- Netcat is better for debugging and protocol testing
- Use curl for HTTP operations with automatic handling
- Use telnet only if nc is unavailable
- Combine tools for comprehensive network diagnostics

#### When to use netcat in your workflow

```bash
# Netcat use cases:

# 1. Network diagnostics - test connectivity and services
# 2. Protocol development - test custom protocols
# 3. File transfers - quick data movement between hosts
# 4. Service testing - verify server configuration
# 5. Network debugging - deep-level packet inspection
# 6. Security testing - port scanning and service detection

# Typical workflow:
# 1. Use netcat to test basic connectivity
# 2. Use nc -zv to scan ports
# 3. Use nc to transfer files
# 4. Use netcat for custom protocol testing
# 5. Use nc with pipes for data processing

echo "Netcat is essential for network professionals"
```

_exec_
```bash
echo "Use netcat for low-level network diagnostics and testing"
```

_output_
```bash
Use netcat for low-level network diagnostics and testing
```

Netcat fills a unique role in network administration for tasks requiring direct network control and raw data access.

- Learn netcat to complement higher-level tools
- Understand both client and server modes
- Practice port scanning and banner grabbing
- Master file transfer techniques

**Best practices:**

- Understand the difference between TCP and UDP operations
- Use verbose mode when learning netcat
- Practice both server and client modes
- Combine with pipes and redirection for power

**Common errors:**

- **'Permission denied' on ports below 1024**: Use ports above 1024 or run with sudo for privileged ports
- **Port already in use**: Check with netstat -ln or ss -ln, and use a different port

## Basic Connections

Master TCP and UDP client-server connections with netcat

### TCP Client Connections

Create TCP client connections to remote servers

**Keywords:** tcp, client, connection, remote, server

#### Connect to remote TCP servers and interact

```bash
# Basic TCP connection to a server
nc hostname port

# Connect to localhost on port 8080
nc localhost 8080

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

# Verbose connection (show what's happening)
nc -v example.com 22

# Send data and close connection
echo "Hello Server" | nc hostname port

# Connect with specific local port
nc -p 8888 example.com 80
```

_exec_
```bash
# Example: Connect to SSH service and see banner
timeout 2 nc -v localhost 22 2>&1 | head -3
```

_output_
```bash
Ncat: Version 7.93
Ncat: Connected to 127.0.0.1:22.
SSH-2.0-OpenSSH_8.2p1 Ubuntu 4ubuntu0.5
```

TCP connections with netcat allow you to interact with network services at the protocol level, useful for testing server responses.

- TCP ensures delivery of data in order
- Default protocol is TCP if -u is not specified
- -w flag sets timeout for connection
- Use echo with pipe to send single-line data

#### Interactive TCP communication

```bash
# Interactive connection (type commands after connecting)
# nc hostname port
# Then type your input and press Enter

# Simple telnet replacement
nc example.com 23

# Connect to web server and send HTTP request
# nc example.com 80
# GET / HTTP/1.1
# Host: example.com
# (blank line and Ctrl+D)

# Connect and auto-close after 3 seconds
nc -w 3 example.com 80

# Set timeout without closing automatically
nc -N example.com 80
```

_exec_
```bash
# Example: Test HTTP server response
(echo -e "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"; sleep 1) | nc localhost 80 | head -10
```

_output_
```bash
HTTP/1.1 200 OK
Server: Apache/2.4.41
Date: Fri, 28 Feb 2025 10:00:00 GMT
Content-Type: text/html
Connection: close
```

Interactive communication allows you to test server protocols manually and understand how services respond to requests.

- \r\n is needed for proper HTTP headers
- Use Ctrl+C to exit interactive mode
- -N closes connection after EOF
- Useful for protocol development and testing

**Best practices:**

- Always specify timeout with -w to prevent hanging
- Use verbose mode (-v) when debugging connections
- Test local services first before remote hosts
- Document expected server responses

**Common errors:**

- **Connection refused**: Verify server is running and port is correct with netstat -ln
- **Connection timed out**: Check network connectivity and firewall rules

### TCP Listen Server

Create TCP listening servers with netcat

**Keywords:** tcp, server, listen, accept, port

#### Start listening server and accept connections

```bash
# Start listening server on port 8888
nc -l 8888

# Listen on specific IP and port
nc -l localhost 8888

# Listen in verbose mode
nc -l -v 8888

# Listen only once (accept one connection then exit)
nc -l 8888

# Set verbosity for debugging
nc -l -vv 8888

# Listen on IPv6
nc -6 -l 8888
```

_exec_
```bash
# Start listening server in background
(nc -l 9999 > /tmp/received.txt &) &
sleep 1
# Connect and send data
echo "Test message" | nc localhost 9999
sleep 1
cat /tmp/received.txt
killall nc 2>/dev/null
```

_output_
```bash
Test message
```

TCP listening servers accept incoming connections and can receive data from clients, enabling bidirectional communication.

- -l flag puts netcat in listening mode
- Default is localhost, specify IP for all interfaces
- Server continues running until manually stopped
- Can handle multiple connections with separate processes

#### Interactive server with multiple connections

```bash
# Listen and handle multiple connections
# Use in a loop to accept new connections
while true; do nc -l 8888; done

# Listen and log all input to file
nc -l 8888 >> /tmp/nc.log

# Listen and echo input back to client
mkfifo /tmp/fifo
nc -l 8888 < /tmp/fifo | tee /tmp/fifo > /dev/null

# Listen with timeout
timeout 30 nc -l 8888

# Listen and execute command for each connection
while true; do nc -l 8888 -e /bin/bash; done
```

_exec_
```bash
# Start server in background
(nc -l 9998 | tee /tmp/server.log &) &
SERVER_PID=$!
sleep 1
# Connect client and send message
echo "Server message" | nc localhost 9998
sleep 1
kill $SERVER_PID 2>/dev/null
cat /tmp/server.log
```

_output_
```bash
Server message
```

Multiple connections can be handled by running netcat in a loop or using process management for more complex scenarios.

- Always clean up with killall nc or process termination
- Use pipes to process incoming data
- Use tee to log and pass data simultaneously
- Consider connection limits and resource usage

**Best practices:**

- Use timeout to prevent indefinite listening
- Log connections and data for auditing
- Handle multiple connections in a loop
- Use verbose mode during development

**Common errors:**

- **Address already in use**: Wait for TIME_WAIT state to expire or use -reuseaddr flag
- **Cannot listen on port 80 (permission denied)**: Use sudo or listen on port above 1024

## Protocol Options

Work with different network protocols and connection types

### UDP Connections

Use UDP protocol for fast, connectionless communication

**Keywords:** udp, connectionless, datagram, protocol, fast

#### UDP client and server communication

```bash
# UDP client to send data
echo "UDP Message" | nc -u hostname 5000

# UDP listening server
nc -u -l 5000

# UDP with verbose output
nc -u -v localhost 5000

# UDP timeout on client
echo "Test" | nc -u -w 2 localhost 5353

# Send multiple UDP messages
(echo "Message 1"; sleep 1; echo "Message 2") | nc -u localhost 5000

# UDP with specific source IP
echo "Data" | nc -u -s 192.168.1.100 8.8.8.8 53
```

_exec_
```bash
# Test DNS server with UDP on port 53
(nc -u -l 5353 | tee /tmp/udp_data.txt &) &
UDP_PID=$!
sleep 1
echo "UDP Test" | nc -u localhost 5353
sleep 1
kill $UDP_PID 2>/dev/null
cat /tmp/udp_data.txt
```

_output_
```bash
UDP Test
```

UDP provides connectionless communication, faster than TCP but without delivery guarantees. Useful for streaming and DNS testing.

- UDP has no connection state, data is sent immediately
- Messages may arrive out of order or be lost
- No acknowledgment of delivery
- Use for time-sensitive data or broadcasts

#### UDP DNS query and service testing

```bash
# Test DNS resolution (requires dig or nslookup usually)
# But can send raw UDP to DNS server
echo "Test" | nc -u 8.8.8.8 53

# Listen for incoming UDP messages
nc -u -l -v 5353

# Send UDP broadcast (if supported)
# echo "broadcast message" | nc -u -b 192.168.1.255 5000

# Create UDP echo server (receives and echoes back)
mkfifo /tmp/fifo
(cat /tmp/fifo | nc -u -l 5000 > /tmp/fifo &)

# Send UDP with specific source port
echo "Data" | nc -u -p 5555 localhost 5000

# Test UDP with multiple servers
for server in 8.8.8.8 1.1.1.1; do
  echo "Test" | timeout 1 nc -u $server 53
done
```

_exec_
```bash
# Start UDP listener
(nc -u -l 5354 > /tmp/udp_msg.txt &) &
PID=$!
sleep 1
# Send UDP message
echo "UDP Communication Test" | nc -u localhost 5354
sleep 1
kill $PID 2>/dev/null
cat /tmp/udp_msg.txt
```

_output_
```bash
UDP Communication Test
```

UDP communication is connectionless and useful for testing services like DNS, NTP, and SNMP that use UDP.

- UDP packets may not arrive or may arrive out of order
- No connection setup or teardown overhead
- Faster than TCP for single messages
- Better for real-time applications

**Best practices:**

- Use UDP for time-sensitive, low-reliability needs
- Test UDP services with verbose output
- Be aware of UDP packet size limits
- Use timeout to prevent indefinite waiting

**Common errors:**

- **No response from UDP server**: UDP may require proper protocol format, check service documentation
- **UDP packets not received**: Check firewall allows UDP, use tcpdump to verify traffic

### IPv6 Connections

Work with IPv6 addresses and dual-stack networking

**Keywords:** ipv6, ipv4, dual-stack, address-family, next-generation

#### IPv6 client and server connections

```bash
# Connect to IPv6 server
nc -6 ::1 8080

# Connect to IPv6 address with zone ID
nc -6 fe80::1%eth0 8080

# Listen on IPv6 address
nc -6 -l ::1 8080

# Listen on all IPv6 interfaces
nc -6 -l :: 8080

# Specify both IPv4 and IPv6
nc -4 localhost 8080  # IPv4
nc -6 localhost 8080  # IPv6

# Force IPv4 only
nc -4 -l 0.0.0.0 8080

# Force IPv6 only
nc -6 -l :: 8080
```

_exec_
```bash
# Check if IPv6 is available
nc -6 -z -w 1 ::1 22 2>&1 && echo "IPv6 available" || echo "IPv6 not available"
```

_output_
```bash
IPv6 available
```

IPv6 support is important for future-ready applications. Netcat supports both IPv4 and IPv6 with explicit flags.

- Use -4 to force IPv4, -6 to force IPv6
- Default behavior depends on system configuration
- IPv6 literals need brackets in URLs [::1]:8080
- Zone ID (%) is used for link-local addresses

#### Dual-stack server and IPv6 testing

```bash
# Listen on both IPv4 and IPv6 (requires separate instances)
nc -4 -l 0.0.0.0 8080 &
nc -6 -l :: 8080 &

# Listen on IPv6 only (may accept IPv4 mapped)
nc -6 -l :: 8080

# Test both IPv4 and IPv6 connectivity
echo "IPv4 Test" | nc -4 -w 1 127.0.0.1 8080
echo "IPv6 Test" | nc -6 -w 1 ::1 8080

# Convert IPv4-mapped IPv6 address
# ::ffff:192.0.2.1 is IPv4 192.0.2.1 mapped as IPv6

# Scan IPv6 ports
nc -6 -z -w 1 ::1 22 2>&1
```

_exec_
```bash
# Test IPv6 loopback
(nc -6 -l ::1 8890 > /tmp/ipv6_test.txt &) &
PID=$!
sleep 1
echo "IPv6 Protocol Test" | nc -6 -w 1 ::1 8890
sleep 1
kill $PID 2>/dev/null
cat /tmp/ipv6_test.txt
```

_output_
```bash
IPv6 Protocol Test
```

IPv6 is the future of internet addressing. Testing and understanding IPv6 support is increasingly important.

- IPv6 and IPv4 can coexist on same host
- Some services support dual-stack (both protocols)
- Link-local addresses require zone ID
- IPv4-mapped IPv6 addresses start with ::ffff:

**Best practices:**

- Test both IPv4 and IPv6 in dual-stack environments
- Use explicit -4 or -6 flags to avoid ambiguity
- Understand IPv6 address format and zone IDs
- Plan for IPv6 in network applications

**Common errors:**

- **Address family not supported by protocol**: System may not have IPv6 enabled, check with ip addr
- **Connection refused on IPv6**: Service may only listen on IPv4, check with netstat -6ln

## Data Transfer

Transfer files and data across networks with netcat

### File Transfer

Send files between machines using netcat

**Keywords:** file, transfer, send, receive, copy

#### Transfer files between machines

```bash
# Send file from client to server
# On receiving end (server):
nc -l 8888 > received_file.txt

# On sending end (client):
cat file.txt | nc hostname 8888

# Send file with progress information
cat large_file.iso | pv | nc hostname 8888

# Receive file and save
nc -l 8888 < file.txt

# Transfer binary files
cat binary.bin | nc hostname 8888
nc -l 8888 > binary.bin

# Keep server listening for multiple files
while true; do nc -l 8888 > file_$(date +%s).txt; done
```

_exec_
```bash
# Create test file and transfer
echo "Test file content" > /tmp/test_send.txt
(nc -l 9997 > /tmp/test_receive.txt &) &
PID=$!
sleep 1
cat /tmp/test_send.txt | nc localhost 9997
sleep 1
kill $PID 2>/dev/null
echo "Received: $(cat /tmp/test_receive.txt)"
```

_output_
```bash
Received: Test file content
```

Files can be transferred efficiently using netcat's piping capabilities, supporting both text and binary data.

- Use pv for progress visualization
- Tar can compress folders before transfer
- Encryption should be added for sensitive data
- Large files may need timeouts

#### Directory and compressed data transfer

```bash
# Transfer entire directory as tar archive
# Receiving end:
nc -l 8888 | tar xz -C /destination/

# Sending end:
tar czf - /source/directory | nc hostname 8888

# Transfer with progress using pv
tar czf - /source | pv | nc hostname 8888

# Receive and decompress simultaneously
nc -l 8888 | tar xzf - -C /path/

# Transfer with MD5 verification
tar czf - /source | nc hostname 8888 &
md5sum /source > /tmp/source.md5

# Receive side:
nc -l 8888 | tar xzf - && md5sum -c /tmp/source.md5

# Transfer exclude patterns
tar czf - --exclude='.git' --exclude='node_modules' . | nc hostname 8888
```

_exec_
```bash
# Create test directory and transfer
mkdir -p /tmp/test_dir/subdir
echo "file1" > /tmp/test_dir/file1.txt
echo "file2" > /tmp/test_dir/subdir/file2.txt
(nc -l 9996 | tar xz -C /tmp/ &) &
PID=$!
sleep 1
tar czf - -C /tmp test_dir | nc localhost 9996
sleep 2
kill $PID 2>/dev/null
find /tmp/test_dir -type f
```

_output_
```bash
/tmp/test_dir/file1.txt
/tmp/test_dir/subdir/file2.txt
```

Complex data transfers can be achieved by combining tar with netcat, allowing compression and directory transfer.

- Always use compression for bandwidth efficiency
- Coordinate sender and receiver timing
- Use tar for directory structures
- Consider checksums for data integrity

**Best practices:**

- Always use compression for efficient transfer
- Use timeouts to prevent hanging connections
- Verify checksums for data integrity
- Use progress indicators for large transfers

**Common errors:**

- **File is empty after transfer**: Ensure server is listening before sender connects
- **Connection times out during transfer**: Increase timeout with -w flag or use different port

### Bidirectional Communication

Enable two-way data exchange between netcat client and server

**Keywords:** bidirectional, two-way, communication, interaction, exchange

#### Interactive bidirectional chat

```bash
# Simple chat system using netcat

# Terminal 1 - Server (listening)
nc -l 5555

# Terminal 2 - Client (connecting)
nc localhost 5555

# Both can now type and receive messages
# Type in one terminal, see in other

# With pipes for automation
# Server listening and responding
mkfifo /tmp/chat_in
nc -l 5555 < /tmp/chat_in | tee /tmp/chat_out

# Client sending and receiving
{ echo "Hello"; cat /tmp/chat_out; } | nc server 5555

# Named pipe chat server
mkfifo /tmp/fifo
cat /tmp/fifo | nc -l 5555 | tee /tmp/fifo
```

_exec_
```bash
# Demonstrate bidirectional with pipes
mkfifo /tmp/fifo_in /tmp/fifo_out 2>/dev/null || true
(nc -l 8891 < /tmp/fifo_in > /tmp/fifo_out &) &
PID=$!
sleep 1
(echo "Message 1"; sleep 0.5; echo "Message 2") | nc localhost 8891 | tee /tmp/bc_log.txt
sleep 1
kill $PID 2>/dev/null
cat /tmp/bc_log.txt
```

_output_
```bash
Message 1
Message 2
```

Bidirectional communication allows real-time interaction between client and server, enabling chat and command systems.

- Both sides can send and receive simultaneously
- Use pipes and FIFOs for complex interactions
- Useful for testing interactive services
- Maintain proper connection management

#### Relay and proxy communication

```bash
# Create relay between two connections
# Listen on one port, forward to another

# Method 1: Simple relay with tee
nc -l 5556 | tee /tmp/relay_log.txt | nc remote_host 5000

# Method 2: Bidirectional relay with pipes
mkfifo /tmp/relay_in /tmp/relay_out
cat /tmp/relay_in | nc -l 5556 > /tmp/relay_out
cat /tmp/relay_out | nc remote_host 5000 > /tmp/relay_in

# Method 3: Socat alternative (if available)
# socat TCP-LISTEN:5556 TCP:remote_host:5000

# Method 4: Transparent relay with logging
while true; do
  nc -l 5556 | tee -a relay.log | nc server.example.com 5000
done

# Bidirectional pipe relay
{ cat; echo; } | nc localhost 5000
```

_exec_
```bash
# Create simple relay test
(nc -l 8892 | tee /tmp/relay_test.log &) &
RELAY_PID=$!
sleep 1
echo "Relay Test Message" | nc localhost 8892
sleep 1
kill $RELAY_PID 2>/dev/null
cat /tmp/relay_test.log
```

_output_
```bash
Relay Test Message
```

Relay and proxy functionality allows netcat to act as an intermediary, forwarding and logging network traffic.

- Create FIFOs for managing data flow
- Use tee for logging while forwarding
- Monitor both directions simultaneously
- Useful for debugging and network analysis

**Best practices:**

- Use verbose mode to monitor bidirectional flow
- Create named pipes (FIFOs) for complex interactions
- Log traffic during relay operations
- Test bidirectional setup before production use

**Common errors:**

- **FIFO already exists**: Remove old FIFOs with rm -f before creating new ones
- **Broken pipe**: Ensure both sides of connection are active

## Port Scanning & Discovery

Scan ports and discover network services with netcat

### Port Scanning

Identify open ports on networked systems

**Keywords:** scanning, ports, discovery, open, service

#### Basic port scanning techniques

```bash
# Scan single port
nc -zv localhost 22

# Scan port range
nc -zv localhost 1-1024

# Scan with timeout
nc -zv -w 1 localhost 1-65535

# Scan specific ports only
nc -zv localhost 22 80 443

# Scan with connection timeout
timeout 10 bash -c 'nc -zv localhost 1-1024'

# Scan and redirect output
nc -zv localhost 1-65535 2>&1 | grep succeeded

# Quiet mode (no output)
nc -zv localhost 80 > /dev/null 2>&1 && echo "Port open" || echo "Port closed"
```

_exec_
```bash
# Scan for common ports on localhost
nc -zv -w 1 localhost 22 80 443 3306 5432 8080 2>&1 | grep -E "succeeded|timed out"
```

_output_
```bash
Connection to localhost 22 port 22 [tcp/ssh] succeeded!
Connection to localhost 80 port 80 [tcp/http] timed out (tried 1 time).
Connection to localhost 443 port 443 [tcp/https] timed out (tried 1 time).
```

Port scanning with -z flag tests connectivity without sending data, useful for discovering available services.

- -z flag enables scan mode (no I/O)
- -v enables verbose output to show results
- -w sets timeout for each connection attempt
- Scanning many ports can be time-consuming

#### Efficient port scanning with filtering

```bash
# Scan and show only open ports
nc -zv localhost 1-1024 2>&1 | grep succeeded

# Scan with fast timeout
nc -zv -w 1 localhost 1-65535 2>&1 | grep succeeded

# Scan remote host
nc -zv example.com 1-1024 2>&1 | grep succeeded

# Create a loop for scanning multiple hosts
for host in 192.168.1.{1..10}; do
  nc -zv -w 1 $host 22 2>&1 | grep succeeded
done

# Scan and save results to file
nc -zv localhost 1-65535 2>&1 | grep succeeded | tee /tmp/open_ports.txt

# Complex scan with statistics
for port in 22 80 443 3306 5432 8080 9000; do
  timeout 1 nc -zv localhost $port 2>&1 | grep succeeded && echo "Open: $port"
done

# Background scan with process count
nc -zv -w 1 localhost 1-1024 > /tmp/scan.log 2>&1 &
wait
grep succeeded /tmp/scan.log | wc -l
```

_exec_
```bash
# Quick scan of common ports
for port in 22 80 443 8080; do
  timeout 1 nc -zv localhost $port 2>&1 | grep succeeded && echo "Port $port: OPEN"
done
```

_output_
```bash
Connection to localhost 22 port 22 [tcp/ssh] succeeded!
Port 22: OPEN
```

Filtering and looping enable systematic port discovery across multiple ports and hosts.

- Always use timeout to prevent hanging
- Grep for "succeeded" to find open ports
- Scanning remote hosts requires network access
- Consider using nmap for production scanning

**Best practices:**

- Always use timeouts to prevent infinite waits
- Scan on networks you own or have permission to scan
- Start with common ports before full range scans
- Document scan results for security audits

**Common errors:**

- **Scanning takes too long**: Reduce timeout value with -w or scan fewer ports
- **No output from scan**: Check verbose flag is used and redirect stderr with 2>&1

### Banner Grabbing & Service Detection

Grab service banners for version identification

**Keywords:** banner, grabbing, version, service, detection

#### Grab service banners and identify versions

```bash
# Grab SSH banner
nc -v localhost 22

# Grab HTTP banner
echo "" | nc -v localhost 80

# Connect and send newline for banner
(echo; sleep 1) | nc -v hostname 3306

# Grab with timeout
timeout 2 nc -v localhost 21

# Get banner and disconnect
(sleep 1; echo "quit") | nc -v hostname 25

# Grab SMTP banner
timeout 2 nc localhost 25

# Get FTP banner
timeout 2 nc localhost 21

# HTTP banner with request
(echo -e "HEAD / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"; sleep 1) | nc localhost 80
```

_exec_
```bash
# Get SSH banner from localhost
timeout 2 nc -v localhost 22 2>&1 | head -1
```

_output_
```bash
SSH-2.0-OpenSSH_8.2p1 Ubuntu 4ubuntu0.5
```

Banner grabbing reveals service type and version, useful for security assessment and troubleshooting.

- SSH sends banner on connection
- HTTP requires proper request format
- Some services require commands before responding
- Timeout prevents hanging on non-responsive services

#### Automated service detection

```bash
# Scan and grab banners from open ports
for port in 21 22 25 53 80 443 3306 5432 8080; do
  echo "Port $port:"
  timeout 1 nc -v localhost $port 2>&1 | head -2
  echo "---"
done

# Create service detection script
#!/bin/bash
for ip in $(seq 1 254); do
  host="192.168.1.$ip"
  timeout 1 nc -z -v $host 22 2>&1 | grep succeeded && \
  timeout 1 nc -v $host 22 2>&1 | head -1
done

# Grab all banners from target
for port in $(seq 1 65535); do
  timeout 0.1 nc -v localhost $port 2>&1 | grep -i "succeeded\|version\|ssh\|http" && echo "Port: $port"
done

# Parallel banner grabbing with GNU parallel
seq 1 1024 | parallel "timeout 1 nc -v localhost {} 2>&1" | grep -i version
```

_exec_
```bash
# Simple service detection on common ports
for port in 22 25 80 3306; do
  banner=$(timeout 1 nc -v localhost $port 2>&1 | head -1)
  if [ -n "$banner" ]; then
    echo "Port $port: $banner"
  fi
done
```

_output_
```bash
Port 22: SSH-2.0-OpenSSH_8.2p1 Ubuntu 4ubuntu0.5
```

Automated banner grabbing across multiple ports provides comprehensive service identification for network reconnaissance.

- Create service detection scripts for network audits
- Use parallel processing for faster scanning
- Always have permission before scanning
- Document findings for security analysis
- Be respectful of network resources

**Best practices:**

- Only grab banners from systems you own or have permission to test
- Document all banners found for security audits
- Use short timeouts to avoid connection delays
- Combine with other reconnaissance tools

**Common errors:**

- **No banner received**: Some services require specific requests, use echo with proper protocol
- **Timeout without banner**: Service may not send banner on connect, send appropriate command

## Advanced Usage

Master advanced netcat techniques for complex network operations

### Proxy and Tunneling

Use netcat for proxying and creating network tunnels

**Keywords:** proxy, tunnel, forwarding, relay, bridge

#### Create network proxies and tunnels

```bash
# Simple TCP proxy/tunnel
nc -l 8080 | nc target.example.com 80 &

# Bidirectional proxy using mkfifo
mkfifo /tmp/proxy_in /tmp/proxy_out
cat /tmp/proxy_in | nc target 8080 | tee /tmp/proxy_out &
cat /tmp/proxy_out | nc -l 8000 > /tmp/proxy_in

# Transparent relay
while true; do nc -l 3000 | nc backend_server 3000; done

# HTTP proxy to backend
nc -l 8000 | nc internal.example.com 8080

# Tunnel SSH connection through proxy
nc -X connect -x proxy.example.com:8080 target 22

# SOCKS proxy (if supported)
nc -X socks5 -x localhost:1080 target 80

# Persistent tunnel in background
(while true; do nc -l 9000 | nc remote 9001; done) &
```

_exec_
```bash
# Create simple proxy between ports
(nc -l 8003 | nc localhost 22 &) &
PROXY_PID=$!
sleep 1
timeout 1 nc -v localhost 8003 2>&1 | head -2
kill $PROXY_PID 2>/dev/null
```

_output_
```bash
Connection to localhost 8003 port 8003 [tcp/*] succeeded!
SSH-2.0-OpenSSH_8.2p1 Ubuntu 4ubuntu0.5
```

Netcat can create network proxies by relaying connections between endpoints, useful for traffic inspection and routing.

- Use named pipes (mkfifo) for bidirectional proxies
- Proxies can add latency and affect performance
- Logging can help understand traffic flow
- Consider security when proxying sensitive data

#### Advanced tunneling scenarios

```bash
# Create encrypted tunnel with SSH
# Forward local 8888 to remote port 3306 through SSH
ssh -L 8888:localhost:3306 user@remote &
nc localhost 8888  # Now connects to remote MySQL

# Reverse tunnel (remote connects to local)
ssh -R 8080:localhost:8000 user@remote

# Multi-hop tunnel
# Via: Local -> Proxy1 -> Proxy2 -> Target
nc -x proxy1:3128 -X connect -x proxy2:3128 target 80

# Tunnel with compression
nc -l 8000 | gzip | nc server 9000

# Persistent SSH tunnel for multiple connections
ssh -N -f -L 8000:target:80 user@proxy

# Use netcat with tar for secure file transfer
tar czf - /files | nc tunnel 9000

# Create persistent tunnel connection pool
for i in {1..5}; do
  (while true; do nc -l 8000 | nc target 8000; done) &
done
```

_exec_
```bash
# Create compression tunnel test
(nc -l 8004 | gunzip > /tmp/tunnel_out.txt &) &
TUNNEL_PID=$!
sleep 1
echo "Tunnel Test Data" | gzip | nc localhost 8004
sleep 1
kill $TUNNEL_PID 2>/dev/null
cat /tmp/tunnel_out.txt
```

_output_
```bash
Tunnel Test Data
```

Advanced tunneling combines netcat with compression, encryption, and multi-hop routing for complex network scenarios.

- Always secure sensitive tunnels with encryption
- Monitor tunnel performance and bandwidth
- Implement timeout and error handling
- Document tunnel topology for maintenance

**Best practices:**

- Encrypt sensitive tunnels with SSH or TLS
- Monitor proxy and tunnel traffic
- Use persistent tunnels for production systems
- Test failover and redundancy

**Common errors:**

- **'Address already in use' on proxy port**: Wait for TIME_WAIT or use SO_REUSEADDR option
- **Tunnel becomes unresponsive**: Monitor connection timeouts and implement keep-alive

### Troubleshooting & Telnet Replacement

Use netcat for network troubleshooting and telnet replacement

**Keywords:** troubleshooting, debugging, telnet, replacement, diagnostic

#### Network troubleshooting and connectivity testing

```bash
# Test basic TCP connectivity (telnet replacement)
nc -v example.com 80

# Check if port responds (telnet replacement with timeout)
nc -zv -w 5 example.com 443

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

# Debug connection issues
nc -vvv example.com 80  # Extra verbose

# Test with packet tracing
strace -e openat,connect nc -v example.com 80

# Check DNS resolution and connectivity
nc -v $(dig +short example.com | head -1) 80

# Test with different TCP options
nc -T noDelay example.com 80

# Trace connection path
traceroute example.com && nc -v example.com 80
```

_exec_
```bash
# Test SSH connectivity
timeout 2 nc -vz localhost 22
echo "Exit Code: $?"
```

_output_
```bash
Connection to localhost port 22 [tcp/ssh] succeeded!
Exit Code: 0
```

Netcat provides reliable connectivity testing and protocol debugging without the overhead of full telnet client.

- -zv combination is fastest for simple connectivity checks
- Use multiple -v flags for extra verbosity in debugging
- -w timeout prevents hanging on unreachable hosts
- Check exit codes for scripting

#### Protocol testing and service validation

```bash
# Test HTTP server response
(echo -e "GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"; sleep 1) | nc localhost 80

# Test SMTP server
(sleep 1; echo "QUIT") | nc localhost 25 | head -5

# Test FTP server
(echo "QUIT") | nc localhost 21

# Test custom protocol
echo "COMMAND arg1 arg2" | nc server.example.com 9000

# Validate server response format
timeout 2 nc -v localhost 3306 2>&1 | od -c | head -5

# Test keep-alive behavior
(echo "PING"; sleep 5; echo "PING") | nc server 5000

# Build protocol conversation step by step
(
  echo "USER username"
  sleep 0.5
  echo "PASS password"
  sleep 0.5
  echo "QUIT"
) | nc -v server.example.com 21

# Capture and analyze server responses
nc -v server 80 > response.txt 2>&1
```

_exec_
```bash
# Test simple HTTP server response
(echo -e "GET / HTTP/1.0\r\nHost: localhost\r\n\r\n"; sleep 1) | nc localhost 80 | head -3
```

_output_
```bash
HTTP/1.0 200 OK
Server: SimpleHTTP/0.6 Python/3.8.10
Date: Fri, 28 Feb 2025 10:00:00 GMT
```

Protocol testing with netcat allows direct interaction with services and validation of protocol compliance.

- \r\n is required for HTTP headers
- Some protocols require specific command sequences
- Use od -c to analyze binary responses
- Log interactions for documentation

**Best practices:**

- Use timeout to prevent hanging connections
- Implement proper protocol format (headers, line endings)
- Log successful connections for documentation
- Test both positive and negative scenarios

**Common errors:**

- **Connection reset by peer**: Server may not accept command, check protocol requirements
- **Unexpected EOF while reading**: Server closed connection, ensure keep-alive or proper close sequence
