Skip to content

Instantly share code, notes, and snippets.

@nimf
Created June 27, 2023 18:05
Show Gist options
  • Save nimf/1a70cdd6e6722d72b51fd205d8a2ad1a to your computer and use it in GitHub Desktop.
Save nimf/1a70cdd6e6722d72b51fd205d8a2ad1a to your computer and use it in GitHub Desktop.
Java DNS lookup test
package org.example;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Hashtable;
import java.util.List;
import javax.naming.NamingEnumeration;
import javax.naming.directory.Attribute;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
public class Main {
public static void main(String[] args) {
System.out.println("Started.");
long start = System.nanoTime();
try {
final String recordType = args[0];
final String name = args[1];
Class.forName("javax.naming.directory.InitialDirContext");
Class.forName("com.sun.jndi.dns.DnsContextFactory");
System.out.println("Querying " + recordType + " records for " + name);
String[] rrType = new String[]{recordType};
List<String> records = new ArrayList<>();
Hashtable<String, String> env = new Hashtable<>();
env.put("com.sun.jndi.ldap.connect.timeout", "5000");
env.put("com.sun.jndi.ldap.read.timeout", "5000");
DirContext dirContext = new InitialDirContext(env);
javax.naming.directory.Attributes attrs = dirContext.getAttributes("dns:///" + name, rrType);
NamingEnumeration<? extends Attribute> rrGroups = attrs.getAll();
while (rrGroups.hasMore()) {
Attribute rrEntry = rrGroups.next();
assert Arrays.asList(rrType).contains(rrEntry.getID());
NamingEnumeration<?> rrValues = rrEntry.getAll();
while (rrValues.hasMore()) {
records.add(String.valueOf(rrValues.next()));
}
rrValues.close();
}
rrGroups.close();
dirContext.close();
System.out.println("Found " + records.size() + " record(s)");
for (String rec : records) {
System.out.println(rec);
}
} catch (Exception e) {
System.out.println("Error: " + e.getLocalizedMessage());
e.printStackTrace(System.out);
} finally {
System.out.println("Finished in " + ((System.nanoTime() - start) / 1000000) + " ms.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment