Search code examples
bashsocat

HTTP Multiple Port Forwarding with SOCAT/Bash


I am attempting to set up a shell script to listen on a port, forward to n different IP addresses, and return the result of one of those API calls.

If I have one IP address, the solution is straightforward with

socat TCP4-LISTEN:8080,fork,reuseaddr,crlf tcp4:127.0.0.1:8000

Where a REST API is on port 8000, and I am listening on port 8080.

For the multiple IP case, it seems like I need to use tee in some capacity to split into multiple API calls, as such:

socat TCP4-LISTEN:8080,fork,reuseaddr,crlf - | tee \
      >(socat - tcp4:127.0.0.1:8000 | cat; echo "This ends") \
      >(socat - tcp4:127.0.0.1:8000 | cat; echo "This ends too")
      >/dev/null

While I am able to print out the API calls from inside and the inner socat calls terminate (as This ends and This ends too are both getting printed when making a call on port 8080), the outer socat call does not return anything. Is there a way to return one of the tee values for the outer socat?


Solution

  • A potential solution to the problem is to create a handler script that takes the TCP-listen input and handles it.

    router.sh:

    socat TCP-LISTEN:8080,fork,reuseaddr EXEC:"bash -e ./route_handler.sh"
    

    route_handler.sh:

    tee >(socat - TCP4:127.0.0.1:8001 >> /dev/null) | socat - TCP4:127.0.0.1:8000
    

    When port 8080 is hit, the results are sent to the localhost ports 8000 and 8001 are called. The output from port 8000 is returned to the TCP listener.