How do I get the local hostname if unresolvable through DNS in Java?

后端 未结 8 2480
清酒与你
清酒与你 2021-02-19 04:38

This sounds like something that should have been asked before, and it has sort of, but I\'m looking to get the local hostname and IP addresses of a machine even when it is not r

8条回答
  •  深忆病人
    2021-02-19 05:14

    This question is old, but unfortunately still relevant since it's still not trivial to get a machine's host name in Java. Here's my solution with some test runs on different systems:

    public static void main(String[] args) throws IOException {
            String OS = System.getProperty("os.name").toLowerCase();
    
            if (OS.indexOf("win") >= 0) {
                System.out.println("Windows computer name throguh env:\"" + System.getenv("COMPUTERNAME") + "\"");
                System.out.println("Windows computer name through exec:\"" + execReadToString("hostname") + "\"");
            } else {
                if (OS.indexOf("nix") >= 0 || OS.indexOf("nux") >= 0) {
                    System.out.println("Linux computer name throguh env:\"" + System.getenv("HOSTNAME") + "\"");
                    System.out.println("Linux computer name through exec:\"" + execReadToString("hostname") + "\"");
                    System.out.println("Linux computer name through /etc/hostname:\"" + execReadToString("cat /etc/hostname") + "\"");
                }
            }
        }
    
        public static String execReadToString(String execCommand) throws IOException {
            Process proc = Runtime.getRuntime().exec(execCommand);
            try (InputStream stream = proc.getInputStream()) {
                try (Scanner s = new Scanner(stream).useDelimiter("\\A")) {
                    return s.hasNext() ? s.next() : "";
                }
            }
        }
    

    Results for different operating systems:

    OpenSuse 13.1

    Linux computer name throguh env:"machinename"
    Linux computer name through exec:"machinename
    "
    Linux computer name through /etc/hostname:""
    

    Ubuntu 14.04 LTS This one is kinda strange since echo $HOSTNAME returns the correct hostname, but System.getenv("HOSTNAME") does not (this however might be an issue with my environment only):

    Linux computer name throguh env:"null"
    Linux computer name through exec:"machinename
    "
    Linux computer name through /etc/hostname:"machinename
    "
    

    Windows 7

    Windows computer name throguh env:"MACHINENAME"
    Windows computer name through exec:"machinename
    "
    

    The machine names have been replaced for (some) anonymization, but I've kept the capitalization and structure. Note the extra newline when executing hostname, you might have to take it into account in some cases.

提交回复
热议问题