Skip to content
Advertisement

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

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.

Advertisement

Answer

There are a similar question in the OpenJDK bugs

The newer calls respect the localhosts /etc/nsswitch.conf configuration files. In the case of this machine that file tells these calls to look in files before referencing other naming services.

Since the /etc/hosts file contains an explicit mapping for this hostname / IP combination, that is what is returned.

In the older JDK’s the gethostbyname actually ignored the local machines settings and immediately delegated to the naming service.

You can always use the Runtime class for that :

Process hostname = Runtime.getRuntime().exec("hostname");

BufferedReader stdInput = new BufferedReader(new
            InputStreamReader(hostname.getInputStream()));
String s;
while ((s = stdInput.readLine()) != null) {
        System.out.println(s);
}

But it’s not so recommended as you can see

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement