Skip to content

TCP/UDP port forward with socat


What is Port Forwarding?

Port forwarding, also known as port mapping, is a method of redirecting internet traffic from one port to another. It is a process of forwarding specific network traffic from one address and port number to another address and port number. Port forwarding is necessary when you have a router or firewall that blocks certain ports by default but requires access to a specific application on that port.

Configuring Port Forwarding with socat

Install socat

## Debian/Ubuntu
sudo apt install socat

## MacOS
brew install socat

TCP port forwarding

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

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

UDP port forwarding

socat -T 600 UDP4-LISTEN:5353,reuseaddr,fork UDP4:

Expose internal port to remote server

For example, we want to expose the ssh service of internal server without static public IP to a external server which has a static public IP.

On the internal server

socat -d -d -d -v tcp:${REMOTE_IP}:6666,forever,intervall=1,fork,reuseaddr tcp:

On the external server

socat -d -d -d tcp-l:2222,reuseaddr,bind=,fork tcp-l:6666,bind=,reuseaddr,retry=10

File transfer with socat

Server side

socat -u open:FILENAME tcp-listen:12345

Client side

socat -u tcp:ServerIP:12345 open:LOCALFILE,create
  • -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

Split Read and Write request

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
  • reuseaddr the same as SO_REUSEADDR
  • fork fork a process to deal with the new request



  • 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 @