Alex Rivera | Logout

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

Asked 2011-05-18T19:27:46.013
16

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.

Edit
Report

1 Answer

1

This is a bit of a hack. But you could launch a new Process from Java and run the hostname command. Reading the outputstream of the child process would give you the name of the localhost.

answered 2011-05-18T20:06:09.557

Your Answer