Some GNU/Linux distributions derived from Debian relies on dhcpcd to configure networking. Notably the Raspberry Pi offical operating system RaspiOS uses dhcpcd to configure both the Ethernet eth0 and WiFi wlan0 interfaces.
There are many HOWTOs describing how to configure a static IP address for the eth0, or even a fallback address to be used if the DHCP method fails, but you can hardly find a method to assign a static IP alias that should be up in any case: DHCP successful, DHCP failed, Ethernet cable detached.
First of all we need to say that every method suggesting to edit the /etc/network/interfaces file (or files under the /etc/network/interfaces.d/ directory) sould be considered obsolete and it may conflicts with the dhcpcd operations. Have a look at the official Raspberry Pi TCP/IP networking page.
The proper solution is to use the user defined hook scripts, see the dhcpcd-run-hooks man page. In short you have to create a shell script named /etc/dhcpcd.enter-hook. That script will be sourced by dhcpcd
several times during bootstrap and when some events happen (DHCP succeed, cable is connected, etc.), each execution will be identified by a differnt content of the $interface and $reason environment variables.
This simple example will configure an eth0:0 alias at the very first time that dhcpcd
consider the eth0 interface:
# File /etc/dhcpcd.enter-hook # Assign an IP alias to the eth0 interface. if [ "$interface" = "eth0" ]; then case $reason in PREINIT) # Other reasons are: NOCARRIER|CARRIER|BOUND /usr/sbin/ip addr add 10.0.0.38/24 dev eth0 label eth0:0 || true ;; esac fi
Beware to not use addresses in the range 169.254.x.y, that is what's called the Automatic Private IP address. dhcpcd
infact will assign automatically an address like that to the eth0 interface if DHCP fails and no fallback is defined. But more important is that dhcpcd
will delete any IP address in the 169.254.x.y range whenever it obtains a valid IP address for the same interface.
If you enable the debug and logfile /tmp/dhcpcd.log option in /etc/dhcpcd.conf, you can observe this (unexpected to me) behaviour:
eth0: DAD completed for 192.168.3.38 eth0: leased 192.168.3.38 for 36000 seconds eth0: renew in 18000 seconds, rebind in 31500 seconds eth0: writing lease `/var/lib/dhcpcd5/eth0.lease' eth0: adding IP address 192.168.3.38/24 broadcast 192.168.3.255 eth0: adding route to 192.168.3.0/24 eth0: adding default route via 192.168.3.1 eth0: ARP announcing 192.168.3.38 (1 of 2), next in 2.0 seconds eth0: executing `/lib/dhcpcd/dhcpcd-run-hooks' BOUND forking to background forked to background, child pid 656 eth0: deleting IP address 169.254.255.38/32