
开启路由功能
$ cat/proc/sys/net/ipv4/ip_forward
如果值为 1,表示开启了路由功能,如未开启,需要在 /etc/sysctl.conf 中设置:
net.ipv4.ip_forward=1
然后执行 sysctl -p 使之生效。
实践
创建两个网络 namespace:
$ ip netns add ns1
$ ip netns add ns2
创建两对 veth-pair,一端分别挂在两个 namespace 中:
$iplinkadd v1type veth peer name v1_r$iplinkadd v2type veth peer name v2_r$iplink setv1netns ns1$iplink setv2netns ns2
分别给两对 veth-pair 端点配上 IP 并启用:
$ ip a a 10.10.10.1/24 dev v1_r$ ip l s v1_r up$ ip a a 10.10.20.1/24 dev v2_r$ ip l s v2_r up$ ip netnsexecns1 ip a a 10.10.10.2/24 dev v1$ ip netnsexecns1 ip l s v1 up$ ip netnsexecns2 ip a a 10.10.20.2/24 dev v2$ ip netnsexecns2 ip l s v2 up
测试:
$ ip netnsexecns1 ping 10.10.20.2
发现不通。
添加路由
查看路由:
$ ip netnsexecns1 route -nKernel IP routing tableDestination Gateway Genmask Flags Metric Ref Use Iface10.10.10.0 0.0.0.0 255.255.255.0 U 0 0 0 v1
只有一条直连路由,没有去往 10.10.20.0/24 网段的路由,怎么通?那就给它配一条:
$ ip netnsexecns1 route add -net 10.10.20.0 netmask 255.255.255.0 gw 10.10.10.1$ ip netnsexecns1 route -n
同理也给 ns2 配上去往 10.10.10.0/24 网段的路由:
$ ip netnsexecns2 route add -net 10.10.10.0 netmask 255.255.255.0 gw 10.10.20.1$ ip netnsexecns2 route -n
再次测试,发现可以 ping 通了:
$ ip netnsexecns1 ping 10.10.20.2
总结
Linux 本身是一台路由器。
上面的实验使用 namespace 效果和使用虚拟机是一样的,关键是知道有这个功能,知道怎么用就差不多了。
1、查看本机路由信息[root@Router ~]# ip route ls
192.168.70.0/24 dev eth0 proto kernel scope link src 192.168.70.70
192.168.1.0/24 dev eth1 proto kernel scope link src 192.168.1.70
169.254.0.0/16 dev eth1 scope link
default via 192.168.1.1 dev eth0
2、确认是否需要改变默认路由
[root@Router ~]# ip route replace default via 192.168.70.254 dev eth0 table main
[root@Router ~]# ip route ls
192.168.70.0/24 dev eth0 proto kernel scope link src 192.168.70.70
192.168.1.0/24 dev eth1 proto kernel scope link src 192.168.1.70
169.254.0.0/16 dev eth1 scope link
default via 192.168.1.1 dev eth0
3、建立特殊路由表
[root@Router ~]# vi /etc/iproute2/rt_tables
255 local
254 main
253 default
200 test
4、向test路由表中添加它自己的默认路由
[root@Router ~]# ip route add default via 192.168.1.1 table test
注意:这个table test一定不要忘了写,否则写到了主路由表中
5、先看看机器当前的ip rule
[root@Router ~]# ip rule ls
0: from all lookup local
32766: from all lookup main
32767: from all lookup default
可以看到,规则中走了3个路由表,local、main、default
我们平常用route看到的,实际是路由表main
这些规则是按序号大小顺序走的,一个不同,则走下一个,知道通路或走完为止
6、添加路由到路由表test中
[root@Router ~]# ip rule add to 59.76.0.0/16 pref 10000 table test
这个意思是说,去向IP地址范围为59.76.0.0/16的访问,则启用test的路由表中的路由规则
而test的路由规则是什么呢?上面已经设置了,走的是202.196.x.1的路由.
现在再来看一下当前的ip rule
[root@Router ~]# ip rule ls
0: from all lookup local
10000: from all to 59.76.0.0/16 lookup test
32766: from all lookup main
32767: from all lookup default
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)