Skip to content

TCP/UDP port forward with socat

homepage-banner

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: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

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

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:127.0.0.1:22

On the external server

socat -d -d -d tcp-l:2222,reuseaddr,bind=0.0.0.0,fork tcp-l:6666,bind=0.0.0.0,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

Reference

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