Lavish Kothari
Lavish Kothari

Reputation: 2331

Different behavior of InetSocketAddress#getHostName in windows and linux for "127.0.0.1"

InetAddress.getByName("127.0.0.1").getHostName()

The above String in windows returns 127.0.0.1 but in linux it returns localhost.

The docs of InetAddress#getHostName says:

If this InetAddress was created with a host name, this host name will be remembered and returned; otherwise, a reverse name lookup will be performed and the result will be returned based on the system configured name lookup service.

I've seen this question, but my question is regarding the difference in behavior of the API in windows and linux and the reason of this difference.

Upvotes: 1

Views: 508

Answers (1)

Fishy
Fishy

Reputation: 1303

So, there is no main difference between Windows and Linux. There is a difference in the configuration of the two, though. As stated in the question that you referenced, it depends on what is inside of the hosts file. This is a file that is on both Windows and Linux, and it tells the OS what IP's can be assigned to specific hostnames. Here is an example entry in the file:

127.0.0.1    localhost

This will tell the OS that if I make a request to localhost, just route the request to 127.0.0.1. It is similar to what a DNS server does, but the process happens on your computer, without checking the internet.

Now, referring why that line changes on different platforms. The documentation says this:

If this InetAddress was created with a host name, this host name will be remembered and returned; otherwise, a reverse name lookup will be performed and the result will be returned based on the system configured name lookup service. If a lookup of the name service is required, call getCanonicalHostName.

This section is referring to the hostname specified in the hosts file. On your Linux system, the hosts file has an entry that looks similar to the one above(which is quite common in Linux environments). Java notices this, and returns that instead of the IP. Since there is no such entry on Windows, it simple returns the IP, instead.

Upvotes: 1

Related Questions