linux 网络接口的混杂模式

Linux 网卡的混杂模式(Promiscuous mode),简称 Promisc mode,俗称 监听模式。在非混杂模式下,网卡只会接受目的 MAC 地址是它自己的单播帧,以及多播帧;在混杂模式下,网卡会接受经过它的所有帧。

查看网卡是否处于 Promiscuous mode,可以使用 ifconfig 或者 netstat -i 命令

ifconfig ens33
ens33: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.142.10 netmask 255.255.255.0 broadcast 192.168.142.255
inet6 fe80::20c:29ff:fee7:c027 prefixlen 64 scopeid 0x20<link>
ether 00:0c:29:e7:c0:27 txqueuelen 1000 (Ethernet)
RX packets 194243 bytes 257521006 (245.5 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 92488 bytes 6051258 (5.7 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

当输出包含 PROMISC 时,表明该网络接口处于 Promiscuous mode,否则表明未处于 Promiscuous mode。要开启网卡的 Promiscuous mode ,可以使用以下命令

$ ifconfig ens33 promisc

$ ifconfig ens33
ens33: flags=4419<UP,BROADCAST,RUNNING,PROMISC,MULTICAST> mtu 1500
inet 192.168.142.10 netmask 255.255.255.0 broadcast 192.168.142.255
inet6 fe80::20c:29ff:fee7:c027 prefixlen 64 scopeid 0x20<link>
ether 00:0c:29:e7:c0:27 txqueuelen 1000 (Ethernet)
RX packets 194383 bytes 257531059 (245.6 MiB)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 92561 bytes 6058652 (5.7 MiB)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0

以下命令使网卡退出 Promiscuous mode

ifconfig ens33 -promisc

将网络设备加入 Linux bridge 后,网络设备会自动进入混杂模式,此种情况使用 ifconfig 或者 netstat -i 命令查看网卡,未显示 PROMISC,但是查看内核日志,显示网卡已进入混杂模式,并且无法退出,直到将 veth 从Linux bridge 中移除。网络设备移除网桥后,会自动退出混杂模式。

$ ip link add veth0 type veth peer name veth1

$ brctl show
bridge name bridge id STP enabled interfaces
br0 8000.000000000000 no

$ brctl addif br0 veth0

$ ifconfig veth0
veth0: flags=4099<UP,BROADCAST,MULTICAST> mtu 1500
inet 192.168.10.1 netmask 255.255.255.0 broadcast 192.168.10.255
ether b6:b3:aa:ae:61:05 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

$ netstat -i
Kernel Interface table
Iface MTU RX-OK RX-ERR RX-DRP RX-OVR TX-OK TX-ERR TX-DRP TX-OVR Flg
br0 1500 0 0 0 0 34 0 0 0 BMU
ens33 1500 195528 0 1 0 93168 0 0 0 BMPRU
veth0 1500 0 0 0 0 0 0 0 0 BMU

$ dmesg | grep promisc
[75099.376421] device veth2d80973 entered promiscuous mode
[77630.104784] device ens33 entered promiscuous mode
[77719.626596] device ens33 left promiscuous mode
[77877.905587] device ens33 entered promiscuous mode
[78153.928533] device veth0 entered promiscuous mode