前言
近期需要搭建一个开发板上网的测试环境,于是顺便学习一下Linux的网桥配置。 实验环境为Virtualbox 6.1 + Ubuntu-20.04,虚拟机共享主机网络上网,通过usb以太网卡连接开发板,本文主要就是配置网桥连接usb以太网卡与虚拟机的主网卡,使开发板能通过网桥上网。
前置准备
虚拟机的配置不在本文描述,默认虚拟机可正常上网,并正常识别usb以太网卡,如下:
root@ubuntu01:~
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::a1cb:f3aa:e2c8:b366 prefixlen 64 scopeid 0x20<link>
ether 08:00:27:2d:c9:da txqueuelen 1000 (Ethernet)
RX packets 403 bytes 393792 (393.7 KB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 382 bytes 51960 (51.9 KB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
enx34298f742220: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
ether 34:29:8f:74:22:20 txqueuelen 1000 (Ethernet)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 0 bytes 0 (0.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
如上enp0s3为虚拟机共享主机上网的网卡,enx34298f742220为usb以太网卡。 虚拟机的默认IP配置和路由配置也先记录一下,后续进行路由配置的时候直接复用即可:
root@ubuntu01:~$ route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 10.0.2.2 0.0.0.0 UG 101 0 0 enp0s3
10.0.2.0 0.0.0.0 255.255.255.0 U 101 0 0 enp0s3
169.254.0.0 0.0.0.0 255.255.0.0 U 1000 0 0 enp0s3
192.168.56.0 0.0.0.0 255.255.255.0 U 100 0 0 enp0s8
关闭图形界面的网络配置,否则可能会干预我们后续在命令行进行的配置,如下:
网桥配置
使能IP转发,如下:
echo 1 > /proc/sys/net/ipv4/ip_forward
清除目标网卡的IP地址及路由:
ifconfig enp0s3 0.0.0.0
ifconfig enx34298f742220 0.0.0.0
添加网桥并绑定网卡:
brctl addbr br0
brctl addif br0 enp0s3
brctl addif br0 enx34298f742220
配置网桥IP,直接复用之前enp0s3的配置并使能:
ifconfig br0 10.0.2.15 netmask 255.255.255.0 broadcast 10.0.2.255 up
确认配置是否正确:
root@ubuntu01:~
br0: 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:fe2d:c9da prefixlen 64 scopeid 0x20<link>
ether 08:00:27:2d:c9:da txqueuelen 1000 (Ethernet)
RX packets 0 bytes 0 (0.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 46 bytes 7881 (7.8 KB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
root@ubuntu01:~
bridge name bridge id STP enabled interfaces
br0 8000.0800272dc9da no enp0s3
enx34298f742220
路由配置
在前置准备时我们保存了默认的虚拟机路由配置,现在直接还原即可,不过要把接口从enp0s3换成br0,如下:
route add default gw 10.0.2.2 dev br0
确认配置是否正确:
root@ubuntu01:~
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 10.0.2.2 0.0.0.0 UG 0 0 0 br0
10.0.2.0 0.0.0.0 255.255.255.0 U 0 0 0 br0
169.254.0.0 0.0.0.0 255.255.0.0 U 1000 0 0 br0
192.168.56.0 0.0.0.0 255.255.255.0 U 100 0 0 enp0s8
在虚拟机中ping一下外网,能ping通,即配置正确。 完成PC端配置后,再进行开发板的路由配置,首先配置开发板的IP地址(与网桥IP同一网段即可):
ifconfig eth0 10.0.2.200 netmask 255.255.255.0 broadcast 10.0.2.255 up
然后配置开发板的网关,同样参考虚拟机的默认路由配置:
route add default gw 10.0.2.2 dev eth0
在开发板上ping一下8.8.8.8,能ping通,即配置正确。
DNS配置
最后就是开发板上常规的DNS配置,如下:
vi /etc/resolv.conf:
nameserver 114.114.114.114
nameserver 8.8.8.8
在开发板上ping一下www.baidu.com,能ping通,即配置正确。
|