4

I am using JNDI in Java to perform DNS lookups in my application to resolve A records - running under Java 8 on Windows 7. However, I am having trouble resolving records unless I specify the complete host entry including domain name.

Java appears to be ignoring the DNS search list which is configured on the PC. I don't have a problem including the domain name, if that is what Java requires, but I can't find a public method to obtain the domains in the search list.

The following SSCCE uses the private method sun.net.dns.ResolverConfiguration to obtain the DNS search list, but I shouldn't use it as it is an internal proprietary API and may be removed in a future release.

import java.util.*;
import javax.naming.*;
import javax.naming.directory.*;

public class SSCCE {
  public static void main(String[] args) {
    String[] hostsToLookup = new String[] { "testhost", "testhost.mydomain.com" };

    try {
      System.out.println("DNS Search List:");
      for (Object o: sun.net.dns.ResolverConfiguration.open().searchlist()) {
        System.out.println(" " + o);
      }

      Properties p = new Properties();
      p.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
      InitialDirContext idc = new InitialDirContext(p);

      for (String h : hostsToLookup) {
        System.out.println("Host: " + h);
        try {
          Attributes attrs = idc.getAttributes(h, new String[] { "A" });
          Attribute attr = attrs.get("A");

          if (attr != null) {
            for (int i = 0; i < attr.size(); i++) {
              System.out.println(" " + attr.get(i));
            }
          }
        }
        catch (NameNotFoundException e) {
          System.out.println(" undefined");
        }
      }
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}

When I run this using just the host part it doesn't resolve, but when I manually add the domain from the search list then it does:

DNS Search List:
 mydomain.com
Host: testhost
 undefined
Host: testhost.mydomain.com
 192.0.2.1

Is it possible to either make Java honour the DNS search list using JNDI or is there a public method to obtain the DNS search list?

3
  • I have exactly the same question. What did you end up doing?
    – Hakanai
    Sep 20, 2016 at 6:30
  • With the introduction of Java 9, the above private method is no longer accessible and I haven't been able to find a public alternative method. I ended up providing a JTextField where the user can manually enter the search domains.
    – chrixm
    Nov 8, 2016 at 10:32
  • Ouch... I was hoping that Java 9's promise to make public APIs for all the private stuff would lead somewhere, but it seems like it's closing more doors than it's opening. :(
    – Hakanai
    Nov 9, 2016 at 0:36

0

Your Answer

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

Browse other questions tagged or ask your own question.