Port Forwarding with Linux Tool
Last updated
Last updated
# socat Tool is not installed by default on NIX system.
# Checking for socat tool
locate socat
socat -h # If you are unable to use locate command then try this.
# Command to start port forwarding with socat
socat TCP-LISTEN:<local_port>,fork TCP:<target_IP>:<target_port>
# Example:
# socat -ddd TCP-LISTEN:2345,fork TCP:10.4.50.215:5432
# Note: Socat is one to one port forwarding method. This means if you want to access other port then you have to change port and rerun the above command.# Alternative Port Forwarding Methods
---------------------------------------------------------
# 1. rinetd: Runs as a daemon, making it suitable for long-term port forwarding, though slightly unwieldy for temporary solutions.
# install if it's not there.
sudo apt-get install rinetd
# Add below line in configuration (/etc/rinetd.conf)
<bind_address> <bind_port> <target_address> <target_port>
# Example: 0.0.0.0 8080 192.168.1.100 80
# Make sure you start the rinetd service
# Command: sudo systemctl start rinetd
-----------------------------------------------------------
# 2. Netcat + FIFO: Combine Netcat and a FIFO named pipe to create a port forward.
# Method of making.
# Create a FIFO named pipe:
mkfifo /tmp/fifo
# Set up port forwarding:
nc -l -p <local_port> < /tmp/fifo | nc <target_IP> <target_port> > /tmp/fifo
# Example of the above
# nc -l -p 8080 < /tmp/fifo | nc 192.168.1.100 80 > /tmp/fifo
-----------------------------------------------------------
# 3. iptables: With root privileges, iptables can be used for port forwarding. Ensure forwarding is enabled on the interface by writing "1" to /proc/sys/net/ipv4/conf/[interface]/forwarding.
# Method to do this
# Enable IP forwarding:
sudo sysctl -w net.ipv4.ip_forward=1
# Set up port forwarding:
sudo iptables -t nat -A PREROUTING -p tcp --dport <local_port> -j DNAT --to-destination <target_IP>:<target_port>
sudo iptables -t nat -A POSTROUTING -j MASQUERADE
# Example of above command:
# sudo iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 192.168.1.100:80
# sudo iptables -t nat -A POSTROUTING -j MASQUERADE