Skip to content

TCP/UDP port forwarding with socat



Port forwarding is an essential tool for network administrators and home users alike. It allows traffic to pass through a specified port on a firewall or router to reach a designated device on a network. In this blog post, we will explore the basics of port forwarding in Linux, how it works, and how to configure it.

TCP port forwarding with socat

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

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

UDP port forwarding with socat

socat -T 600 UDP4-LISTEN:5353,reuseaddr,fork UDP4:
  • -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.



Small world. Big idea!
  • Welcome to visit the knowledge base of SRE and DevOps!
  • License under CC BY-NC 4.0
  • Made with Material for MkDocs and improve writing by generative AI tools
  • Copyright issue feedback, replace # with @