---
title: "Netcat"
lang: "en"
author: "Mohammad Abu Mattar"
canonical: https://mkabumattar.com/nc
---

[Home](/)›[Cheatsheets](/cheatsheets)

Cheatsheets

# Netcat

Complete netcat reference covering TCP/UDP connections, file transfers, server testing, port scanning, banner grabbing, and network troubleshooting with practical examples

6 Categories12 Sections24 ExamplesPublished: 01 Jan 2023Updated: 28 Feb 2025

NetcatncNetworkTCP/UDPPort ScanningNetworkingServer Testing

[Markdown for AI(opens in a new tab)](/nc/index.md "Open the plain-Markdown version of this page, for pasting into an AI tool")

Series

[Linux & System Administration](/series/linux--system-administration)8/12

[PreviousGrep](/cheatsheets/grep)[NextNetstat](/cheatsheets/netstat)

All posts in this series (12)

Cheatsheets12

1.  [AWK](/cheatsheets/awk)
2.  [Bash](/cheatsheets/bash)
3.  [Chmod](/cheatsheets/chmod)
4.  [Cron](/cheatsheets/cron)
5.  [Curl](/cheatsheets/curl)
6.  [Find](/cheatsheets/find)
7.  [Grep](/cheatsheets/grep)
8.  [NetcatYou are here](/cheatsheets/nc)
9.  [Netstat](/cheatsheets/netstat)
10.  [Sed](/cheatsheets/sed)
11.  [SSH](/cheatsheets/ssh)
12.  [Linux Networking](/cheatsheets/linux-networking)

This netcat cheatsheet covers TCP/UDP connections, file transfers, port scanning, banner grabbing, and advanced network operations.

