路由策略

顺序

ip rule,ip tables,ip route 的顺序 如下:

  • 当内核收到一个数据包时,它会先查看 ip rule 中的路由策略,根据数据包的特征(如源地址、目标地址、标记等)选择一个路由表。

    ip rule add fwmark 1 table table1   #查看到标记为1 的选择table1
    ip rule add fwmark 2 table table2	#查看到标记为2 的选择table2
    
  • 内核会在选定的路由表中查找匹配的路由条目,根据数据包的目标地址选择一个出口网卡或网关。

    ip route list table  [num/name]  查看指定[num/name]的路由表的 路由条目
    
  • 接着,内核会将数据包发送到 iptables 的 mangle 表和 nat 表的 prerouting 链,根据用户定义的规则对数据包进行修改或转换(如更改 IP 头、执行 DNAT 等)。

    sysctl -w net.ipv4.conf.eth2.rp_filter=0
    # ip route flush cache
    
    
  • 然后,内核会根据修改后的数据包重新查看 ip rule 和 ip route,选择一个新的出口网卡或网关。

  • 接着,内核会将数据包发送到 iptables 的 filter 表的 forward 链,根据用户定义的规则对数据包进行过滤或转发(如接受、丢弃、拒绝等)。

  • 然后,内核会将数据包发送到 iptables 的 mangle 表和 nat 表的 postrouting 链,根据用户定义的规则对数据包进行修改或转换(如更改源地址、执行 SNAT 等)。

  • 最后,内核会将数据包发送出去。

ip route add default dev eth0 table table1
#将所有不匹配任何其他路由的数据包,通过eth0发出去 并使用路由表table1
root@wim:/# ip route show table tuntable
default dev eth1  scope link

root@wim:/# ip rule list
0:      from all lookup 128
0:      from all fwmark 0x2 lookup tuntable
0:      from all fwmark 0x2 lookup tuntable
1:      from all lookup local
32766:  from all lookup main
32767:  from all lookup default



root@wim:/# route
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
192.168.40.0    *               255.255.255.0   U     0      0        0 eth0
192.168.50.0    *               255.255.255.0   U     0      0        0 br-lan

root@wim:/# ip route
192.168.40.0/24 dev eth0  proto kernel  scope link  src 192.168.40.3
192.168.50.0/24 dev br-lan  proto kernel  scope link  src 192.168.50.3