Source: http://www.stearns.org/doc/nc-intro.v0.80.html
A generic tcp proxy
There's one rather interesting use for netcat that comes in very handy when debugging network traffic. Remember our first example? We wanted to see the exact stream of characters returned from a remote server. What if we want to see all the requests coming in from people to one of our servers, and exactly what is sent back to them? It's not all that hard.
Let's monitor the web server we have on mason.stearns.org. First of all, we need to tell that server to listen on another port, say 81. That's done by editing "/etc/httpd/httpd.conf", changing "Listen 80" to "Listen 127.0.0.1:81" and restarting the web server.
Now we'll set up a server netcat to listen on port 80. We'll also set up a client netcat to talk to the real web server on port 81. By getting them to pass all data they receive to each other, together they form a proxy; something that sits in the middle of a network connection. Here are the commands we use:
mknod backpipe p
nc -l -p 80 0<backpipe | tee -a inflow | nc localhost 81 | tee -a outflow 1>backpipe
Because bash pipes only carry data in one direction, we need to provide a way to carry the responses as well. We can create a pipe on the local filesystem to carry the data in the backwards direction with the mknod command; this only needs to be run once.
Requests coming into the proxy from the client arrive at the first nc, listening on port 80. They get handed off to the "tee" command, which logs them to the inflow file, then continue on to the second nc command which hands them off to the real web server. When a response comes back from the server, it arrives back at the second nc command, gets logged in the second tee command to the outflow file, and then gets pushed into the backpipe pipe on the local filesystem. Since the first netcat is listening to that pipe, these responses get handed to that first netcat, which then dutifully gives them back to the original client.
The exact form of the nc-tee-nc-tee command line will depend on whether this will be started by hand or in a boot script, and whether you want it to restart automatically or you just need to look at a single connection. Something similar to the above "nohup su nobody -c 'while...done' & will give a persistent proxy startable from the boot scripts, but this may need a little tweaking.
While the above example is for watching tcp streams going to and from a web server, the above technique is useful for watching any tcp connection. In fact, since nc also works with udp packets - something telnet can't do - it should be possible to even set up udp proxies this way.