How to add a second local loop_back address?

Solution 1:

1) Can add it temporary using below command

ifconfig lo:40 192.168.40.1 netmask 255.255.255.0 up

2) Add them permanently to /etc/network/interfaces

auto lo lo:10 lo:20
iface lo inet loopback

iface lo:10 inet static
        address 192.168.10.1
        netmask 255.255.255.0
        network 192.168.10.0

iface lo:20 inet static
        address 192.168.20.1
        netmask 255.255.255.0
        network 192.168.20.0

Solution 2:

Though it's probably not actually leaving us soon, ifconfig is the "old" way of doing things, and is being replaced with the ip command. The way to do this with ip is:

ip addr add 192.168.40.1/32 dev lo

There's no need for virtual interfaces any more (i.e., the lo:10 and so forth Mukesh used), but you can still have them if you want like

ip addr add 192.168.40.1/32 dev lo label lo:40

note that I'm using /32 netmasks because lo is special in that it will answer for an address belonging to a network configured on it. So if you add 192.168.40.1/24 it will actually respond to any 192.168.40.* address, not just .1

To that end, for your original example of 127.0.0.2, it will actually already respond to that, because it falls in 127.0.0.0/8 so you don't have to do anything at all to get that particular address.

Also, be careful with addresses on loopback, because the kernel will know that address is on the host and will reply to requests for that address on physical interfaces as well.