DNS query in Java
Asked Answered
R

4

14

I am messing around with DNS services in Java. I am specifically trying to look up all google.com addresses and display them in an array, similar to running a lookup using nslookup:

nslookup -q=TXT _netblocks.google.com 8.8.8.8

I am using InetAddress for this but I keep on getting exceptions. Since the exceptions refer to an 'Unknown Host', I don't think InetAddress can read TXT records (if I use google.com it works, but that doesn't show the full IP range).

Below is my code:

InetAddress dnsresult[] = InetAddress.getAllByName("_netblocks.google.com");

for (int i=0; i<dnsresult.length; i++)
    System.out.println(dnsresult[i]);

I would appreciate it if someone could point me in the right direction.

Regeneration answered 17/2, 2015 at 10:44 Comment(2)
This problem may not be Java related only since my ping also can't resolve _netblocks.google.com.Termite
Thanks Zhedar, I know that :) I added that to illustrate what I am trying to do. If I use 'google.com' as my argument, it does pop out an IP. But that is the A record. I need to grab the TXT record.Regeneration
M
12

You cannot lookup TXT or other DNS records InetAddress class. InetAddress.getAllByName() looks up for A, or AAAA records only.

Check DNS Java for your needs.

Misfeasance answered 17/2, 2015 at 22:43 Comment(0)
V
6

Here is an example that does what you are trying to do:

Attribute attr = new InitialDirContext().getAttributes("dns:_netblocks.google.com", new String[] {"TXT"}).get("TXT");
System.out.println("attr.get() = " + attr.get());
System.out.println("attr.getAll() = " + Collections.list(attr.getAll()));

If you want to use a custom dns server use "dns://1.1/_netblocks.google.com" instead.

Vulpine answered 26/10, 2018 at 5:20 Comment(0)
B
5

InetAddress doesn't do this, but you can accomplish DNS TXT record lookups in Java via the JNDI DNS provider.

Bisson answered 17/2, 2015 at 23:5 Comment(0)
C
1

I ended up using Google's "JSON API for DNS over HTTPS (DoH)"

https://developers.google.com/speed/public-dns/docs/doh/json

Cambria answered 5/10, 2022 at 14:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.