I am trying get the fully qualified name of my machine (Windows 7 x64) in Java. On my machine, I've updated the c:\Windows\system32\drivers\etc\hosts file such that it has an entry like this:
10.44.2.167 myserver myserver.domain.com
All our systems have an entry in the \etc\hosts file (in the above format) which I cannot change.
The following code always returns "myserver" and I am never able to get the fully qualified name.
InetAddress addr = InetAddress.getLocalHost();
String fqName = addr.getCanonicalHostName();
How do I achieve this in Java?
Thanks,
Shreyas
The /etc/hosts file contains the Internet Protocol (IP) host names and addresses for the local host and other hosts in the Internet network. This file is used to resolve a name into an address (that is, to translate a host name into its Internet address).
Unfortunately, we can't. The hosts file only deals with hostnames, not ports.
Windows users In Windows 10 the hosts file is located at c:\Windows\System32\Drivers\etc\hosts. Right click on Notepad in your start menu and select “Run as Administrator”. This is crucial to ensure you can make the required changes to the file.
A quick and dirty way to do this:
try {
InetAddress addr = InetAddress.getLocalHost();
// Get IP Address
byte[] ipAddr = addr.getAddress();
// Get hostname
String hostname = addr.getHostName();
} catch (UnknownHostException e) {
}
from 'man hosts ' /etc/hosts (or windows equivalent) has the following format:
ip_address fully_qualified_name aliases
so in your case, hosts file would look like:
10.44.2.167 myserver.domain.com myserver another_alias
When Java does host lookup, if /etc/hosts has an entry, it will grab the first host_name (not the alias)
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