I'm not so thrilled about the InetAddress.getLocalHost().getHostName()
solution that you can find so many places on the Internet and indeed also here. That method will get you the hostname as seen from a network perspective. I can see two problems with this:
What if the host has multiple network interfaces ? The host may be known on the network by multiple names. The one returned by said method is indeterminate afaik.
What if the host is not connected to any network and has no network interfaces ?
All OS'es that I know of have the concept of naming a node/host irrespective of network. Sad that Java cannot return this in an easy way. This would be the environment variable COMPUTERNAME
on all versions of Windows and the environment variable HOSTNAME
on Unix/Linux/MacOS (or alternatively the output from host command hostname
if the HOSTNAME
environment variable is not available as is the case in old shells like Bourne and Korn).
I would write a method that would retrieve (depending on OS) those OS vars and only as a last resort use the InetAddress.getLocalHost().getHostName()
method. But that's just me.
UPDATE (Unices)
As others have pointed out the HOSTNAME
environment variable is typically not available to a Java application on Unix/Linux as it is not exported by default. Hence not a reliable method unless you are in control of the clients. This really sucks. Why isn't there a standard property with this information?
Alas, as far as I can see the only reliable way on Unix/Linux would be to make a JNI call to gethostname() or to use Runtime.exec()
to capture the output from the hostname
command. I don't particularly like any of these ideas but if anyone has a better idea I'm all ears. (update: I recently came across gethostname4j which seems to be the answer to my prayers).
Long read
I've created a long explanation in another answer on another post. In particular you may want to read it because it attempts to establish some terminology, gives concrete examples of when the InetAddress.getLocalHost().getHostName()
solution will fail, and points to the only safe solution that I know of currently, namely gethostname4j.
It's sad that Java doesn't provide a method for obtaining the computername. Vote for JDK-8169296 if you are able to.
localhost
5
. Subsequent cats should be named5e
and6
;) (Though I suppose you could name oneTenBaseTee
if you're old school)