Linux Port Forwarding with Socat – Is It Possible?

linuxport-forwardingsocatsocket

Is there any way to listen and execute a command ( for every connection ) while port forwarding with socat? A non-working example to make it more clear:

socat TCP-LISTEN:8080,reuseaddr, "exec:ls" fork tcp:localhost:80

Best Answer

Like this?

socat tcp-listen:8080,reuseaddr,fork system:'ls; exec socat - tcp\:localhost\:80'
  • 1st parameter gets ,fork to have socat stay listening for more connections

  • system: is preferred over exec: to have a shell interpreter and easily run an additional command after the ls command,

  • which is a new socat command

    which will have stdin/stdout connected to the remote client's output/input and will forward it bidirectionally again to the next destination. Note that its : separator (and a few other special characters) must be escaped with a \ to not confuse the first socat command. If this line becomes more complex it become easier to simply exec a script like this:

    socat tcp-listen:8080,reuseaddr,fork exec:/path/to/myscript.sh
    

    with /path/to/myscript.sh:

    #!/bin/sh
    ls
    exec socat - tcp:localhost:80
    

    exec in the shell command is optional but avoids uselessly leaving around the shell.

socat also exports a few variables of its own that can be reused in the script, that you could check for example like this (with a connection made):

$ env - socat TCP-LISTEN:8080,reuseaddr,fork exec:printenv
SOCAT_PID=1057351
SOCAT_PPID=1057284
SOCAT_VERSION=1.7.4.1
SOCAT_SOCKADDR=127.0.0.1
SOCAT_SOCKPORT=8080
SOCAT_PEERADDR=127.0.0.1
SOCAT_PEERPORT=42970
Related Topic