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()
The following methods are used to get the Host Name. getHostName(): This function retrieves the standard hostname for the local computer. getHostByName(): This function retrieves host information corresponding to a hostname from a host database.
The getHostName() method Java InetAddress returns the host name of a corresponding IP address. If this InetAddress was created with a host name, this host name will be remembered and returned else a reverse name lookup will be performed and the result will be returned based on the system configured name lookup service.
Locating Your Computer's Hostname on a PC (Windows 10)In the window the window that appears on the bottom-left hand corner of your screen, type in cmd and click OK. The command prompt window will appear. In this window, type hostname and press Enter. The name of your computer will be displayed.
The corresponding command is uname(1) . Thus to obtain the so-called "hostname", really the "nodename" one can use the command uname --nodename too. This should (generally) be the string that can be found in /etc/hostname .
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With