Wednesday, November 30, 2011

How to share network connection with iptables

While working in isolated environment you might need to share your machine internet connection with other computers or virtual machines (e.g. host only network in VirtualBox). Ensure you have iptables installed.
apt-get install iptables
There are two thing we need to do: let kernel know that it is permitted to forward network traffic.
echo "sysctl net.ipv4.ip_forward=1" >> \
and apply masquerading for the interface that we what to share (eth0), add the following line to /etc/rc.local:
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
You have to restart your computer so the changes take place during the next system boot.


  1. Not sure why you'd need to restart here - just also execute :

    echo 1 > /proc/sys/net/ipv4/ip_forward

    1. This is just to ensure nothing breaks after reboot. Note, the changes in /etc/rc.local. Alternatively use the following to apply changes on fly (without restart):
      sysctl -f /etc/sysctl.d/ip_forward.conf