Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fully qualified machine name Java with /etc/hosts

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

like image 603
Shreyas Shinde Avatar asked May 18 '11 18:05

Shreyas Shinde


People also ask

What should be in etc hosts?

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).

Can you specify a port in etc hosts?

Unfortunately, we can't. The hosts file only deals with hostnames, not ports.

What is the Windows equivalent of ETC hosts?

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.


2 Answers

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) {
}
like image 197
Kyle Avatar answered Sep 25 '22 04:09

Kyle


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)

like image 22
Sujee Maniyam Avatar answered Sep 23 '22 04:09

Sujee Maniyam