linux双网卡怎么指定网卡
linux双网卡怎么指定网卡详细介绍
在 Linux 中指定双网卡的使用场景通常包括设置默认路由通过特定网卡,或为特定网络 / IP 地址指定出口网卡。以下是具体操作步骤,适用于常见的 Debian/Ubuntu 和 CentOS/RHEL 系系统:
一、基础准备:确认网卡名称
通过以下命令查看网卡名称(如 ens33、enp0s3、eth0 等):
bash
show
二、静态配置网卡 IP(以 Debian/Ubuntu 为例)
编辑网卡配置文件(如 eth0 和 eth1):
bash
/etc/network/interfaces
添加以下内容(根据实际网卡名和 IP 修改):
ini
auto eth0
iface eth0 inet static
address 192.168.1.100
netmask 255.255.255.0
gateway 192.168.1.1
dns-nameservers 8.8.8.8 8.8.4.4
auto eth1
iface eth1 inet static
address 10.0.0.100
netmask 255.255.255.0
保存后重启网络服务:
bash
systemctl restart networking.service
三、指定默认路由通过特定网卡
如果需要让某一网卡作为默认出口(如 eth0),确保仅该网卡配置 gateway,另一网卡不配置。
若已存在双默认路由(冲突),可通过以下命令删除并重新添加:
bash
route del default
route default via .1.1 dev eth0
四、为特定网络 / IP 指定出口网卡
通过添加静态路由,使特定流量从指定网卡流出。例如:
场景 1:访问 192.168.2.0/24 网络时通过 eth1
bash
route .2.0/24 dev eth1
场景 2:访问 8.8.8.8 时强制通过 eth1
bash
route .8.8/32 dev eth1
场景 3:基于源 IP 的策略路由(更灵活)
假设 eth0 的 IP 为 192.168.1.100,eth1 为 10.0.0.100,希望源 IP 为 10.0.0.100 的流量走 eth1:
- 添加路由表(如
table 100):bash/etc/iproute2/rt_tablesmyroute
- 添加策略路由规则:bash
rule from .0.100 table myrouteroute default via .0.1 dev eth1 table myroute
五、CentOS/RHEL 系配置(以ifcfg-ethX为例)
编辑网卡配置文件:
bash
/etc/sysconfig/network-scripts/ifcfg-eth0
ini
sudo nano /etc/sysconfig/network-scripts/ifcfg-eth1
重启网络服务:
bash
systemctl restart network
六、验证配置
- 查看路由表:bash
route showroute show table all
- 测试指定网卡访问(例如从
eth1发送 ping):basheth1 目标IP - 查看流量是否通过指定网卡:bash
tcpdump eth1
注意事项
- 避免双默认路由:仅一个网卡配置
gateway,或通过策略路由区分流量。 - DNS 配置:确保
resolv.conf或网卡配置中指定正确的 DNS 服务器(通常随网关自动获取)。 - 持久化配置:上述
ip route命令仅临时生效,如需永久生效,需写入网卡配置文件或通过rc.local脚本加载。
通过以上方法,可灵活指定 Linux 双网卡的使用场景,实现默认路由或特定流量的网卡绑定。