News:

The Latest electronic and computer Tips that work!

Main Menu

iptables port forward to another server on the network

Started by branx86, May 04, 2025, 08:28:21 PM

Previous topic - Next topic

0 Members and 1 Guest are viewing this topic.

branx86

    Add a port forwarding rule
    # DNAT (rewrite destination IP and port) - PREROUTING chain
    sudo iptables -t nat -A PREROUTING -p tcp --dport 22 -j DNAT --to-destination <dest_server_ip>:<dest_port>
   
    #iptables -A FORWARD -s <internal ip> -p tcp --sport <internal port> -d <public_ip> --dport 8080 -j ACCEPT
   
    Allow forwarded packets to be sent out
    # SNAT (rewrite source IP) - POSTROUTING chain
    sudo iptables -t nat -A POSTROUTING -d <dest_server_ip> -p tcp --dport <dest_port> -j MASQUERADE

<dest_server_ip> = The server you want to get too.
<dest_port> = The server port you want to get too.

***You need both DNAT and SNAT for the port forwarding to work and make sure First, verify that IP forwarding is enabled. You can check this by running the command sysctl net.ipv4.ip_forward.
nano /etc/sysctl.conf  to change
If it's not set to 1, enable it temporarily by running sysctl -w net.ipv4.ip_forward=1.
Use cmd -  sysctl -p    to check if port forwarding is on

iptables-save > /etc/sysconfig/iptables  = Once you have everything the way you want it.



                   Examples
The following example redirects TCP port 25 to port 2525:
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 25 -j REDIRECT --to-port 2525

In this example all incoming traffic on port 80 redirect to port 8123:
iptables -t nat -I PREROUTING --src 0/0 --dst 192.168.1.5 -p tcp --dport 80 -j REDIRECT --to-ports 8123