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.

pc-laptop-inet

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 172.16.16.1 netmask 255.255.255.0

From the PC:

ifconfig eth0 172.16.16.2 netmask 255.255.255.0
route add default gw 172.16.16.1

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
172.16.16.0      0.0.0.0         255.255.255.0   U     0      0        0 eth0
0.0.0.0         172.16.16.1      0.0.0.0         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 8.8.8.8:

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

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!