Share your Internet connection with GNU/Linux

Introduction

In this article I want to show how easy it is to set up our GNU/Linux to share our Internet connection with other computers. For instance, when we are connected via USB modem at home and a friend comes with his/her laptop, we can connect both computers via cable or Wireless and share our Internet connection with our friend in an easy way.

Configuring the Kernel

As usual, you have to configure the kernel in order to add support to the system. Go into the kernel configuration menu and add the following options:

  • Networking --->
    • Networking options --->
      • [*] IP: advanced router
      • [*] Network packet filtering framework (Netfilter) --->
        • Core Netfilter Configuration --->
          • <*> Netfilter connection tracking support
        • IP: Netfilter Configuration --->
          • <*> IPv4 connection tracking support (required for NAT)
          • <*> IP tables support (required for filtering/masq/NAT)
          • <*> Full NAT
          • <*> MASQUERADE target support

In new kernel versions we can activate the filtering support via Netfilter and also the netlink support, which speed ups the communication between userland and kernel. These options are inside the Core Netfilter Configuration menu. Although well, with that above was already enough, now we need to compile and reboot the system.

Share your Connection

Next step is to install the iptables software. To do that, in Debian:

~$ apt-get install iptables

After that, the only thing left to do will be to execute a simple command and our Internet connection will be shared The command is the following:

~$ iptables -t NAT -A POSTROUTING -s IP/mask -o IFACE -j MASQUERADE
~$ sysctl -w net.ipv4.ip_forward=1

In the first command, IP must be replaced by your IP address in the subnet were we are, but ending with 0. I mean, if you have the IP 192.168.0.4, then you must type 192.168.0.0; or if you are in the subnet 1, then you need to type 192.168.1.0. In the mask, you will set the subnet mask in decimal notation, for example, 255.255.255.0 is 24. In the IFACE type the interface name which give us the outway to Internet. For instance, when you use a modem, it will be ppp0, or eth0 when using an Ethernet connection. You can see that by doing /sbin/ifconfig.

As a note, I have a pair of rules to route from 1 and 2 subnetworks, this is my script which I load at boot time to share my connection:

#!/bin/sh
IFACE="eth0"

# Main program
echo -n "Configuring NAT: "
iptables -t nat -A POSTROUTING -s 192.168.0.0/24 -o $IFACE -j MASQUERADE
iptables -t nat -A POSTROUTING -s 192.168.1.0/24 -o $IFACE -j MASQUERADE
sysctl -w net.ipv4.ip_forward=1 >/dev/null 2>/dev/null
echo "done."

I hope you have no problem, at least I didn't have any and it was so easy. If you have any doubt, please contact me.

www.claudiocamacho.org
Updated on Tuesday, 19 August 2008 16:59