user3380123
user3380123

Reputation: 703

Different IP addresses by getLocalHost and getByName("localhost")..why so?

Under what circumstances does InetAddress.getLocalHost().getHostAddress() return a different IP address than InetAddress.getByName("localhost")?

On my system, one returns 192.168.0.2 while the other returns 127.0.0.1

Upvotes: 1

Views: 5851

Answers (2)

Shailesh Aswal
Shailesh Aswal

Reputation: 6802

seems, InetAddress.getLocalHost().getHostAddress() is returning your system ip and InetAddress.getByName("localhost") the loopback address.

I doubt the security manager case described by Parthian for getByName,
As per InetAddress API specification for getByName(): http://docs.oracle.com/javase/7/docs/api/java/net/InetAddress.html#getByName%28java.lang.String%29

The method throws: SecurityException - if a security manager exists and its checkConnect method doesn't allow the operation.

whereas getLocalHost() doesn't throw any such exception but returns loopback address as failsafe. http://docs.oracle.com/javase/7/docs/api/java/net/InetAddress.html#getLocalHost%28%29

getByName() needs to connect to DNS to resolve hostname. getByName() in this case is resolving 'localhost' from /etc/hosts(linux) or C:\Windows\System32\drivers\etc (windows). The hostname ip pair is user configurable in these files. To check, you can provide any value to localhost, e.g: localhost 127.0.0.2 in hosts file, and getByName will return it.

Upvotes: 1

Parthian Shot
Parthian Shot

Reputation: 1432

According to this:

"[InetAddress.getLocalHost()] 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. Note: The resolved address may be cached for a short period of time.

If there is a security manager, its checkConnect method is called with the local host name and -1 as its arguments to see if the operation is allowed. If the operation is not allowed, an InetAddress representing the loopback address is returned."

Probably what's happened is you're getting the loopback address because your security manager doesn't allow you to connect using the local subnet's 192 address.

InetAddress.getByName("localhost") justs asks the operating system to perform a name resolution, from what I can tell, anyway.

Upvotes: 0

Related Questions