Configuring Multi-NIC Routing in Windows VMs

This guide covers setting up multi-network interface card (NIC) routing for Windows virtual machines, including viewing, adding, and deleting routes to ensure proper internet and local network access.

1. 背景

Windows 创建的虚拟机只能通过 NAT 上网(桥接需要过认证),但需要桥接到内网供外部访问。

此场景使用的两张网卡会同时被设置为默认网关,出口流量有概率从桥接网卡出口导致无法访问。

2. 路由表基础操作

2.1 查看路由策略

1
2
3
4
5
[root@localhost ~]# ip rule

0:      from all lookup local
32766:  from all lookup main
32767:  from all lookup default

2.2 查看路由表

1
2
3
4
5
[root@localhost ~]# ip route list

default via 172.21.208.1 dev eth0 proto dhcp metric 101
10.60.20.0/24 dev eth1 proto kernel scope link src 10.60.20.12 metric 100
172.21.208.0/20 dev eth0 proto kernel scope link src 172.21.219.71 metric 101

2.3 新增默认路由

1
[root@localhost ~]# ip route add default via 10.60.20.254 dev eth1

2.4 删除默认路由

1
[root@localhost ~]# ip route del default via 10.60.20.254 dev eth1

3. 多网口出口配置

一般配置多网卡时,两张网卡都会被配置为默认路由,使用 ip route list 查看能看到类似如下配置

1
2
3
4
5
6
[root@localhost ~]# ip route list

default via 10.60.20.254 dev eth1 proto dhcp metric 100
default via 172.21.208.1 dev eth0 proto dhcp metric 101
10.60.20.0/24 dev eth1 proto kernel scope link src 10.60.20.12 metric 100
172.21.208.0/20 dev eth0 proto kernel scope link src 172.21.219.71 metric 101

对于 default via 10.60.20.254 dev eth1 proto dhcp metric 100

  • default 表示默认路由
  • via 10.60.20.254 表示数据包将发往 10.60.20.254 这个目标 IP 地址
  • dev eth1 指定数据包将从 eth1 接口发送
  • proto dhcp 表示该路由规则是通过 DHCP 协议动态分配的
  • metric 100 表示优先级度量值(越小优先级越高)

对于 10.60.20.0/24 dev eth1 proto kernel scope link src 10.60.20.12 metric 100

  • 这是一个具体的子网路由规则,用于指定数据包如何到达 10.60.20.0/24 子网。
  • 10.60.20.0/24 表示目标子网地址范围
  • dev eth1 指定数据包将从 eth1 接口发送
  • proto kernel 表示该路由规则由内核自动生成
  • scope link 表示这是一个本地链接,即目标 IP 地址与本机直接相连
  • src 10.60.20.12 表示源 IP 地址,即从 10.60.20.12 发送到目标子网
  • metric 100 表示优先级度量值(越小优先级越高)

如果不希望访问外网时通过 10.60.20.254 网关,只需将第一条路由删除即可,执行

1
[root@localhost ~]# ip route del default via 10.60.20.254 dev eth1

验证除了 10.60.20.0/24 的地址,都会走 eth0 网卡

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
[root@localhost ~]# ip route get 10.60.20.10
10.60.20.10 dev eth1 src 10.60.20.12
    cache

[root@localhost ~]# ip route get 1.1.1.1
1.1.1.1 via 172.21.208.1 dev eth0 src 172.21.219.71
    cache

[root@localhost ~]# ip route get 8.8.8.8
8.8.8.8 via 172.21.208.1 dev eth0 src 172.21.219.71
    cache

4. 保存设置

以上路由会在重启后被清理,应使用 ip route save 保存信息

1
sudo ip route save table main > /var/opt/route-main.rules

使用 ip route restore 恢复

1
2
sudo ip route flush table main
sudo ip route restore table main < /var/opt/route-main.rules

也可以将其写为 systemd 脚本,当网卡准备完成后执行

使用 Hugo 构建
主题 StackJimmy 设计