Is "localhost" a constant anywhere in Java SE 6?
The simple answer is No.
You can confirm this by going to the Java SE javadoc index page for "L" and searching. There is no public "localhost" or local_host" constant listed in the javadoc in any capitalization.
It's not terribly difficult to type out, but it might be nice to have a constant in many places rather than the String.
First, I disagree that it would be "nice". IMO, it would make code less readable. SomeInterface.LOCAL_HOST
is more characters than "localhost"
. And if you used a static import, the reader still has to lookup the definition of LOCALHOST
to figure out what it has actually be bound to.
Second, and more importantly, the "localhost" name is actually a convention rather than a standard. Old Windows systems (for example) didn't provide a default mapping for the "localhost" name, so there is no guarantee that the name would resolve. (And even if it does, there is no guarantee that it will resolve to a loopback IP address.) So if the Java SE APIs did define a symbol for the "localhost" hostname, it would (in theory) raise portability issues.
And note that "localhost"
and InetAddress.getLocalHost().getHostName()
are most likely not the same. The former typically resolves to 127.0.0.1
and the latter typically resolves to an IP address that other systems can route packets to; i.e. NOT a 127.x.x.x
IP address. Does it matter? In a lot of contexts, yes! For example, it is common practice to a use 127.x.x.x
addresses when you explicitly do not want the IP traffic to leave the current host; e.g. because it is being sent unencrypted.