A router is a device that directs network traffic destined for an entirely different network in the right direction. For example, suppose your network is having the IP address range of 192.168.1.0/16 and you also have a different network which has a network addresses in range 192.168.2.0/16 . Note that these are ‘Class C’ network addresses which are subnetted. So for your computer ( on the network 192.168.1.0/16 ) to directly communicate between a computer in the network 192.168.2.0/16, you need a intermediary to direct the traffic to the destination network. This is achieved by a router.
Configuring Linux as a router
Linux can be effectively configured to act as a router between two networks. To activate routing functionality , you enable IP forwarding in Linux. This is how you do this:
# echo "1" > /proc/sys/net/ipv4/ip_forward
Now you have enabled IP forwarding in Linux. Now make this change persistent across reboots by editing the file /etc/sysctl.conf and entering the following line:
#FILE : /etc/sysctl.conf
net.ipv4.ip_forward = 1
Optionally, after editing the above file, you may execute the command :
# sysctl -p
Note: For your linux machine to act as a router, you need two ethernet cards in your machine or you can also configure a single ethernet card to have multiple IP addresses.
What is a gateway?
Any device which acts as the path to or from your network to another network or the internet is considered to be a gateway. Let me explain this with an example: Suppose your computer, machine_B has an address 192.168.0.5 with default netmask. And another computer (machine_A) with an IP address 192.168.0.1 in your network is connected to the internet using a USB cable modem. Now if you want machine_B to send or recieve data destined for an outside network a.k.a internet, it has to direct it to machine_A first which forwards it to the internet. So machine_A acts as the gateway to the internet. Each machine needs a default gateway to reach machines outside the local network. You can set the gateway in machine_B to point to machine_A as follows:
# route add default gw machine_A
Or if DNS is not configured…
# route add default gw 192.168.0.1
Now you can check if the default gateway is set on machine_B as follows:
# route -n
What is NAT ?
Network Address Translation (NAT) is a capability of linux kernel where the source or destination address / port of the packet is altered while in transit.
This is used in situations where multiple machines need to access the internet with only one official IP address available. A common name for this is IP masquerading. With masquerading, your router acts as a OSI layer 3 or layer 4 proxy. In this case, Linux keeps track of the packet(s) journey so that during transmission and recipt of data, the content of the session remains intact. You can easily implement NAT on your gateway machine or router by using Iptables, which I will explain in another post.