2

With InetAddress.getByName() I would like to be able to distinguish between

  • The name service replied, and the result was negative

and

  • the name service did not reply (no connectivity to DNS server or whatever)

I believe there's a huge difference between the two in terms of support, i.e. telling someone where to look for the problem. It's the difference between a problem with the argument vs an infrastructure problem.

So how can I distinguish between the two?

As I see it there's just UnknownHostException in both cases and the message text is similar. Any good ideas ?

Code snippet to clarify:

try {
    InetAddress addr = InetAddress.getByName(hostname);
} catch (UnknownHostException ex) {
    if ( ..... ) {
        System.out.println("Name server replied but did not know \"" + hostname + "\"");
    } else {
        System.out.println("Name server could not be contacted");
    }
}

To be specific: what would ..... be in the example ??

peterh
  • 18,404
  • 12
  • 87
  • 115

2 Answers2

-1

As an extension, you could always code into your try/catch an extra function to ping the IP address given to see the response (as defined in this (java code to ping an IP address) posting).

By doing so, you could use your function and then verify exactly why the problem occurred. However I might just recommend testing this in advance if possible (e.g. before you try to connect directly).

Community
  • 1
  • 1
Sh4d0wsPlyr
  • 948
  • 12
  • 28
  • Ouch. That's a really bad idea. Ping means ICMP which may be blocked while TCP/UDP is not, i.e. such test will give false results in my scenario. I'm interested in whether or not the *name server* replies, not the endpoint used in the name lookup. Your suggestion would additionally require me to know the DNS server IP. – peterh Sep 10 '14 at 17:43
  • Ping what IP address? The IP address is what he's trying to determine. – user207421 Sep 10 '14 at 18:26
-1

You can use methods inherited by this class from java.lang.Throwable class(see java api) or build custom exception in which you can check two conditions one for negative and null.

  • Not sure I understand. How can I control the nature and contents of exceptions thrown by [getByName](http://docs.oracle.com/javase/8/docs/api/java/net/InetAddress.html#getByName-java.lang.String-) ? That class is part of standard JDK, not mine. – peterh Sep 10 '14 at 17:38