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.

3 Answers 3

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.

1
  • And this outputs http headers in proxied connections: 'ncat -lvvv --proxy-type http localhost 8888' Feb 3, 2021 at 21:29
5

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

2
  • 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 6, 2012 at 17:40
  • 1
    Try fork as in socat -v tcp-listen:8080,fork tcp:localhost:8081 Oct 7, 2012 at 9: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
1
  • 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 6, 2012 at 21:23

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .