Which of the following is the best and most portable way to get the hostname of the current computer in Java?
Runtime.getRuntime().exec("hostname")
vs
InetAddress.getLocalHost().getHostName()
Strictly speaking - you have no choice but calling either hostname(1)
or - on Unix gethostname(2)
. This is the name of your computer. Any attempt to determine the hostname by an IP address like this
InetAddress.getLocalHost().getHostName()
is bound to fail in some circumstances:
Also don't confuse the name of an IP-address with the name of the host (hostname). A metaphor might make it clearer:
There is a large city (server) called "London". Inside the city walls much business happens. The city has several gates (IP addresses). Each gate has a name ("North Gate", "River Gate", "Southampton Gate"...) but the name of the gate is not the name of the city. Also you cannot deduce the name of the city by using the name of a gate - "North Gate" would catch half of the bigger cities and not just one city. However - a stranger (IP packet) walks along the river and asks a local: "I have a strange address: 'Rivergate, second left, third house'. Can you help me?" The local says: "Of course, you are on the right road, simply go ahead and you will arrive at your destination within half an hour."
This illustrates it pretty much I think.
The good news is: The real hostname is usually not necessary. In most cases any name which resolves into an IP address on this host will do. (The stranger might enter the city by Northgate, but helpful locals translate the "2nd left" part.)
In the remaining corner cases you must use the definitive source of this configuration setting - which is the C function gethostname(2)
. That function is also called by the program hostname
.