AllGoodBits.org

Network Socket Programming with netcat(1) and shell

netcat

Sometimes we want to send or receive data across the network directly, using lightweight tools providing as much visibility as possible. netcat is one such tool.

Here is a minimal example of sending:

cat file | nc <remotehost>.example.com -p <portnumber>

Yes, this is just one simple way, there are others, possibly better [1].

Sometimes we want to receive data easily:

nc -l -p <portnumber> [| <some command>] > $HOME/outputfile

Once I wanted to receive data, save it and send it on elsewhere. This listens on 8192, saves to a file, prepends an identifier (which happened to be an API key for a SaaS) and sends it on to a specified port on a remote host:

These kinds of command patterns are excellent examples of the great power and flexibility enabled by unix pipes. Either of those pipelines could easily have other commands added, here are a couple of simple examples.

shell

Some shells create pseudo-devices that represent network sockets that present just as ordinary files and can read from and written in the same ways. I know that it has worked with bash(1) for years and ksh(1) at least since ksh-93, perhaps before.

This opens a socket on port 80 of remotehost.example.com, makes an HTTP request, and displays the reply: