Difference between revisions of "Forward (redirect/nat) traffic with iptables"
(Created page with "If you want to redirect all traffic to IP 1.1.1.1 to IP 2.2.2.2, it simply can be done with iptables.<br/> First of all enable IP forwarding in ''/etc/sysctl.conf'' on 1.1.1.1...") |
|||
Line 3: | Line 3: | ||
<pre> | <pre> | ||
net.ipv4.ip_forward=1 | net.ipv4.ip_forward=1 | ||
+ | </pre> | ||
+ | Execute following for the changes to take effect: | ||
+ | <pre> | ||
+ | sysctl -p | ||
</pre> | </pre> | ||
Now add the rules to related sections: | Now add the rules to related sections: | ||
Line 11: | Line 15: | ||
-A PREROUTING -d 1.1.1.1 -p udp -m udp --dport 23:65500 -j DNAT --to-destination 2.2.2.2 | -A PREROUTING -d 1.1.1.1 -p udp -m udp --dport 23:65500 -j DNAT --to-destination 2.2.2.2 | ||
-A POSTROUTING -o eth0 -j MASQUERADE | -A POSTROUTING -o eth0 -j MASQUERADE | ||
+ | </pre> | ||
+ | Restart iptables | ||
+ | <pre> | ||
+ | service iptables restart | ||
</pre> | </pre> | ||
Here is an example of working iptables: | Here is an example of working iptables: |
Revision as of 15:01, 11 April 2013
If you want to redirect all traffic to IP 1.1.1.1 to IP 2.2.2.2, it simply can be done with iptables.
First of all enable IP forwarding in /etc/sysctl.conf on 1.1.1.1 host:
net.ipv4.ip_forward=1
Execute following for the changes to take effect:
sysctl -p
Now add the rules to related sections:
-A FORWARD -d 2.2.2.2 -i eth0 -p tcp -m tcp --dport 23:65500 -j ACCEPT -A FORWARD -d 2.2.2.2 -i eth0 -p udp -m udp --dport 23:65500 -j ACCEPT -A PREROUTING -d 1.1.1.1 -p tcp -m tcp --dport 23:65500 -j DNAT --to-destination 2.2.2.2 -A PREROUTING -d 1.1.1.1 -p udp -m udp --dport 23:65500 -j DNAT --to-destination 2.2.2.2 -A POSTROUTING -o eth0 -j MASQUERADE
Restart iptables
service iptables restart
Here is an example of working iptables:
# Generated by iptables-save v1.4.7 on Tue Apr 9 14:27:04 2013 *filter :FORWARD ACCEPT [0:0] -A FORWARD -d 2.2.2.2 -i eth0 -p tcp -m tcp --dport 23:65500 -j ACCEPT -A FORWARD -d 2.2.2.2 -i eth0 -p udp -m udp --dport 23:65500 -j ACCEPT COMMIT # Completed on Tue Apr 9 14:27:04 2013 # Generated by iptables-save v1.4.7 on Tue Apr 9 14:27:04 2013 *nat :PREROUTING ACCEPT [0:0] :POSTROUTING ACCEPT [0:0] :OUTPUT ACCEPT [0:0] -A PREROUTING -d 1.1.1.1 -p tcp -m tcp --dport 23:65500 -j DNAT --to-destination 2.2.2.2 -A PREROUTING -d 1.1.1.1 -p udp -m udp --dport 23:65500 -j DNAT --to-destination 2.2.2.2 -A POSTROUTING -o eth0 -j MASQUERADE COMMIT # Completed on Tue Apr 9 14:27:04 2013
Make sure your ssh port is out of range 23:65500, otherwise you will lose ssh access to 1.1.1.1