How to: Assign multiple IP addresses to one interface in Ubuntu using the Command Line Interface (CLI)?

How to: Assign multiple IP addresses to one interface in Ubuntu using the Command Line Interface (CLI)?

I have been working with Ubuntu more lately and ran into the need to direct traffic going to one server (via IP) to go to a new server but I couldn’t change the client’s configuration. Because part of the services were already migrated over I could not change the IP address to the old server. Because of this I required a way for the new server to answer on the new IP address assigned to it but also listen to the old server’s IP address. To do this you need your server to have more than one IP address which is possible (have done it with Windows Servers for several years) so just needed to find out how to do it on Ubuntu


Solution

  1. If you need an additional IP address just for the moment you can add it to any interface on your machine with
     sudo ip address add <ip-address>/<netmask> dev <interface>
    

    for example

     sudo ip address add 172.16.100.17/24 dev eth0
    

    would add 172.16.100.17 using a 24bit netmask to the list of addresses configured for your eth0.

    You can check the result with

    ip address show eth0
    

    and you can delete this address again with

    sudo ip address del 172.16.100.17/24 dev eth0
    

    Of course these changes are lost when you reboot your machine.

  2. To make the additional addresses permanent you can edit the file /etc/network/interfaces by adding as many stanzas as needed of the form:
    iface eth0 static
        address 172.16.100.17/24
    

    so if you needed say 2 IP addresses you would do so as follows:

    iface eth0 inet dhcp
    
    iface eth0 inet static
        address 172.16.100.17/24
    
    iface eth0 inet static
        address 172.16.24.15/24
    

    Note we left the dhcp on the first line, so you will end with 3 ip addresses, 2 static ones provided above and one assigned to you by the DHCP server which will be your primary address.

    To activate these settings without a reboot use ifdown/ifup likeso:

    sudo ifdown eth0 && sudo ifup eth0
    

    It is essential to put those two commands into one line if you are remoting into the server because the first one will drop your connection! Given in this way the ssh-session will survive and you’ll be able to reconnect. Exercise caution as if there is an error networking will be dropped but because of the config error it won’t come back up.

 

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.