2011年8月25日 星期四

[Network] Configuring multiple default routes and name resolving in Linux

problem description:
There are 2 NICs on my Ubuntu 10.10, I need to configure multiple default route and multiple name resolve with my host.

assume that my nic setting
$ ifconfig
wlan0: 192.168.2.115  netmask 255.255.255.0
       default gw 192.168.2.1
eth0:  10.157.132.104 netmask 255.255.240.0
       default gw 10.157.143.254

first you have to make sure your Linux kernel has support "policy routing"
$ cd /usr/src/linux
$ sudo make menuconfig
[*] Networking support  --->
      Networking options  --->    
        [*] IP: advanced router
        [*] IP: policy routing 
        [*] IP: use netfilter MARK value as routing key

create a new policy routing table entry(T2)
$ sudo echo "1 T2" >> /etc/iproute2/rt_tables

add new entry within this policy table
$ sudo ip route add 10.157.128.0/20 dev eth0 src 10.157.132.104 table T2
$ sudo ip route add default via 10.157.143.254 dev eth0 table T2
$ sudo ip rule add from 10.157.128.0/20 table T2
$ sudo ip rule add to 10.157.128.0/20 table T2

add nameserver
$ sudo echo "options rotate" > /etc/resolv.conf
$ sudo echo "nameserver 192.168.2.1" >> /etc/resolv.conf
$ sudo echo "nameserver 172.17.125.5" >> /etc/resolv.conf

I write a shell script for quickly configuring multiple default routes as below
#!/bin/bash

# first nic setting
IF1=wlan0
IP1=192.168.2.115
NM1=255.255.255.0
NT1=192.168.2.0/24
GW1=192.168.2.1

# second nic setting
IF2=eth0
IP2=10.157.132.104
NM2=255.255.240.0
NT2=10.157.128.0/20
GW2=10.157.143.254

# additional setting for second nic
IP3=172.17.125.5
NM3=255.255.255.0
NT3=172.17.125.0/24

# default gateway
DGW=${GW2}

# set ip/netmask
ifconfig ${IF2} ${IP2} netmask ${NM2}
ifconfig ${IF1} ${IP1} netmask ${NM1}

# create a new policy routing table entry
T2=`cat /etc/iproute2/rt_tables|awk '{print $2}'|grep -in T2|cut -d : -f 2`
if [ -z "$T2" ]; then
  echo "1 T2" >> /etc/iproute2/rt_tables
fi

# add new entry within this policy table
ip route add ${NT2} dev ${IF2} src ${IP2} table T2
ip route add default via ${GW2} dev ${IF2} table T2
ip rule add from ${NT2} table T2
ip rule add to ${NT2} table T2
ip rule add from ${NT3} table T2
ip rule add to ${NT3} table T2

# options timeout:1 rotate attempts:1
echo "options rotate"          >  /etc/resolv.conf
echo "nameserver 192.168.2.1"  >> /etc/resolv.conf
echo "nameserver 172.17.125.5" >> /etc/resolv.conf

reference:
* Configuring Multiple Default Routes in Linux --> works for me
* 雙網卡、兩個對外ip、共同存在並能上網
* Linux 用兩張網卡作不同子網路設定

沒有留言: