How to change your Ethernet’s Mac address on boot (Linux)


USB / Ethernet adapterLet’s say you bought three cute little USB-to-Ethernet adapters for your Raspberry Pi Zeros running UBOS. Plug one in, works like a charm.

… as long as you don’t attempt to use two with two Pi Zeros at the same time, on the same Ethernet network. Or all three.

Because if you do that, as I just found out the hard way, mayhem occurs: all three of my adapters have the same Ethernet Mac address! Oh, oh.

(For the non-networking geeks among us, imagine being in a crowded room and wanting to have a conversation, but three people are talking, at the same time, on different subjects, with the exact tone of voice and volume, and not necessarily attempting to talk to you, but you can’t tell which is and which isn’t. And when you talk, all three think that you are responding just to them!)

So, Linux to the rescue. Specifically, systemd-networkd. On my first Pi Zero, I create a file called /etc/systemd/network/00-default.link with this content:

[Match]
MACAddress=00:e0:4c:53:44:58

[Link]
MACAddress=00:e0:4c:53:44:01

and on the second, the same file but instead of ending with :01 I have it end with :02.

Upon boot, systemd-networkd will look for a device with the Mac address in the “[Match]” section, and rename it, in software, to the Mac address in the “[Link]” section. Because I rename it to something else on the second RPi Zero, there are no more conflicts and we know who sent something, and to whom a response is directed.

Unfortunately this has to be done on every boot. But as a beneficial side effect, I don’t have to keep track which of my adapters is which: as they all have the same hardware Mac address, the rename will work every time, regardless which adapter is which.

Credit: the always excellent Arch Linux wiki.