[Getting Started](#category-getting-started)

-   [What is Netcat](#section-what-is-netcat)
-   [Netcat vs Alternatives](#section-netcat-vs-alternatives)

[Basic Connections](#category-basic-connections)

-   [TCP Client Connections](#section-tcp-client-connections)
-   [TCP Listen Server](#section-tcp-listen-server)

[Protocol Options](#category-protocol-options)

-   [UDP Connections](#section-udp-connections)
-   [IPv6 Connections](#section-ipv6-connections)

[Data Transfer](#category-data-transfer)

-   [File Transfer](#section-file-transfer)
-   [Bidirectional Communication](#section-bidirectional-communication)

[Port Scanning & Discovery](#category-port-scanning-discovery)

-   [Port Scanning](#section-port-scanning)
-   [Banner Grabbing & Service Detection](#section-banner-grabbing)

[Advanced Usage](#category-advanced-usage)

-   [Proxy and Tunneling](#section-proxy-tunneling)
-   [Troubleshooting & Telnet Replacement](#section-troubleshooting-telnet-replacement)

No commands found

Try adjusting your search term

## Getting Started

Introduction to netcat and its capabilities for network operations

### What is Netcat

Netcat and its role in network operations and diagnostics

#### Accessibility

Clear introduction to netcat capabilities and practical use cases

#### 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

#### Keywords

introductionwhataboutnetcatnetworkutility

[Learn more](https://man.openbsd.org/nc)

#### Install and verify netcat installation

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

Code

Terminal window

```
# On Debian/Ubuntu systemssudo apt-get updatesudo apt-get install netcat-openbsd
# Alternative: Traditional netcatsudo apt-get install netcat
# On CentOS/RHEL systemssudo yum install nc
# On Fedora systemssudo dnf install nc
# Verify installationwhich ncnc -h 2>&1 | head -3
```

Execution

Terminal window

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

Output

Terminal window

```
/bin/ncNetcat is installed
```

-   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

Netcat handles different network operations through its flags.

Code

Terminal window

```
# 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] portecho "Netcat is ready for network operations"
```

Execution

Terminal window

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

Output

Terminal window

```
-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
```

-   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 broader network diagnostics

### Netcat vs Alternatives

Compare netcat with other networking tools for different use cases

#### Accessibility

Understanding when to use netcat vs other networking tools

#### 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 to process data

#### 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

#### Keywords

comparisonalternativestoolstelnetcurl

[Learn more](https://nmap.org/ncat/)

#### Netcat vs telnet and curl comparison

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

Code

Terminal window

```
# 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"
```

Execution

Terminal window

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

Output

Terminal window

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

-   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 more complete network diagnostics

#### When to use netcat in your workflow

Netcat covers the network administration tasks that need direct network control and raw data access.

Code

Terminal window

```
# 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"
```

Execution

Terminal window

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

Output

Terminal window

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

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

## Basic Connections

TCP and UDP client-server connections with netcat

### TCP Client Connections

Create TCP client connections to remote servers

#### Accessibility

Commands to establish and manage TCP connections

#### 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

#### Keywords

tcpclientconnectionremoteserver

[Learn more](https://man.openbsd.org/nc)

#### Connect to remote TCP servers and interact

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

Code

Terminal window

```
# Basic TCP connection to a servernc hostname port
# Connect to localhost on port 8080nc 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 connectionecho "Hello Server" | nc hostname port
# Connect with specific local portnc -p 8888 example.com 80
```

Execution

Terminal window

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

Output

Terminal window

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

-   TCP guarantees 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

Interactive communication lets you manually test server protocols and see how services respond to requests.

Code

Terminal window

```
# Interactive connection (type commands after connecting)# nc hostname port# Then type your input and press Enter
# Simple telnet replacementnc 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 secondsnc -w 3 example.com 80
# Set timeout without closing automaticallync -N example.com 80
```

Execution

Terminal window

```
# 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

Terminal window

```
HTTP/1.1 200 OKServer: Apache/2.4.41Date: Fri, 28 Feb 2025 10:00:00 GMTContent-Type: text/htmlConnection: close
```

-   \\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

### TCP Listen Server

Create TCP listening servers with netcat

#### Accessibility

Commands to start TCP listening servers

#### 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

#### Keywords

tcpserverlistenacceptport

[Learn more](https://man.openbsd.org/nc)

#### Start listening server and accept connections

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

Code

Terminal window

```
# Start listening server on port 8888nc -l 8888
# Listen on specific IP and portnc -l localhost 8888
# Listen in verbose modenc -l -v 8888
# Listen only once (accept one connection then exit)nc -l 8888
# Set verbosity for debuggingnc -l -vv 8888
# Listen on IPv6nc -6 -l 8888
```

Execution

Terminal window

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

Output

Terminal window

```
Test message
```

-   \-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

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

Code

Terminal window

```
# Listen and handle multiple connections# Use in a loop to accept new connectionswhile true; do nc -l 8888; done
# Listen and log all input to filenc -l 8888 >> /tmp/nc.log
# Listen and echo input back to clientmkfifo /tmp/fifonc -l 8888 < /tmp/fifo | tee /tmp/fifo > /dev/null
# Listen with timeouttimeout 30 nc -l 8888
# Listen and execute command for each connectionwhile true; do nc -l 8888 -e /bin/bash; done
```

Execution

Terminal window

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

Output

Terminal window

```
Server message
```

-   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

## Protocol Options

Work with different network protocols and connection types

### UDP Connections

Use UDP protocol for fast, connectionless communication

#### Accessibility

Commands for UDP communication and testing

#### 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

#### Keywords

udpconnectionlessdatagramprotocolfast

[Learn more](https://man.openbsd.org/nc)

#### UDP client and server communication

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

Code

Terminal window

```
# UDP client to send dataecho "UDP Message" | nc -u hostname 5000
# UDP listening servernc -u -l 5000
# UDP with verbose outputnc -u -v localhost 5000
# UDP timeout on clientecho "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 IPecho "Data" | nc -u -s 192.168.1.100 8.8.8.8 53
```

Execution

Terminal window

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

Output

Terminal window

```
UDP Test
```

-   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

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

Code

Terminal window

```
# Test DNS resolution (requires dig or nslookup usually)# But can send raw UDP to DNS serverecho "Test" | nc -u 8.8.8.8 53
# Listen for incoming UDP messagesnc -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 portecho "Data" | nc -u -p 5555 localhost 5000
# Test UDP with multiple serversfor server in 8.8.8.8 1.1.1.1; do  echo "Test" | timeout 1 nc -u $server 53done
```

Execution

Terminal window

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

Output

Terminal window

```
UDP Communication Test
```

-   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

### IPv6 Connections

Work with IPv6 addresses and dual-stack networking

#### Accessibility

Commands for IPv4 and IPv6 network operations

#### 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

#### Keywords

ipv6ipv4dual-stackaddress-familynext-generation

[Learn more](https://man.openbsd.org/nc)

#### IPv6 client and server connections

Netcat works over both IPv4 and IPv6, selected with explicit flags.

Code

Terminal window

```
# Connect to IPv6 servernc -6 ::1 8080
# Connect to IPv6 address with zone IDnc -6 fe80::1%eth0 8080
# Listen on IPv6 addressnc -6 -l ::1 8080
# Listen on all IPv6 interfacesnc -6 -l :: 8080
# Specify both IPv4 and IPv6nc -4 localhost 8080  # IPv4nc -6 localhost 8080  # IPv6
# Force IPv4 onlync -4 -l 0.0.0.0 8080
# Force IPv6 onlync -6 -l :: 8080
```

Execution

Terminal window

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

Output

Terminal window

```
IPv6 available
```

-   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

IPv6 and IPv4 run side by side on dual-stack hosts. Test both address families when a service has to answer on either.

Code

Terminal window

```
# 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 connectivityecho "IPv4 Test" | nc -4 -w 1 127.0.0.1 8080echo "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 portsnc -6 -z -w 1 ::1 22 2>&1
```

Execution

Terminal window

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

Output

Terminal window

```
IPv6 Protocol Test
```

-   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:

## Data Transfer

Transfer files and data across networks with netcat

### File Transfer

Send files between machines using netcat

#### Accessibility

Commands for secure and efficient file transfer

#### Best Practices

-   Compress before sending to cut transfer size
-   Use timeouts to prevent hanging connections
-   Verify checksums for data integrity
-   Use progress indicators for large transfers

#### Common Errors

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

#### Keywords

filetransfersendreceivecopy

[Learn more](https://man.openbsd.org/nc)

#### Transfer files between machines

Netcat transfers files by piping stdin and stdout, for both text and binary data.

Code

Terminal window

```
# 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 informationcat large_file.iso | pv | nc hostname 8888
# Receive file and savenc -l 8888 < file.txt
# Transfer binary filescat binary.bin | nc hostname 8888nc -l 8888 > binary.bin
# Keep server listening for multiple fileswhile true; do nc -l 8888 > file_$(date +%s).txt; done
```

Execution

Terminal window

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

Output

Terminal window

```
Received: Test file content
```

-   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

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

Code

Terminal window

```
# 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 pvtar czf - /source | pv | nc hostname 8888
# Receive and decompress simultaneouslync -l 8888 | tar xzf - -C /path/
# Transfer with MD5 verificationtar czf - /source | nc hostname 8888 &md5sum /source > /tmp/source.md5
# Receive side:nc -l 8888 | tar xzf - && md5sum -c /tmp/source.md5
# Transfer exclude patternstar czf - --exclude='.git' --exclude='node_modules' . | nc hostname 8888
```

Execution

Terminal window

```
# Create test directory and transfermkdir -p /tmp/test_dir/subdirecho "file1" > /tmp/test_dir/file1.txtecho "file2" > /tmp/test_dir/subdir/file2.txt(nc -l 9996 | tar xz -C /tmp/ &) &PID=$!sleep 1tar czf - -C /tmp test_dir | nc localhost 9996sleep 2kill $PID 2>/dev/nullfind /tmp/test_dir -type f
```

Output

Terminal window

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

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

### Bidirectional Communication

Enable two-way data exchange between netcat client and server

#### Accessibility

Commands for interactive bidirectional messaging

#### 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:** Check both sides of the connection are still active

#### Keywords

bidirectionaltwo-waycommunicationinteractionexchange

[Learn more](https://man.openbsd.org/nc)

#### Interactive bidirectional chat

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

Code

Terminal window

```
# 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 respondingmkfifo /tmp/chat_innc -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 servermkfifo /tmp/fifocat /tmp/fifo | nc -l 5555 | tee /tmp/fifo
```

Execution

Terminal window

```
# Demonstrate bidirectional with pipesmkfifo /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.txtsleep 1kill $PID 2>/dev/nullcat /tmp/bc_log.txt
```

Output

Terminal window

```
Message 1Message 2
```

-   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

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

Code

Terminal window

```
# Create relay between two connections# Listen on one port, forward to another
# Method 1: Simple relay with teenc -l 5556 | tee /tmp/relay_log.txt | nc remote_host 5000
# Method 2: Bidirectional relay with pipesmkfifo /tmp/relay_in /tmp/relay_outcat /tmp/relay_in | nc -l 5556 > /tmp/relay_outcat /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 loggingwhile true; do  nc -l 5556 | tee -a relay.log | nc server.example.com 5000done
# Bidirectional pipe relay{ cat; echo; } | nc localhost 5000
```

Execution

Terminal window

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

Output

Terminal window

```
Relay Test Message
```

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

## Port Scanning & Discovery

Scan ports and discover network services with netcat

### Port Scanning

Identify open ports on networked systems

#### Accessibility

Commands to scan for open ports efficiently

#### 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

#### Keywords

scanningportsdiscoveryopenservice

[Learn more](https://man.openbsd.org/nc)

#### Basic port scanning techniques

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

Code

Terminal window

```
# Scan single portnc -zv localhost 22
# Scan port rangenc -zv localhost 1-1024
# Scan with timeoutnc -zv -w 1 localhost 1-65535
# Scan specific ports onlync -zv localhost 22 80 443
# Scan with connection timeouttimeout 10 bash -c 'nc -zv localhost 1-1024'
# Scan and redirect outputnc -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"
```

Execution

Terminal window

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

Output

Terminal window

```
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).
```

-   \-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

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

Code

Terminal window

```
# Scan and show only open portsnc -zv localhost 1-1024 2>&1 | grep succeeded
# Scan with fast timeoutnc -zv -w 1 localhost 1-65535 2>&1 | grep succeeded
# Scan remote hostnc -zv example.com 1-1024 2>&1 | grep succeeded
# Create a loop for scanning multiple hostsfor host in 192.168.1.{1..10}; do  nc -zv -w 1 $host 22 2>&1 | grep succeededdone
# Scan and save results to filenc -zv localhost 1-65535 2>&1 | grep succeeded | tee /tmp/open_ports.txt
# Complex scan with statisticsfor 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 countnc -zv -w 1 localhost 1-1024 > /tmp/scan.log 2>&1 &waitgrep succeeded /tmp/scan.log | wc -l
```

Execution

Terminal window

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

Output

Terminal window

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

-   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

### Banner Grabbing & Service Detection

Grab service banners for version identification

#### Accessibility

Commands to identify services and their versions

#### 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

#### Keywords

bannergrabbingversionservicedetection

[Learn more](https://man.openbsd.org/nc)

#### Grab service banners and identify versions

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

Code

Terminal window

```
# Grab SSH bannernc -v localhost 22
# Grab HTTP bannerecho "" | nc -v localhost 80
# Connect and send newline for banner(echo; sleep 1) | nc -v hostname 3306
# Grab with timeouttimeout 2 nc -v localhost 21
# Get banner and disconnect(sleep 1; echo "quit") | nc -v hostname 25
# Grab SMTP bannertimeout 2 nc localhost 25
# Get FTP bannertimeout 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
```

Execution

Terminal window

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

Output

Terminal window

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

-   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

Automated banner grabbing across multiple ports identifies services for network reconnaissance.

Code

Terminal window

```
# Scan and grab banners from open portsfor 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/bashfor 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 -1done
# Grab all banners from targetfor 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 parallelseq 1 1024 | parallel "timeout 1 nc -v localhost {} 2>&1" | grep -i version
```

Execution

Terminal window

```
# Simple service detection on common portsfor 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"  fidone
```

Output

Terminal window

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

-   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

## Advanced Usage

Advanced netcat techniques for complex network operations

### Proxy and Tunneling

Use netcat for proxying and creating network tunnels

#### Accessibility

Advanced techniques for network routing and tunneling

#### 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

#### Keywords

proxytunnelforwardingrelaybridge

[Learn more](https://man.openbsd.org/nc)

#### Create network proxies and tunnels

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

Code

Terminal window

```
# Simple TCP proxy/tunnelnc -l 8080 | nc target.example.com 80 &
# Bidirectional proxy using mkfifomkfifo /tmp/proxy_in /tmp/proxy_outcat /tmp/proxy_in | nc target 8080 | tee /tmp/proxy_out &cat /tmp/proxy_out | nc -l 8000 > /tmp/proxy_in
# Transparent relaywhile true; do nc -l 3000 | nc backend_server 3000; done
# HTTP proxy to backendnc -l 8000 | nc internal.example.com 8080
# Tunnel SSH connection through proxync -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) &
```

Execution

Terminal window

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

Output

Terminal window

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

-   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

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

Code

Terminal window

```
# Create encrypted tunnel with SSH# Forward local 8888 to remote port 3306 through SSHssh -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 -> Targetnc -x proxy1:3128 -X connect -x proxy2:3128 target 80
# Tunnel with compressionnc -l 8000 | gzip | nc server 9000
# Persistent SSH tunnel for multiple connectionsssh -N -f -L 8000:target:80 user@proxy
# Use netcat with tar for secure file transfertar czf - /files | nc tunnel 9000
# Create persistent tunnel connection poolfor i in {1..5}; do  (while true; do nc -l 8000 | nc target 8000; done) &done
```

Execution

Terminal window

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

Output

Terminal window

```
Tunnel Test Data
```

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

### Troubleshooting & Telnet Replacement

Use netcat for network troubleshooting and telnet replacement

#### Accessibility

Commands for network diagnostics and protocol testing

#### 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:** The server closed the connection. Use keep-alive or a proper close sequence

#### Keywords

troubleshootingdebuggingtelnetreplacementdiagnostic

[Learn more](https://man.openbsd.org/nc)

#### Network troubleshooting and connectivity testing

Netcat tests connectivity and debugs protocols without the overhead of a full telnet client.

Code

Terminal window

```
# 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 IPnc -s 192.168.1.100 example.com 80
# Debug connection issuesnc -vvv example.com 80  # Extra verbose
# Test with packet tracingstrace -e openat,connect nc -v example.com 80
# Check DNS resolution and connectivitync -v $(dig +short example.com | head -1) 80
# Test with different TCP optionsnc -T noDelay example.com 80
# Trace connection pathtraceroute example.com && nc -v example.com 80
```

Execution

Terminal window

```
# Test SSH connectivitytimeout 2 nc -vz localhost 22echo "Exit Code: $?"
```

Output

Terminal window

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

-   \-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

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

Code

Terminal window

```
# 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 protocolecho "COMMAND arg1 arg2" | nc server.example.com 9000
# Validate server response formattimeout 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 responsesnc -v server 80 > response.txt 2>&1
```

Execution

Terminal window

```
# 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

Terminal window

```
HTTP/1.0 200 OKServer: SimpleHTTP/0.6 Python/3.8.10Date: Fri, 28 Feb 2025 10:00:00 GMT
```

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

Was this useful?

## Tags

#Netcat#Nc#Network#TCP/UDP#Port Scanning#Networking#Server Testing

## Share

[Facebook](https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fnc "Share on Facebook")[Twitter](https://twitter.com/intent/tweet/?text=Netcat&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fnc "Share on Twitter")[LinkedIn](https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fnc&title=Netcat&summary=Complete%20netcat%20reference%20covering%20TCP%2FUDP%20connections%2C%20file%20transfers%2C%20server%20testing%2C%20port%20scanning%2C%20banner%20grabbing%2C%20and%20network%20troubleshooting%20with%20practical%20examples&source=https://mkabumattar.com "Share on LinkedIn")[WhatsApp](https://wa.me/?text=Netcat%20https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fnc "Share on WhatsApp")[Telegram](https://t.me/share/url?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fnc&text=Netcat "Share on Telegram")[Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fnc&title=Netcat "Share on Reddit")[Hacker News](http://news.ycombinator.com/submitlink?u=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fnc&t=Netcat "Share on Hacker News")[Pinterest](https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fnc&media=&description=Complete%20netcat%20reference%20covering%20TCP%2FUDP%20connections%2C%20file%20transfers%2C%20server%20testing%2C%20port%20scanning%2C%20banner%20grabbing%2C%20and%20network%20troubleshooting%20with%20practical%20examples "Share on Pinterest")[Email](<mailto:?subject=Netcat&body=Check out this article: https%3A%2F%2Fmkabumattar.com%2Fcheatsheets%2Fnc>)

## Comments

## You might also enjoy

More posts on similar topics

## [Netstat](/cheatsheets/netstat)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   System Administration
-   Linux
-   Networking
-   Tools

This netstat cheatsheet covers six categories, with worked examples and troubleshooting steps in each.

#Netstat#Network#Connections+3 tags

[read more](/cheatsheets/netstat)

## [Cron](/cheatsheets/cron)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   System Administration
-   Linux
-   Scheduling
-   Automation
-   Tools

Quick reference Field layout Min Hour Day Month Weekday Command\* /path/to/command ┬ ┬ ┬ ┬ ┬ │ │ │ │ └───── Weekday (0=Sunday,

#Cron#Crontab#Scheduling+3 tags

[read more](/cheatsheets/cron)

## [Chmod](/cheatsheets/chmod)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Programming
-   Linux
-   File Management
-   Tools

Complete chmod reference covering file permissions, recursive changes with -v and -c, reference mode, logical operators, batch operations, practical examples, and security best practices for Linux fil

#Chmod#Permissions#File Permissions+5 tags

[read more](/cheatsheets/chmod)

## [Curl](/cheatsheets/curl)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Web Development
-   APIs
-   HTTP
-   Command Line
-   Tools

Getting started with Curl cURL (client URL) is a command-line tool for transferring data using URLs. It speaks HTTP, HTTPS, FTP, SFTP, and many other protocols, which makes it the usual choice for

#Curl#HTTP#REST+3 tags

[read more](/cheatsheets/curl)

## [Find](/cheatsheets/find)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Programming
-   Linux
-   File Operations
-   Tools

Best practices for find command usageAlways quote patterns to prevent shell expansion of special characters Use -type f first in find expressions for optimal performance \*\*Prune hea

#Find#File Search#Discovery+3 tags

[read more](/cheatsheets/find)

## [Grep](/cheatsheets/grep)

-   [Mohammad Abu Mattar](/authors/mohammad-abu-mattar)
-   Terminal
-   Programming
-   Linux
-   Text Processing
-   Tools

Best practices for grep usageAlways quote patterns to prevent shell interpretation of special characters Use -E flag for complex patterns to avoid escaping issues with basic regex

#Grep#Search#Pattern Matching+3 tags

[read more](/cheatsheets/grep)

6 related posts
