一、前言
Linux多个网卡设置为相同网段,会发现只有其中一个网卡可以正常使用,原因是如果系统有多个独立网卡,并且这些网卡的IP属于同一个子网,那么后面的网卡的IP将自动路由到最前面的网卡上。
注意: 本文的解决方法在Ubuntu系统下测试有效,其他的Linux系统不确定是否可以按照相同的方法配置。
二、解决方法
解决方法是:策略路由设置,指定IP路由的走向。
例子:
同一设备下两个独立网卡的配置如下
eth0 192.168.2.10
eth1 192.168.2.11
1、修改/etc/iproute2/rt_tables
打开文件 vi /etc/iproute2/rt_tables
增加内容:
11 net_1
10 net_0
2、修改/etc/rc.local
打开文件 vi /etc/rc.local
增加内容:
ip route add 192.168.2.0/24 dev eth0 src 192.168.2.10 table net_0
ip route add default dev eth0 table net_0
ip rule add from 192.168.2.10 table net_0
ip route add 192.168.2.0/24 dev eth1 src 192.168.2.11 table net_1
ip route add default dev eth1 table net_1
ip rule add from 192.168.2.11 table net_1
ip route flush cache
3、自启动文件执行权限
修改/etc/rc.local文件的执行权限,保证在开机时有足够的权限执行配置
chmod u+x /etc/rc.local
4、重启设备
reboot
以上配置解释:
第1步:
把路由表序号(10、11)和路由表名字(net_0、net_1)添加到/etc/iproute2/rt_tables中
第2步:
(1)ip route add 192.168.2.0/24 dev eth0 src 192.168.2.10 table net_0
从192.168.2.10发送到192.168.2.0/24网段的数据从eth0发出,把该路由项添加到路由表net_0中
(2)ip route add default dev eth0 table net_0
在路由表中添加默认路由,默认路由从eth0进出
(3)ip rule add from 192.168.2.10 table net_0
添加路由策略,来自192.168.2.10的路由要求使用net_0
(4) ip route flush cache
把新添加的路由策略和路由表刷新到缓存中,即时生效
配置完成后测试
1、查看路由信息
route
ip route
ip route list
ip route list table net_0
2、查看路由策略
ip rule
3、ping
在同一设备下有多个同网段的网卡,ping命令需要添加部分参数进行网络测试
-I 设置输出接口,即选择ping的来源网卡IP
如:ping -I 192.168.2.10 192.168.2.1
表示使用IP为192.168.2.10的网卡ping目标IP为192.168.2.1的设备