JDK-8169296 : Need a way get local nodename
  • Type: Enhancement
  • Component: core-libs
  • Sub-Component: java.net
  • Affected Version: 8,9
  • Priority: P4
  • Status: New
  • Resolution: Unresolved
  • OS: generic
  • CPU: generic
  • Submitted: 2016-11-06
  • Updated: 2016-11-07
While Java has a way to get the local host's network name, it doesn't have a way to get the name of the local host unrelated to network. This is also sometimes referred to as a nodename.

On Windows this would be the equivalent of environment variable COMPUTERNAME (or better: Win32 function GetComputerName). On Unices it is the equivalent of "uname -n" or (better) calling the C function gethostname(). 

Even host's that aren't networked have a name. For host that are indeed networked the network name is often ambigious as a host may have multiple network interfaces. So there's often a need to get hold of some type of string that can identify the local host. For a lack of better word we refer to this a the nodename in this RFE.

This is standard in other cross-platform languages. Say for example PHP's "gethostname()" or in Python there's platform.node(). However, don't look too much on Python's source code for platform.node(). It does the right thing on Unices but on Windows it resorts to figuring out the nodename by using a Socket. It should have used the Win32 function GetComputerName().

In Java there isn't an easy way to get this information without resorting to JNI.

To have a method for this in System class or perhaps have it as an always available system property, akin to "user.name".

For OSes that doesn't have the concept of nodename the returned value would then be null. However I don't know of any OSes that doesn't have this concept.

On Windows:   System.getenv("COMPUTERNAME"). 

On Unices:  Create a sub-process with Runtime.exec() and harvest the output from "hostname" shell command or "uname -n" command. Ugly.

Yes, in principal, InetAddress.getLocalhost() should return what the gethostname() API delivers. However, there are cases on some platforms where a getnameinfo/getaddrinfo resolution is done which may alter the gethostname result. I think this coding originally came up because of workarounding something - but I would opt for removing getnameinfo/getaddrinfo in getLocalhost - if possible.

The submitter has not mentioned InetAddress.getLocalHost().getHostName(). This should do what he/she wants in most environments.