9

I want to use netcat as a proxy to log http requests and responses to files, then tail these to inspect traffic. Think wireshark.

Tried the following where 'fifo' is a named pipe, 'in' and 'out' are files, netcat proxy on port 8080, server on port 8081.

while true; do cat fifo | nc -l -p 8080 | tee -a in | nc localhost 8081 | tee -a out 1>fifo; done

Problems:

  • Netcat stop responing after first request (while loop ignored?).

  • Netcat fails with msg localhost [127.0.0.1] 8081 (tproxy) : Connection refused if server unavailable on 8081. Question: Is it possible to "lazily" connect to 8081 when request is made? I.e. I do not want to have 8081 running when netcat is started.

HackToHell
  • 6,328
  • 3
  • 38
  • 62
deephacks
  • 191
  • 1
  • 1
  • 2

3 Answers3

11

ncat can do this quite easily, using the --sh-exec argument.

The following command will allow you to see both directions of a TCP connection live, and allows multiple connections. The connection to example.com is done once for each connection received on localhost:8080.

ncat -lkv localhost 8080 -c 'tee /dev/stderr | ncat -v example.com 80 | tee /dev/stderr'

Change the two tee commands to tee -a ./file if you wish to log to a file instead of displaying it live. You can also remove the -v to disable verbose output, leaving just the transfered data printed to the terminal.

-k, --keep-open            Accept multiple connections in listen mode
-l, --listen               Bind and listen for incoming connections
-v, --verbose              Set verbosity level (can be used several times)
-c, --sh-exec <command>    Executes the given command via /bin/sh

See ncat --help or man ncat for more details.

Oddstr13
  • 331
  • 3
  • 8
5

Use socat, you don't need the pipes and fifos

RedGrittyBrick
  • 81,981
  • 20
  • 135
  • 205
  • Works good. Im able to see the response now. But how do I make socat stay alive for subsequent requests? Tried `while true; do socat -v tcp-listen:8080,keepalive=1 tcp:localhost:8081; done` and `socat -v tcp-listen:8080,keepalive=1 tcp:localhost:8081 ` – deephacks Oct 06 '12 at 17:40
  • 1
    Try [`fork`](http://www.dest-unreach.org/socat/doc/socat.html#OPTION_FORK) as in `socat -v tcp-listen:8080,fork tcp:localhost:8081` – RedGrittyBrick Oct 07 '12 at 09:56
2

I'd use tcpdump (tutorial) for this. I think the command you want would look like this:

sudo tcpdump -i eth0 -s0 -v port 8080
garyjohn
  • 34,610
  • 8
  • 97
  • 89
  • 3
    tcpdump only show raw packets which are hard to read. tcpflow does exactly what I want and eliminate the need to proxy request/response. `sudo tcpflow -p -i lo -c port 8081` – deephacks Oct 06 '12 at 21:23