Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

hostname

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 resolvable through DNS (in Java).

I can get the local IP addresses without resolution by iterating through NetworkInterfaces.getNetworkInterfaces().

Any answers to this question I've found indicate to use getLocalHost()

InetAddress localhost = java.net.InetAddress.getLocalHost();
hostName = localhost.getHostName();

but this throws an UnknownHostException if the hostname isn't resolvable through DNS.

Is there no way to get the local hostname without a DNS lookup happening behind the scenes?

edit: the IP address retrieved is 10.4.168.23 The exception is java.net.UnknownHostException: cms1.companyname.com: cms1.companyname.com (hostname changed for pseudo-anonymity), and the hosts file does not contain the hostname. But it does know its hostname, so I'm not sure why I can't get it without an exception being thrown.

like image 410
Shawn D. Avatar asked May 18 '11 19:05

Shawn D.


People also ask

How do I find my DNS hostname?

Go to https://who.is/ and search for your domain. In the search results, the section labeled Name Servers shows the location of your DNS host.

How does Java determine hostname?

In Java, you can use InetAddress. getLocalHost() to get the Ip Address of the current Server running the Java app and InetAddress. getHostName() to get Hostname of the current Server name.

Which is the proper method to retrieve the host name of local machine?

The following methods are used to get the Host Name. getHostName(): This function retrieves the standard hostname for the local computer. getHostByName(): This function retrieves host information corresponding to a hostname from a host database.

How do I find the hostname of an IP address?

In an open command line, type ping followed by the hostname (for example, ping dotcom-monitor.com). and press Enter. The command line will show the IP address of the requested web resource in the response. An alternative way to call Command Prompt is the keyboard shortcut Win + R.


2 Answers

Yes, there should be a way in Java to get the hostname without resorting to name service lookups but unfortunately there isn't.

However, you can do something like this:

if (System.getProperty("os.name").startsWith("Windows")) {
    // Windows will always set the 'COMPUTERNAME' variable
    return System.getenv("COMPUTERNAME");
} else {
    // If it is not Windows then it is most likely a Unix-like operating system
    // such as Solaris, AIX, HP-UX, Linux or MacOS.

    // Most modern shells (such as Bash or derivatives) sets the 
    // HOSTNAME variable so lets try that first.
    String hostname = System.getenv("HOSTNAME");
    if (hostname != null) {
       return hostname;
    } else {

       // If the above returns null *and* the OS is Unix-like
       // then you can try an exec() and read the output from the 
       // 'hostname' command which exist on all types of Unix/Linux.

       // If you are an OS other than Unix/Linux then you would have 
       // to do something else. For example on OpenVMS you would find 
       // it like this from the shell:  F$GETSYI("NODENAME") 
       // which you would probably also have to find from within Java 
       // via an exec() call.

       // If you are on zOS then who knows ??

       // etc, etc
    }
}

and that will get you 100% what you want on the traditional Sun JDK platforms (Windows, Solaris, Linux) but becomes less easy if your OS is more excotic (from a Java perspective). See the comments in the code example.

I wish there was a better way.

like image 61
peterh Avatar answered Sep 29 '22 10:09

peterh


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.

like image 32
Malt Avatar answered Sep 29 '22 10:09

Malt