Fully qualified machine name Java with /etc/hosts

11,348

Solution 1

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

Solution 2

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)

Share:
11,348
Shreyas Shinde
Author by

Shreyas Shinde

Mild mannered programmer.

Updated on June 09, 2022

Comments

  • Shreyas Shinde
    Shreyas Shinde about 2 years

    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

  • Shreyas Shinde
    Shreyas Shinde about 13 years
    on my machine this still returns the short name.
  • Kyle
    Kyle about 13 years
    Try this link to retrieve the fully qualified host name by calling getCanonicalHostName()
  • Shreyas Shinde
    Shreyas Shinde about 13 years
    getCanonicalHostName() is what I am using but it does not work in my case because of my etc/hosts file.
  • Kyle
    Kyle about 13 years
    Have you tried encapsulating myserver myserver.domain.com in quotes?
  • pxcv7r
    pxcv7r almost 4 years
    This provides only the primary name, not any alias.