aboutsummaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/net/HostName.java
blob: 4e791ca117a3e4149b65b3f5e81250dd153ee216 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.net;

import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * Utilities for getting the hostname on a system running with the JVM. This is moved here from the old
 * HostSystem#getHostName in config-model.
 *
 * @author lulf
 */
public class HostName {

    private static String myHost = null;

    /**
     * Static method that returns the name of localhost using shell command "hostname".
     * If you need a guaranteed resolvable name see LinuxINetAddress.
     *
     * @return the name of localhost.
     * @throws RuntimeException if executing the command 'hostname' fails.
     */
    public static synchronized String getLocalhost() {
        if (myHost == null) {
            try {
                Process p = Runtime.getRuntime().exec("hostname");
                BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
                myHost = in.readLine();
                p.waitFor();
                if (p.exitValue() != 0) {
                    throw new RuntimeException("Command 'hostname' failed: exit("+p.exitValue()+")");
                }
            } catch (Exception e) {
                throw new RuntimeException("Failed when executing command 'hostname'", e);
            }
        }
        return myHost;
    }

}