Menu

Netcat basics and a few smart examples

23 April 2014

The nc (or netcat) utility is used for just about anything under the sun involving TCP or UDP - manpage

Netcat is like a more powerful version of telnet, and is perfect to handle all kind of socket and simple network testing. With netcat you can eg. do port scanning, create a webserver, handle sockets in general, and do file transfering in its smartest way (heard of people using it for transfering disk clones piped from dd to nc).

Very basic ones

Telnet-like usage

Connection to port 80 at localhost (try with different hosts or urls):

$ nc localhost 80

Simplest socket server

Starting socket server on port 5000:

nc -l 5000

Chat functionality

If you combine these two and connect to the simple socket server, and write something it will appear on the other computer and vice versa.

Webserver

Very useful for simple html. Could be a test of port 80 in its simplest manner, or a maintenance page.

Create some html in a document (and call it eg. index.html), and run the following to make it listen on port 80 with content from your newly created index.html-file:

$ while true; do; sudo nc -l 80 < index.html; done

The while loop makes it possible to render the page for more than one connection.

Transfer file

Lets start the socket server with the index.html file we made earlier:

$ nc -l 5000 < index.html

To connect from the client machine and get the file do:

$ nc aarvik.dk 5000 > index.html

To do the disk clone + transfer example i mentioned in the beginning it would be something like this from the server:

$ dd if=/dev/vda | nc -l 5000

To get the file from the client:

$ nc -n aarvik.dk 5000 | dd of=/dev/vda

Got some comments about how smart nc are with compressed directories and if you do not got space to hold the compressed dir on your partition. Then you can do something like the following, on the server: