Code and Stuff

Jan 15, 2015

Java: DNS Query

Getting information about a host or a domain in Java is actually quite simple if you use the JNDI (Java Naming and Directory Interface). This interface, available since java 1.3, offers a standardized access to a range of directory services. Among them the DNS.

Its usage can be quite simple. For instance, asking for the IP of a host is simply:

DirContext ctx = new InitialDirContext();
Attributes attr = ctx.getAttributes("dns:/www.example.com");
String ip = attr.get("a").get().toString();

Getting the MX record of a domain is just as simple:

DirContext ctx = new InitialDirContext();
Attributes attr = ctx.getAttributes("dns:/gmail.com",
                                    new String[] { "MX" });
String host = attr.get("MX").get().toString();

And so is quering a different DNS server. The following example will query google's DNS for the MX record of gmail.com:

DirContext ctx = new InitialDirContext();
Attributes attr = ctx.getAttributes("dns://8.8.8.8/gmail.com",
                                    new String[] { "MX" });
String host = attr.get("MX").get().toString();

More

More information can be found at the following sites:

No comments: