Skip to content

How to proceed TCP/UDP port forwarding with socat

homepage-banner

TCP port forwarding with socat

socat -d TCP4-LISTEN:80,reuseaddr,fork TCP4:127.0.0.1:8080

# specify listening address
socat -d TCP4-LISTEN:80,reuseaddr,fork,bind=127.0.0.1 TCP4:10.10.1.1:8888

UDP port forwarding with socat

socat -T 600 UDP4-LISTEN:5353,reuseaddr,fork UDP4:114.114.114.114:53
  • -u unidirectional stream transfer, the stream of data runs from the first argument, to the second argument
  • -U data transfer from the second argument to the first argument
  • open call system open()
  • tcp-listen listen tcp port
  • create if file not exists, create a new one
  • reuseaddr reuse address
  • fork fork a new process for each connection
  • forever keep listening, intervall=1 reconnect every 1 second
  • -d log level, -d -d debug level, -d -d -d trace level

File transfer with socat

On Server side

socat -u open:FILENAME tcp-listen:12345

On Client side

socat -u tcp:ServerIP:12345 open:LOCALFILE,create

Split Read/Write

socat open:hello.html\!\!open:log.txt,create,append tcp-listen:12345,reuseaddr,fork
  • !! read in LHS, write in WHS
  • open:hello.html read hello.html file
  • open:log.txt write to log.txt

Other tools and methods

Port forwarding with SSH

Refer to How to Use ssh tunnel

Port forwarding with iptables

You can also use iptables to configure port forwarding in Linux. Configuring port forwarding in Linux involves modifying the iptables using the command-line interface.

sudo iptables -A INPUT -p tcp --dport {port_number} -j ACCEPT

sudo iptables -t nat -A PREROUTING -p tcp --dport {port_number} -j DNAT --to-destination {destination_ip_address}:{destination_port_number}

This command forwards incoming traffic on the specified port to the specified device on your network. Once these commands are executed, your Linux machine will be able to receive incoming traffic on the specified port.

Reference

  • https://man.imzye.com/Linux/socat/
  • http://www.dest-unreach.org/socat/doc/socat.html
Feedback