Linux – Set up two IPs (one using DHCP and other static) over the same Interface

linuxnetworking

I am trying to set up 2 IPs using just one interface. I need this because if the DHCP server is not available the device must be accessible through a static IP. After reading many posts here (and in other forums) and doing many test my /etc/network/interfaces is as follows:

auto lo
iface lo inet loopback

auto enp0s3
allow-hotplug enp0s3
iface enp0s3 inet dhcp

auto enp0s3:0
allow-hotplug enp0s3:0
iface enp0s3:0 inet static
address 192.168.254.250
netmask 255.255.255.0

This seems to work but the static IP is not accessible until the DHCP IP is configured, and I need to access the device through the static IP if there no DHCP server running in the network.
It is important to bear in mind that in the best case I should be able to access the device using either the IP got from DHCP and the static one.

Any advice will be really welcome.

Best Answer

Based upon testing various settings, it appears that your allow-hotplug is your culprit.

Based upon the explanation given by another user at the unix site (see link below), you really do not need it unless you are hooking into the network system with your application via the hotplug event.


Add another ip address to an adaptor

In your /etc/network/interfaces file create your standard interface definition.
After it is created then add a secondary configuration in this manner:

Template:

auto [iface]:[n]
iface [iface]:[n] inet static
standard attributes here...

Whenever you specify the interface name, ensure you also specify the index number of the new virtual interface (the secondary ip address).
n is the interface index.

Example:

auto lo
iface lo inet loopback

auto enp0s3
iface enp0s3 inet dhcp

auto enp0s3:1
iface enp0s3:1 inet static
address 192.168.254.250
netmask 255.255.255.0

auto enp0s3:2
iface enp0s3:2 inet static
address 10.0.0.2
netmask 255.255.0.0
gateway 10.0.0.1

In the above example we have the loopback adaptor created normally and the standard dhcp configuration for the normal interface.

Then we create two additional interfaces, both are statically configured, one on the 192.168.254.0 network and the other on the 10.0.0.0 network. The second virtual interface has the gateway configured while the first does not.


Tl;Dr

Remove the allow-hotplug lines from your network config.


Links

What is allow-hotplug?
https://unix.stackexchange.com/questions/192671/what-is-a-hotplug-event-from-the-interface

How to have more than one ip address on a single interface:
https://www.garron.me/en/linux/add-secondary-ip-linux.html