17

My question is similar to this question . I want to get the real IP of my machine (not 127.0.0.1) but strange, the below code in my Ubuntu is returning 127.0.1.1

InetAddress.getLocalHost().getHostAddress()

Below is my complete code, originally posted in SO at here

public String getMachineIP() {
    try {
        String hostIP = InetAddress.getLocalHost().getHostAddress();
        if (!hostIP.equals("127.0.0.1")) {
            return hostIP;
        }

        /*
         * Above method often returns "127.0.0.1", In this case we need to
         * check all the available network interfaces
         */
        Enumeration<NetworkInterface> nInterfaces = NetworkInterface
                .getNetworkInterfaces();
        while (nInterfaces.hasMoreElements()) {
            Enumeration<InetAddress> inetAddresses = nInterfaces
                    .nextElement().getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                String address = inetAddresses.nextElement()
                        .getHostAddress();
                if (!address.equals("127.0.0.1")) {
                    return address;
                }
            }
        }
    } catch (UnknownHostException e1) {
        System.err.println("Error = " + e1.getMessage());
    } catch (SocketException e1) {
        System.err.println("Error = " + e1.getMessage());
    }
    return null;
}

The above code is returning 127.0.1.1 whereas ifconfig on my Ubuntu machine is giving below output

root@dell:~# ifconfig
eth0      Link encap:Ethernet  HWaddr 00:21:70:b7:30:cd  
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
          Interrupt:28 Base address:0x6000 

eth1      Link encap:Ethernet  HWaddr 00:22:68:d3:02:b5  
          inet addr:192.168.2.112  Bcast:192.168.2.255  Mask:255.255.255.0
          inet6 addr: fe80::222:68ff:fed3:2b5/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:23827 errors:0 dropped:0 overruns:0 frame:32515
          TX packets:23200 errors:46 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000 
          RX bytes:22027719 (22.0 MB)  TX bytes:3778268 (3.7 MB)
          Interrupt:19 

lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:402 errors:0 dropped:0 overruns:0 frame:0
          TX packets:402 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:29197 (29.1 KB)  TX bytes:29197 (29.1 KB)

I found 127.0.1.1 entry in host file (Strange to me, since I never updated this file)

root@dell:~# cat /etc/hosts
127.0.0.1   localhost
127.0.1.1   dell

# The following lines are desirable for IPv6 capable hosts
::1     localhost ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts

How to get the real IP of my machine (not 127.0.0.1)? I am looking ONLY for IPv4 address excluding 127.0.0.0/8 subnet

Community
  • 1
  • 1
ravi
  • 6,140
  • 18
  • 77
  • 154
  • What happens if you skip 127.0.1.1 (wondering) – ssedano May 08 '13 at 15:40
  • Does this help? http://stackoverflow.com/q/8083479/1039920 – Mark Sholund May 08 '13 at 15:42
  • Don't mark as duplicate... I am getting `127.0.1.1` not `127.0.0.1` – ravi May 08 '13 at 15:50
  • 2
    Your `hostname` seems to be `dell` (you report `root@dell` as the command prompt), and the resolver information in `/etc/hosts` says that is 127.0.1.1. And yes, this *is* a duplicate, as you ask " I am looking ONLY for IPv4 address excluding 127.0.0.0/8 subnet" – Raedwald May 08 '13 at 16:43
  • @Raedwald: Yes, `hostname` is dell but I have never added `127.0.1.1` in the host file. `ifconfig` is not showing me `127.0.1.1`, then how come java is returning `127.0.1.1`? – ravi May 08 '13 at 16:50
  • Curiously, `InetAddress.getLocalHost()` actually works well (i.e. return real IP) on Mac OS . I have no idea why. – user1783732 Mar 18 '19 at 19:00

3 Answers3

9

Try this code and paste what you get:

Enumeration en = NetworkInterface.getNetworkInterfaces();
while(en.hasMoreElements()){
    NetworkInterface ni=(NetworkInterface) en.nextElement();
    Enumeration ee = ni.getInetAddresses();
    while(ee.hasMoreElements()) {
        InetAddress ia= (InetAddress) ee.nextElement();
        System.out.println(ia.getHostAddress());
    }
 }

This will loop over all of the IP addresses bounded to your host

maloney
  • 1,633
  • 3
  • 26
  • 49
  • 1
    following is the output `fe80:0:0:0:222:68ff:fed3:2b5%3, 192.168.2.112, 0:0:0:0:0:0:0:1%1 and 127.0.0.1` – ravi May 08 '13 at 16:21
  • 1
    ok well 127 is a loopback address and only visible to your host and 192 is a private IP address. It appears the one starting fe80 is being returned as a Hex IP address - this may be the one you are looking for. I'm not 100% sure, can anyone else shed some light as to why this is a hex address? – maloney May 08 '13 at 16:31
  • I am currently connected to a wifi network. For my purpose 192 will work fine.. – ravi May 08 '13 at 16:32
  • The hex address is the IPv6 equivalent of the 192 address. – Adrian May 08 '13 at 16:32
8

You'll need to use NetworkInterface to enumerate network interfaces; InetAddress.getLocalHost() always returns loopback. This doesn't explain why you get 127.0.1.1 instead of 127.0.0.1, but since that method doesn't do what you're trying to do, it doesn't seem especially pertinent. See: http://docs.oracle.com/javase/6/docs/api/java/net/NetworkInterface.html#getInetAddresses()

Adrian
  • 42,911
  • 6
  • 107
  • 99
  • After enumerating network interface, I am getting `fe80:0:0:0:222:68ff:fed3:2b5%3, 192.168.2.112, 0:0:0:0:0:0:0:1%1 and 127.0.0.1` – ravi May 08 '13 at 16:17
  • 1
    Those are your active network interfaces. In order, they are: external IPv6, external IPv4, loopback IPv6, loopback IPv4. This seems like what you were looking for, according to your question... if you want your external IP, you'll have to use an external service to resolve it. – Adrian May 08 '13 at 16:32
  • I am looking ONLY for IPv4 address excluding `127.0.0.0/8 subnet` – ravi May 08 '13 at 16:35
  • 1
    Then iterate the list you get back and filter out anything that's not an IPv4 address and anything that's on the 127.0.0.0/8 subnet. – Adrian May 08 '13 at 16:55
  • Are you sure about that it always returns loopback? ```java String local = impl.getLocalHostName(); if (local.equals("localhost")) { return impl.loopbackAddress(); } ``` – Arthur Xu Aug 24 '17 at 08:15
2

The whole 127.0.0.0/8 subnet is reserved for loopback devices (Reserved IP addresses) Just ignore any IP beginning with 127 :)

Tobi042
  • 116
  • 2