Finding your hostname from Java

6 AM July 6, 2005

How to find a hostname for your local machine, from DevX:


    private String findHostName() {

        try {

            return InetAddress.getLocalHost().getHostName();

        } catch (UnknownHostException e) {

            return "unknown";

        }

    }

By alang | # | Comments (4)
(Posted to javablogs and Java)

Comments

At 09:00, 06 Jul 2005 Simon Brunning wrote:

Python:

socket.gethostbyname('hostname')

(#)
At 09:47, 06 Jul 2005 Alastair wrote:

You need to be careful with this one. It actually does a reverse DNS lookup on the IPv4 address for the outgoing interface of the default route, which:

a) may not be what you expect (ie it may not match the locally-configured hostname),
b) may not be correct anyway, if the DNS is misconfigured and the PTR record does not match the A record (ie you really need to do a forward lookup to check the hostname you get back),
c) can take a long time and freeze your GUI (for example), and
d) can return an IP address (and not a hostname or an error) if there's a SecurityManager that prevents the DNS lookup

Also as a matter of coding style I think you're generally better off throwing the exception out rather than returning a bogus string, but that obviously depends on the context (and your general attitude to exceptions).

Aren't code reviews fun :)

(#)
At 06:24, 07 Jul 2005 Richard wrote:

Simon: I believe the equivalent is:

  socket.gethostname()
(#)
At 11:02, 07 Jul 2005 Alan Green wrote:

Alastair:

[a], [b] and [d] aren't a problem in this context. The code runs on only a few machines and is intended to only to provide a human readable memory-jogger. [c] could be a problem, causing the application to freeze on initialisation. Will have to investigate.

Thanks for your comments - I don't mind a thorough review.

(#)

Add Comment




(Not displayed)






(Leave blank line between paragraphs. URLs converted to links. HTML stripped. Indented source code will be formatted with <pre> tags.)




© 2003-2006 Alan Green