0

I am trying to query using the google public dns server (8.8.8.8) to get the IP address of some known URL. However, it seems like I am not able to get that using the following code? I am using the dnsjava java library. This is my current code

The results

        Lookup lookup = new Lookup("stackoverflow.com", Type.NS);
        SimpleResolver resolver=new SimpleResolver("8.8.8.8");

        lookup.setDefaultResolver(resolver);
        lookup.setResolver(resolver);
        Record [] records = lookup.run();
        for (int i = 0; i < records.length; i++) {
            Record  r = (Record ) records[i];
            System.out.println(r.getName()+","+r.getAdditionalName());
        }
    }
    catch (  Exception ex) {
        ex.printStackTrace();
        logger.error(ex.getMessage(),ex);
    }

Results:

stackoverflow.com.,ns-1033.awsdns-01.org.
stackoverflow.com.,ns-cloud-e1.googledomains.com.
stackoverflow.com.,ns-cloud-e2.googledomains.com.
stackoverflow.com.,ns-358.awsdns-44.com.
Dany
  • 11
  • 1
  • 3
  • Yes, should be up now – Dany Jul 01 '19 at 14:42
  • The results also need to appear as text in your question. See https://meta.stackoverflow.com/questions/285551/why-not-upload-images-of-code-on-so-when-asking-a-question/285557#285557. – VGR Jul 01 '19 at 14:43
  • Changes have been made – Dany Jul 01 '19 at 14:46
  • Thank you. I see that you also changed your code from using `Type.A` to `Type.NS`; if you want IPv4 addresses, you want `Type.A`. Or do you want to obtain the addresses of other name servers? – VGR Jul 01 '19 at 14:50
  • I want to use the public google dns at 8.8.8.8 and ask for the specific IP address of some URL – Dany Jul 01 '19 at 14:53

1 Answers1

0

You don’t need a DNS library just to look up an IP address. You can simply use JNDI:

Properties env = new Properties();
env.setProperty(Context.INITIAL_CONTEXT_FACTORY,
    "com.sun.jndi.dns.DnsContextFactory");
env.setProperty(Context.PROVIDER_URL, "dns://8.8.8.8");

DirContext context = new InitialDirContext(env);
Attributes list = context.getAttributes("stackoverflow.com",
    new String[] { "A" });

NamingEnumeration<? extends Attribute> records = list.getAll();
while (records.hasMore()) {
    Attribute record = records.next();
    String name = record.get().toString();
    System.out.println(name);
}

If you insist on using the dnsjava library, you need to use Type.A (as your code was originally doing, before your edit).

Looking at the documentation for the Record class, notice the long list under Direct Known Subclasses. You need to cast each Record to the appropriate subclass, which in this case is ARecord.

Once you’ve done that cast, you have an additional method available, getAddress:

for (int i = 0; i < records.length; i++) {
    ARecord r = (ARecord) records[i];
    System.out.println(r.getName() + "," + r.getAdditionalName()
        + " => " + r.getAddress());
}
VGR
  • 40,506
  • 4
  • 48
  • 63