Raspberry Pi Zero: avoiding random network addresses in Gadget Mode

The Raspberry Pi Zero can be set up to appear as one of several USB OTG “gadgets” if you plug it into another computer. The most popular setting seems to be the virtual network gadget that turns your Zero into a computer on the end of your USB cable. Andrew Mulholland’s guide Raspberry Pi Zero – Programming over USB! (Part 2) (along with his super-short simple guide) seems to be the definitive source on how to set these modes up.

One problem, though, is that the Zero would show up on different network addresses every time it was restarted. The changing addresses made ssh access no fun at all. A suggestion on the Raspberry Pi forum helped me come up with a solution. On the Raspberry Pi Zero, run this command once:

echo 'options g_ether host_addr='$(dmesg | awk '/: HOST MAC/{print $NF}')' dev_addr='$(dmesg | awk '/: MAC/{print $NF}') | sudo tee /etc/modprobe.d/g_ether.conf

This will set the USB port’s hardware addresses to a fixed value, and you should always get a connection on the same IP address if it’s available.

How my Raspberry Pi Zero appears on my Ubuntu machine

Update: For some reason, this seemed to stop working, and I was getting the old random addresses again. I was resisting putting more stuff in /boot/cmdline.txt, but it seems to me it’s more reliable than what I proposed. So if your g_ether.conf looked like:

options g_ether host_addr=66:e0:94:40:44:74 dev_addr=de:82:66:79:e2:66

right at the end of your /boot/cmdline.txt (which is all one line, btw), add

 g_ether.host_addr=66:e0:94:40:44:74 g_ether.dev_addr=de:82:66:79:e2:66

You’ll probably also want to share the IPv4 connection so your Raspberry Pi Zero can use the network of the device it’s attached to: