Linux – Configure multiple network with iproute2

Iprout2 can be used to access two different networks in parallel from a Linux machine.If you have a Linux machine with interfaces eth0 and eth1, and you want to access internet through eth0 and use eth1 to access restricted resources.you can configure iproute2 to achieve  this.

Consider eth0 and eth1 has below ip addresses and subnets.

eth0(internet)

ip:172.16.0.188
netmask:255.255.0.0
gateway: 172.16.0.4

eth1(private)

ip: 10.105.12.8
netmask: 255.255.255.192
gateway: 10.105.12.62

Now add the script below in your bashrc file to make it permanent after reboot.

-------------------START-------------------
#Verify if a rule is already present and create with name 100 if not present

ip rule show | grep -i 100  > /dev/null
if test "$?" -ne "0";then

ip route add 10.105.12.0/26 dev eth1 src 10.105.12.8 table 100
ip route add default via 10.105.12.62 dev eth1 table 100

ip rule add from 10.105.12.8/32 table 100
ip rule add to 10.105.12.8/32 table 100
fi

#Configure/add  individual routes if needed
route -n | grep -w "10.105.12.62" > /dev/null

if test "$?" -ne "0"; then
route add -net 10.103.20.0/24 gw 10.105.12.62
route add -net 10.103.20.0/24 gw 10.105.12.62
fi
-------------------END-------------------