Is "localhost" a constant anywhere in Java SE 6? It's not terribly difficult to type out, but it might be nice to have a constant in many places rather than the String. Are there standard practices around this?

Edit: I know how to create a constant. In the past, I've found constants such as org.apache.http.HttpHeaders cleaner than using my own, as they are less prone to typos or accidental edits.

8

2 Answers

Well, you can get the local host's name like this:

InetAddress.getLocalHost().getHostName() 

The previous snippet will return the local host's configured name (not really the string "localhost"). I believe you're better off writing your own constant:

public static final String LOCAL_HOST = "localhost"; 

And (although some people will say it's a bad practice, but that's open to debate) you can import the constant statically in any class where you need it, just replace "package.to" with the real package where the class resides and TheClass with the actual name of the class defining the constant:

import static package.to.TheClass.LOCAL_HOST; 

In this way, using the constant will be a simple matter of writing LOCAL_HOST where needed.

1

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.

6