In Java 8, how do I get my hostname without hard-coding it in my environment?

Dave picture Dave · Jan 18, 2018 · Viewed 8.3k times · Source

We just upgraded to Java 8 on Amazon Linux. We are using Spring 4.3.8.RELEASE. It used to be that we could get our machine hostname by setting up beans in our application context file like so ...

<bean id="localhostInetAddress" class="java.net.InetAddress" factory-method="getLocalHost" />
<bean id="hostname" factory-bean="localhostInetAddress" factory-method="getHostName" />

But with Java 8, the bean "hostname" now contains the string

localhost

Before Java 8, it used to contain the "hostname" value as run on the command line, which is

[myuser@machine1 ~]$ hostname
machine1.mydomain.org

How can I reconfigure our bean so that it gets the hostname that the command line lists out? I don't want to hard-code anything anywhere.

Answer

mikep picture mikep · Jan 21, 2018

From InetAddress java 8 is not getting the hostname :

There was similar bug fired in JDK.

What I understand is that they changed default resolution process.

They honor configuration in /etc/nsswitch.conf where hosts are configured for /etc/hosts that gives it main priority for name resolution.

Usually /etc/hosts has record for 127.0.0.1 localhost that provide name for host localhost