5

I'm don't understand, why code below prints 0.0.9.229 instead 127.0.0.1. Can anybody tell me, hot to fix that?

String ha = InetAddress.getLocalHost().getHostAddress();
System.out.println(ha);

UPD: Code running on Ubuntu

/etc/hosts

127.0.0.1       localhost
127.0.1.1       2533
shurik2533
  • 1,770
  • 4
  • 22
  • 41

3 Answers3

10

InetAddress.getLocalHost() doesn't do what most people think that it does. It actually returns the hostname of the machine, and the IP address associated with that hostname. This may be the address used to connect to the outside world. It may not. It just depends on how you have your system configured.

On my windowsbox it gets the machine name and the external ip address. On my linux box it returns hostname and 127.0.0.1 because I have it set so in /etc/hosts

No Idea For Name
  • 11,411
  • 10
  • 42
  • 70
  • I'm using the lib, that contains this code. I suspect, that there must be something like 127.0.0.1 or localhost, but there is 0.0.9.229, that cause Cannot bind to URL error further. I'm don't understand where from 0.0.9.229 – shurik2533 Aug 28 '13 at 13:32
  • I know you're not the selected answer but this answer saved me a ton of grief today. Thanks! – durron597 Sep 17 '13 at 20:17
3

The problem is that my hostname will consists only of numbers and could not be resolved. I change my /etc/hostname with characters at first position and problem has solved.

shurik2533
  • 1,770
  • 4
  • 22
  • 41
2

Use NetworkInterface to enumerate network interfaces; InetAddress.getLocalHost() always returns loopback.If you want to get all IP's associated with your machine use NetworkInterface then you will get 127.0.0.1 also.

 Enumeration<NetworkInterface> nInterfaces = NetworkInterface.getNetworkInterfaces();

    while (nInterfaces.hasMoreElements()) {
        Enumeration<InetAddress> inetAddresses = nInterfaces.nextElement().getInetAddresses();
        while (inetAddresses.hasMoreElements()) {
            String address = inetAddresses.nextElement().getHostAddress();
            System.out.println(address);
        }
    }
amicngh
  • 7,831
  • 3
  • 35
  • 54