Fully qualified machine name Java with /etc/hosts

Shreyas Shinde picture Shreyas Shinde · May 18, 2011 · Viewed 10.8k times · Source

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

Answer

Kyle picture Kyle · May 18, 2011

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) {
}