1

I have the following question for all Java pundits out there.

I am trying to came up with a reliable way of creating an localHost InetAddress object as a fallback way to InetAddress.getLocalHost().

I am facing the following issue:

There are cases where my Java application would not start due to an UnknownHostException being thrown, in case the network connection of the machine it runs from is down (deploying on Windows machines).

So my ideas so far are the following:

1) Either try to get the localHost InetAddress object from the NetworkInterfaces Enumeration (which I found a bit cumbersome).

2) Try to get the local host name string via the System environment and then trying to create a InetAddress object by doing InetAddress.getByName().

I strongly favor the second approach as it much easier and seems a bit sleeker, but I am still getting issues getting the InetAddress object I want, in case the network connection is down.

Now my questions, are two:

1) Given the fact that I maintain a hosts file within the said machine, that contains the machine's entry (hostname - IP Address) wouldn't it be possible for #2 to work as intended? I know that eventually the DNS resolution will come down to the actual OS but shouldn't Windows be able to use their hosts file to do this even no network connection was available.

2) Is there any way possible to create an InetAddress object given the host name of a machine but without this machine having an active network connection - interface being down (thus avoiding the UnkownHostException mentioned before)?

1 Answer 1

1

1) It would work as intended provided that:

  • the local DNS resolver was configured to check the "hosts" file before external DNS servers, and

  • the entry was correct, and it referred to a working IP address for the local host.

An alternative is to use a loopback address (e.g. "localhost" / 127.0.0.1)

2) Sure. Use InetAddress.getByAddress(String, byte[]). Note that the name is not checked in DNS.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.