Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I retrieve multiple TXT records from DNS with Java?

Tags:

java

dns

I have a domain with multiple TXT records. Dig shows all of them. The nameserver returns them in a non-deterministic order. Trying to retrieve these records with the javax.naming.directory classes only every results in the first name returned by the nameserver — sometimes it's one, sometimes another, because the order returned by the nameserver varies.

Here's a code fragment:

Hashtable<String, String> env = new Hashtable<String, String>();
env.put("java.naming.factory.initial",
            "com.sun.jndi.dns.DnsContextFactory");
DirContext dirContext = new InitialDirContext(env);
Attributes attrs = dirContext.getAttributes(name, new String[] { "TXT" });

At this point, attrs only ever contains one Attribute. Is this expected behaviour? How can I make Java retrieve all the TXT records?

like image 329
Paul A. Hoadley Avatar asked Sep 05 '12 10:09

Paul A. Hoadley


1 Answers

In my own tests, the (single) returned attribute contains both of the TXT records in the domain I tried:

Attributes attrs = dirContext.getAttributes("paypal.com", new String[] { "TXT" });
Attribute txt = attrs.get("TXT");
NamingEnumeration e = txt.getAll();
while (e.hasMore()) {
     System.out.println(e.next());
}

If that isn't working for you, the dnsjava library would certainly allow you to obtain all of the records.

like image 129
Alnitak Avatar answered Oct 10 '22 15:10

Alnitak