How to share Internet Connection with GNU/Linux

You just need to setup some iptables rules and turn on the ip_forward feature in the Linux kernel, assign some IPs and Routes and voila, your PC will become a router.

For example, suppose you have a laptop connected to Internet through a wifi card (let’s call it eth1) and you want to connect a PC to Internet through it, using an ethernet cable.


1. First, connect your PC with your laptop.

2. Supposing that both the laptop and PC ethernet interface are named eth0, give an IP address to both. Of course you can do it graphically, but I’ll explain here the cli version (using ifconfig):

From the Laptop:

ifconfig eth0 netmask

From the PC:

ifconfig eth0 netmask
route add default gw

Try to do a ping from the PC to the Laptop and see if there’s connectivity.
You can also check that the routes are added correctly on the PC:
lipi@gall:~$ route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface   U     0      0        0 eth0         UG    0      0        0 eth0

And maybe you need name resolution. On the PC, edit your resolv.conf for example using the Google DNS’s

lipi@gall:~$ cat /etc/resolv.conf

3. Now it’s time to convert your laptop in a router. Just setup the firewall and the ip_forwarding on the Laptop:

iptables --table nat --append POSTROUTING --out-interface eth0 -j MASQUERADE
iptables --append FORWARD --in-interface eth1 -j ACCEPT
echo 1 > /proc/sys/net/ipv4/ip_forward

4. Try to navigate from the PC!