Fully qualified Java machine name with / etc / hosts

I am trying to get the full name of my computer (Windows 7 x64) in Java. On my machine, I updated the file c: \ Windows \ system32 \ drivers \ etc \ hosts so 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 can never get the full name.

 InetAddress addr = InetAddress.getLocalHost(); String fqName = addr.getCanonicalHostName(); 

How to achieve this in Java?

Thanks,

Shreias

+6
source share
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) { } 
+2
source

from "man hosts" / etc / hosts (or the Windows equivalent) has the following format:

 ip_address fully_qualified_name aliases 

so in your case, the hosts file will look like this:

 10.44.2.167 myserver.domain.com myserver another_alias 

When Java searches for a host, if there is an entry in the / etc / hosts file, it will capture the first host name (and not an alias)

+2
source

Source: https://habr.com/ru/post/888457/


All Articles