root@ubt1:~# ip a 1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000 link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00 inet 127.0.0.1/8 scope host lo valid_lft forever preferred_lft forever inet6 ::1/128 scope host noprefixroute valid_lft forever preferred_lft forever 2: enp0s3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000 link/ether 08:00:27:be:32:7c brd ff:ff:ff:ff:ff:ff inet 10.0.2.5/24 brd 10.0.2.255 scope global enp0s3 valid_lft forever preferred_lft forever inet6 fe80::a00:27ff:febe:327c/64 scope link valid_lft forever preferred_lft forever 3: enp0s8: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000 link/ether 08:00:27:5b:86:46 brd ff:ff:ff:ff:ff:ff inet 192.168.56.150/24 brd 192.168.56.255 scope global enp0s8 valid_lft forever preferred_lft forever inet6 fe80::a00:27ff:fe5b:8646/64 scope link valid_lft forever preferred_lft forever 4: docker0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default link/ether 02:42:67:23:ff:9e brd ff:ff:ff:ff:ff:ff inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0 valid_lft forever preferred_lft forever root@ubt1:~#
network: version: 2 ethernets: # 第一块网卡的名称,配置nat网络 enp0s3: dhcp4: false optional: true # 静态ip ip要在nat网卡所在网段 addresses: - 10.0.2.5/24 routes: - to: default via: 10.0.2.1 nameservers: addresses: - 8.8.8.8 # 第二块网卡的名称,配置host-only网络 enp0s8: dhcp4: false optional: true # 静态ip ip要在host-only网卡所在网段 addresses: - 192.168.56.150/24
root@ubt1:~# netplan apply root@ubt1:~# hostname -I 10.0.2.5 192.168.56.150 172.17.0.1
没有报错就可以
虚拟机访问外网会通过10.0.2.5
宿主机访问虚拟机通过192.168.56.150
4.测试
root@ubt1:~# ping -c3 172.16.20.1 PING 172.16.20.1 (172.16.20.1) 56(84) bytes of data. 64 bytes from 172.16.20.1: icmp_seq=1 ttl=127 time=0.511 ms 64 bytes from 172.16.20.1: icmp_seq=2 ttl=127 time=0.720 ms 64 bytes from 172.16.20.1: icmp_seq=3 ttl=127 time=1.02 ms --- 172.16.20.1 ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 2002ms rtt min/avg/max/mdev = 0.511/0.749/1.018/0.208 ms
root@ubt1:~# ping -c3 baidu.com PING baidu.com (28.0.0.112) 56(84) bytes of data. 64 bytes from 28.0.0.112: icmp_seq=1 ttl=63 time=0.864 ms 64 bytes from 28.0.0.112: icmp_seq=2 ttl=63 time=0.795 ms 64 bytes from 28.0.0.112: icmp_seq=3 ttl=63 time=1.27 ms --- baidu.com ping statistics --- 3 packets transmitted, 3 received, 0% packet loss, time 2028ms rtt min/avg/max/mdev = 0.795/0.976/1.271/0.210 ms
C:\Users\***>ping 192.168.56.150 正在 Ping 192.168.56.150 具有 32 字节的数据: 来自 192.168.56.150 的回复: 字节=32 时间<1ms TTL=64 来自 192.168.56.150 的回复: 字节=32 时间<1ms TTL=64 来自 192.168.56.150 的回复: 字节=32 时间<1ms TTL=64 来自 192.168.56.150 的回复: 字节=32 时间<1ms TTL=64 192.168.56.150 的 Ping 统计信息: 数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失), 往返行程的估计时间(以毫秒为单位): 最短 = 0ms,最长 = 0ms,平均 = 0ms