August 31, 2016

Linux route and rule

1. There are 3 default route tables: local, main, and default
2. Their priority and selector is defined by "rules".  use "ip rule list" to see the priority and selector of each table.

$ ip rule list
0:      from all lookup local
32766:  from all lookup main
32767:  from all lookup default

by default, local has highest priority (0). default has lowest priority (it's usually empty). main has next to lowest priority. You can all three tables match "from all" packets. So table local consulted first, then table main, then table default.  

$ ip route show table default
(return nothing)
$ ip route show table main
default via 192.168.140.2 dev eth0
(this is the default gateway)

Routing tables goes by number 1-255.  You can find the names at  /etc/iproute2/rt_tables

255 local
254 main
253 default
0 unspec

You can add your own table number like
100 mytable

or you can just use a number if you like.

You can add selector to specify which table should be consulted (or not). For example, you can use 
ip rule add from 10.0.0.0/24 table mytable    OR 
ip rule add to 10.0.0.0/24  OR
ip rule add iif eth0 OR
ip rule add oif eth2 OR
ip rule add fwmark MARK 

ip rule help gives you all the list

Then use "ip route add default via 10.0.0.1 dev eth1 table mytable" to add a default gateway rule to this table. "via ..." "dev ..." just tells the kernel how to route it.