Scenario:

  • Linux hosts or VMs with 1 single NIC

  • IP address of the interface needs to be changed to a new address in the same network (not as a secondary IP or alias).

  • In this case we use ip command from iproute2 rather than ifconfig from net-tools (deprecated).

Old IP address: 172.16.11.222/24 New IP address: 172.16.11.111/24

Once secondary IP is added, we will be connecting to the host via the new IP through SSH. Connection will NOT be lost after secondary IP is promoted to primary.

Since Linux 2.6.12, /proc/sys/net/ipv4/conf/DEV/promote_secondaries was introduced. This option make secondary IP addresses get promoted when primary IP addresses are removed from the device.

NOTE: If NOT set, when primary IP is removed, all secondary IPs will be purged from the interface.

OK, let’s enable it.

echo 1 | sudo tee /proc/sys/net/ipv4/conf/eth0/promote_secondaries

or as root

echo 1 》 /proc/sys/net/ipv4/conf/eth0/promote_secondaries

NOTE: Of course you can enable it for all interfaces by applying to /proc/sys/net/ipv4/conf/all/promote_secondaries.

Add the new IP

ip addr add 172.16.11.111/24 dev eth0`

NOTE: The new IP is in the same CIDR network as the old address, it becomes a secondary address.

SSH to the host using the new IP

Remove the old IP address

ip addr del 172.16.11.222/24 dev eth0

Done! IP changed, we are still connected ;-D

NOTE: Someone mentioned that this can also be achieved by using ifconfig and route from net-tools. But I haven’t found any. Most likely one will be dealing with route, metric and other complex craps. I am not good at those so I’m not going to touch them for now.

Something extra: if we add the old IP address back soon enough, what will happen? Assume we have an established SSH connection and it was stuck after removing the old IP.

What!? It’ll be revived! Why? It is your homework ;-D