Reputation: 15501
String hostAddress = InetAddress.getLocalHost().getHostAddress();
The above code works differently on Java 1.7 and 1.6. In 1.6, it returns correct IP allocated to the system (10.4...). In 1.7, it returns 127.0.0.1.
To workaround this issue, I have to use NetworkInterface.getNetworkInterfaces()
and get InetAddress
from it. I will try to connect to every InetAddress
available until once succeeds. This works well but I am wondering why Java 1.7 is behaving differently?
Any help would be great.
Upvotes: 0
Views: 424
Reputation: 30210
It's hard to tell exactly, but a few ideas:
From the docs:
Returns the address of the local host. This is achieved by retrieving the name of the host from the system, then resolving that name into an InetAddress.
Would indicate that the change to gethostname
mentioned by @Jayamohan would be relevant.
Also from the docs
If the operation is not allowed, an InetAddress representing the loopback address is returned.
Which is what you're getting.
127.0.0.1 is indeed a valid address for your machine (most likely). In a multi-address system, how is the JVM to determine which IP you want?
More reading, similar question
Upvotes: 2
Reputation: 12924
This is because of the change since JDK 7u4
.
The details are available here
This is not really a bug but is a behavior change in 7u4. Prior to 7u4 the Linux implementation used gethostname, with 7u4 it uses getnameinfo. This change was an error that crept in with the Mac port.
Upvotes: 1