Setup NAT with iptables

TheĀ  Setup

Having this setup where Machine A like to connect the Internet via Machine B.

+-------------------+          +-----------------+
|                   |          |  Machine B      |
|      Machine A    |          |  (the gateway)  |
|      (the client) |          |                 |
|                   |          |                 |
|              eth0 +----------+  eth0     eth1  |
+-------------------+          +-------------+---+
                                             |
                                             |
                     .-~~~-.                 |
             .- ~ ~-(       )_ _             |
            /                     ~ -.       |
           |        internet           \<----+
            \                         .'
              ~- . _____________ . -~

Add the following lines to the iptables

iptables -I FORWARD     -o eth0 -m comment --comment "NAT" -j ACCEPT
iptables -I FORWARD     -i eth0 -m comment --comment "NAT" -j ACCEPT
iptables -I POSTROUTING -o eth1 -m comment --comment "NAT" -j MASQUERADE -t nat

and make sure to enable forwarding on Machine B

sysctl -w net.ipv4.ip_forward=1

 

Leave a Reply

Your email address will not be published. Required fields are marked *