Friday, April 2, 2010

How to enable routing on a linux machine

Ever wondered how to make your linux machine a router? Of course not as powerful as a cisco router ;)

The only requirement is that you have at least two networking interfaces in the machine and one of them is connected to the external network or the Internet

Let us suppose 'eth0' is the interface connected to the external world and 'eth1', 'eth2' etc ., are connected to other machines/switches which would connect to the Internet/external network via this machine

The following script would enable routing on the machine and lets other machines connected to it access machines in the external network

# Delete and flush. Default table is "filter". Others like "nat" must be explicitly stated.
iptables --flush # - Flush all the rules in filter and nat tables
iptables --table nat --flush
iptables --delete-chain # - Delete all chains that are not in default filter and nat table
iptables --table nat --delete-chain

# Set up IP FORWARDing and Masquerading
iptables --table nat --append POSTROUTING --out-interface eth0 -j MASQUERADE
iptables --append FORWARD --in-interface eth1 -j ACCEPT
#Add a similar line as above for each other interfaces which accepts connections

echo 1 > /proc/sys/net/ipv4/ip_forward # - Enables packet forwarding by kernel

No comments:

Post a Comment