Netcat - the TCP/IP Swiss army knife

nc (Netcat)

Usage :

Netcat is known as the "network Swiss-army knife".

Flags :

Flag Usage
-l listen mode
-n numeric-only IP addresses, no DNS
-p xxxx local port number. xxxx can be a single port or a range of ports : lo-hi (inclusive)
-q n after EOF on stdin, wait n seconds, then quit
-s x.x.x.x use x.x.x.x as the source address
-u UDP mode (default is TCP)
-v verbose output (Use this to see error messages)
-w n wait n seconds before timeout
-z zero-I/O mode : scan for listening processes without sending any data to them

Example :

Scan ports of a host :

Ports list :
nc -vzw5n 10.113.63.103 80 443
Ports range :
nc -z 10.121.108.7 1-1023

Check a remote port is open :

An iptables rule such as :
REJECT	all	--	0.0.0.0/0	0.0.0.0/0	reject-with icmp-host-prohibited
will make this test fail displaying :
No route to host
TCP :

nc -vz ipAddress tcpPort

  • nc -w 5 -z 12.15.44.21 25 > /dev/null && echo OPEN || echo NOT OPEN
  • nc -w 5 -z 12.15.44.21 25 && echo OPEN || echo NOT OPEN
UDP :
nc -vzu host.example.com 160

Test hosts + ports via SSH :

sourceServers='server1 server2 server3'; destinationList='ip.add.ress.1 ip.add.ress.2 ip.add.ress.3'; portList='80 443'; for server in $sourceServers; do for destination in $destinationList; do for port in $portList; do echo -e "\nTESTING FROM '$server' TO '$destination:$port'"; ssh -q $server "nc -nvw3z $destination $port"; done; done; done

Transfer files :

On the receiver side, having IP 192.168.3.112, listen on port 8888 :
  • nc -l -p 8888 > destinationFile
  • nc -l -p 8888 | pv -W > destinationFile
On the sender side :
  • nc 192.168.3.112 8888 < sourceFile
  • cat sourceFile | nc -q 5 192.168.3.112 8888
  • pv sourceFile | nc 192.168.3.112 8888
  • cat sourceFile | pv -b | nc 192.168.3.112 8888

pv is a utility allowing to monitor the progress of data through a pipe. It is optional here. (More on pv)

Setup a remote shell (source) :

on the remote host, having IP 192.168.3.112, listening on port 8888 :
nc -l -p 8888 -v -e /bin/bash
on the local host :
nc 192.168.3.112 8888

Go through an HTTP proxy (source) :

nc localhost 8080

GET www.google.com/
HEAD www.google.com/
HEAD www.google.com/ HTTP/1.0
HEAD www.google.com/ HTTP/1.1

==> the final 'HTTP/1.x' causes an HTTP 504 (???)






telnet localhost 8080
HEAD http://www.google.com/	+  + 
	==> HTTP/1.1 302 Found

HEAD http://www.google.com/ HTTP/1.0	+  + 
	==> HTTP/1.1 302 Found

HEAD http://www.google.com/ HTTP/1.1	+  + 
	==> HTTP 302

HEAD http://www.google.fr/ HTTP/1.1	+  + 
	==> HTTP 200