Environment variables may also provide a useful means -- COMPUTERNAME
on Windows, HOSTNAME
on most modern Unix/Linux shells.
See: https://stackoverflow.com/a/17956000/768795
I'm using these as "supplementary" methods to InetAddress.getLocalHost().getHostName()
, since as several people point out, that function doesn't work in all environments.
Runtime.getRuntime().exec("hostname")
is another possible supplement. At this stage, I haven't used it.
import java.net.InetAddress;
import java.net.UnknownHostException;
// try InetAddress.LocalHost first;
// NOTE -- InetAddress.getLocalHost().getHostName() will not work in certain environments.
try {
String result = InetAddress.getLocalHost().getHostName();
if (StringUtils.isNotEmpty( result))
return result;
} catch (UnknownHostException e) {
// failed; try alternate means.
}
// try environment properties.
//
String host = System.getenv("COMPUTERNAME");
if (host != null)
return host;
host = System.getenv("HOSTNAME");
if (host != null)
return host;
// undetermined.
return null;