Skip to content

TCP/UDP port forwarding with socat

homepage-banner

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

File transfer

Server side

socat -u open:FILENAME tcp-listen:12345

Client side

socat -u tcp:ServerIP:12345 open:LOCALFILE,create
  • -u 表示数据单向传送,从第一个参数传递到第二个参数
  • -U 则表示从第二个参数传送到第一个参数
  • open 表示使用系统调用open()打开文件,不能打开unixsocket
  • tcp-listen 表示监听tcp端口
  • create 表示如果文件不存在则创建
  • 传输结束后两端均退出

Split Read/Write

  • 使用!!符号,左侧表示读,右侧表示写
socat open:hello.html\!\!open:log.txt,create,append tcp-listen:12345,reuseaddr,fork
  • open:hello.html 表示读hello.html文件
  • open:log.txt 表示收到的数据写入log.txt文件
  • reuseaddrsocketSO_REUSEADDR
  • fork 请求到达时,fork一个进程进行处理
  • bash下,需要用\!进行转义

Reference

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

Back to Table of Contents

Disclaimer
  1. License under CC BY-NC 4.0
  2. Copyright issue feedback me#imzye.com, replace # with @
  3. Not all the commands and scripts are tested in production environment, use at your own risk
  4. No personal information is collected.
Feedback