背景
給VirtualBox虛擬機(裝載了Ubuntu16.04系統(tǒng))配置了兩張網(wǎng)卡,網(wǎng)絡(luò)模式分別為“網(wǎng)絡(luò)地址轉(zhuǎn)換(NAT)”和“僅主機(Host-Only)適配器”,其中,enp0s3網(wǎng)卡(NAT)用于外網(wǎng)訪問,而enp0s8網(wǎng)卡(Host-Only)用于主機訪問虛擬機。然而,虛擬機啟動后,卻不能訪問外網(wǎng)。
定位
網(wǎng)絡(luò)配置文件如下:
# vi /etc/network/interface
...
# The primary network interface
auto enp0s3
iface enp0s3 inet dhcp
auto enp0s8
iface enp0s8 inet static
address 192.168.137.16
netmask 255.255.255.0
gateway 192.168.137.1
eth0使用dhcp,eth1使用static。eth0的實際網(wǎng)絡(luò)如下:
# ifconfig
enp0s3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 10.0.2.15 netmask 255.255.255.0 broadcast 10.0.2.255
inet6 fe80::a00:27ff:fe55:2858 prefixlen 64 scopeid 0x20<link>
ether 08:00:27:55:28:58 txqueuelen 1000 (Ethernet)
RX packets 6 bytes 1476 (1.4 KB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 33 bytes 3108 (3.1 KB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
打開其路由,才發(fā)現(xiàn)了問題。
# route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 192.168.137.1 0.0.0.0 UG 0 0 0 enp0s8
10.0.2.0 0.0.0.0 255.255.255.0 U 0 0 0 enp0s3
192.168.137.0 0.0.0.0 255.255.255.0 U 0 0 0 enp0s8
enp0s8網(wǎng)卡成為了默認路由,這就導致其他路由不能匹配到的網(wǎng)段都會走enp0s8這個網(wǎng)卡,而我們實際上配置與外網(wǎng)連接的虛擬網(wǎng)卡是enp0s3,環(huán)境自然就連接不了外網(wǎng)了。我們可以嘗試手動來刪除現(xiàn)在的默認路由。
# route del default
# route add default gw 10.0.2.2 dev enp0s3
# route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
default gateway 0.0.0.0 UG 0 0 0 enp0s3
10.0.2.0 0.0.0.0 255.255.255.0 U 0 0 0 enp0s3
192.168.137.0 0.0.0.0 255.255.255.0 U 0 0 0 enp0s8
路由設(shè)置成功,OS也可以訪問外網(wǎng)了。但這只是修改了本次的路由設(shè)置,OS重啟后就失效了,因此我們需要將配置持久化。
持久化路由配置
我們將路由持久化設(shè)置在網(wǎng)絡(luò)配置文件/etc/network/interfaces中。在網(wǎng)卡啟動后添加對應(yīng)的路由增刪的代碼,與route命令類似,只是在句首加上up即可。
# vi /etc/network/interfaces
...
auto enp0s3
iface enp0s3 inet dhcp
up route add default gw 10.0.2.2 dev enp0s3
auto enp0s8
iface enp0s8 inet static
address 192.168.137.16
netmask 255.255.255.0
gateway 192.168.137.1
up route del default dev enp0s8
注意:up route add default gw [gateway-addr] dev [dev-name],該語句中,[dev-name]表示外網(wǎng)網(wǎng)卡的名稱,即上面的enp0s3,而[gateway-addr]表示外網(wǎng)網(wǎng)卡使用的網(wǎng)關(guān)ip地址。
那么,如何獲取這個外網(wǎng)網(wǎng)卡的網(wǎng)關(guān)地址呢?virtualbox如下規(guī)定:
In NAT mode, the guest network interface is assigned to the IPv4 range 10.0.x.0/24 by default where x corresponds to the instance of the NAT interface +2. So x is 2 when there is only one NAT instance active. In that case the guest is assigned to the address 10.0.2.15, the gateway is set to 10.0.2.2 and the name server can be found at 10.0.2.3.
簡單的說,就是如果第0個網(wǎng)卡是NAT網(wǎng)卡,那么其網(wǎng)段的第三個數(shù)字就0+2=2就是10.0.2.0,網(wǎng)關(guān)為10.0.2.2,name server則是10.0.2.3.以此類推。
參考:鏈接地址
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。