TCP/UDP port forwarding with socat
Introduction
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: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 argumentopen
call system open()tcp-listen
listen tcp portcreate
if file not exists, create a new onereuseaddr
reuse addressfork
fork a new process for each connectionforever
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 WHSopen:hello.html
read hello.html fileopen: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
Leave a message
Disclaimer
- 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 me#imzye.com, replace # with @