Most Java developers have never needed to interact with the DNS directly; the most well-known job of DNS, that of resolving hostnames to IP addresses, is performed automatically every time a network operation involving a hostname is performed. Similarly, finding a server that is willing to accept email for a particular email address is performed transparently using DNS. How would a Java developer get access to such arcane, low-level information to do something as simple as validate that a particular email address has a server somewhere in the world willing to accept email for it? It all comes down to hierarchy.

Overview Of DNS

DNS, or Domain Name System, was created to provide a globally-distributed database of information about systems and capabilities. To help keep system and organizational information organized, it was decided to break up the chore of maintaining and updating the information across lines known as 'domains'. There are two common types of domain: the top-level domain and subdomains. A top-level domain represents a major division of the DNS space. For example, the TLD '.edu' is reserved for educational institutions, '.com' for businesses, etc. Subdomains (sometimes called second-, third-, etc level domains) represent an organizational entity or subunit; examples would be '', which uniquely identifies the company 'captechventures' in the '.com' top-level domain. An organization can choose to further divide their domain into subsequent subdomains; '' and '' would be examples. Read from right to left, Fully Qualified Domain Names (ones that includes all domains from the lowest level all the way up to the TLD) form a hierarchical tree of domains.

Within these domains administrators are free to define hostnames and services. Definitions take the form of Resource Records, each of which defines a different type of mapping. To define a hostname to IP address mapping, an entry called an 'A record' is made in the DNS configuration for the desired domain. To map the hostname '' to the IP address, the following entry would be added to the '' DNS configuration: 6321 IN A

The name on the left is the FQDN of the host. The number 6321 is the cache time-to-live of the entry, 'IN' indicates this mapping is for the 'IN'ternet class of address, the 'A' is the resource record type, and the rest is the IP address in dotted quad notation. Similarly, servers that are willing to accept SMTP email for users in a particular domain are indicated by 'MX' resource records. MX records include timeout values, classes, and types just like 'A' records, but also include a priority that indicates the order in which MX server should be contacted. When queried using any of a whole host of command-line tools such as dig or nslookup, the popular email service GMail returns the following servers that accept email for users: 613 IN MX 5 613 IN MX 10 613 IN MX 20 613 IN MX 30 613 IN MX 40

Getting Access with Java

Given that DNS is hierarchical and that there's no java.dns package, how can one get to this sort of data? By leveraging another hierarcical Java construct, the classes in javax.naming. You might say, "Hey! Those classes are for looking up JNDI names and LDAP information!" You're correct; one use of javax.naming.InitialContext is to look up JNDI names, and one use of is for looking up LDAP information, but they're much more versatile that that. Specifically, Sun (now Oracle) provides several different Initial Context Factories that provide a wide range of lookup services including DNS resource records.

If you've used JNDI, you're likely familiar with the concept of an InitialContextFactory. To look up DNS information, the context factory to use is "com.sun.jndi.dns.DnsContextFactory". The following code snippet shows how to create an InitialDirContext object ready to perform DNS lookups. Note that all of the code examples below omit error checking and exception handling for clarity.

Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
InitialDirContext idc = new InitialDirContext(env);

If you wish to use DNS servers other than the DNS servers defined on the host where the code will be executed, you can specify the DNS server(s) with an additional environment entry:

env.put(Context.PROVIDER_URL, "dns://");

Similarly, if you'd like to adjust the timeouts, recursion status, and many other DNS lookup parameters, see this excellent article.

Once you have a valid InitialDirContext, looking up DNS information is as simple as specifying what Resource Record type(s) you'd like information on.

private static final String MX_ATTRIB = "MX";
private static final String ADDR_ATTRIB = "A";
private static String[] MX_ATTRIBS = {MX_ATTRIB};
private static String[] ADDR_ATTRIBS = {ADDR_ATTRIB};
private InitialDirContext idc;
public DNSLookup() {
 Properties env = new Properties();
 env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
 idc = new InitialDirContext(env);
public ListString> getMXServers(String domain) {
 ListString> servers = new ArrayListString>();
 Attributes attrs = idc.getAttributes(domain, MX_ATTRIBS);
 Attribute attr = attrs.get(MX_ATTRIB);
 if (attr != null) {
 for (int i = 0; i  attr.size(); i++) {
 String mxAttr = (String) attr.get(i);
 String[] parts = mxAttr.split(" ");
 // Split off the priority, and take the last field
 servers.add(parts[parts.length - 1]);
 return servers;

Once you have a list of MX servers for a domain, you could perform a similar lookup to make sure at least one MX server has a valid IP address. Do perform that lookup, simply substitute A_ATTRIB(s) for MX_ATTRIB(s), and delete the string manipulation that removes the leading priority from the MX records.

public ListString> getIPAddresses(String hostname) {
 ListString> ipAddresses = new ArrayListString>();
 Attributes attrs = idc.getAttributes(hostname, ADDR_ATTRIBS);
 Attribute attr = attrs.get(ADDR_ATTRIB);
 if (attr != null) {
 for (int i = 0; i  attr.size(); i++) {
 ipAddresses.add((String) attr.get(i));
 return ipAddresses;

With "MX" and "A" lookups under your belt, you can validate than the domain for any email address has at least one valid MX server and that its IP address is valid. You could even come up with a service that scans a database of email addresses, strips off the domain, performs the lookup, and sets a flag in the database if the lookup fails. If you want to get fancy, you could even use the java.util.concurrent.Executors.newFixedThreadPool to handle several lookups in parallel. Note that InitialDirContexts are _not_ threadsafe, and must be allocated per thread (the easiest way being via the ThreadLocal mechanism).

If your curiousity had been piqued, follow me into the world of ...

Reverse IP lookups and Canonical Names

In order to look up a hostname given an IP address, you search for a resource record of type "PTR". This RR is a bit of an odd duck - it is a pointer to other parts of the DNS configuration. When looking up a PTR record, you actually search for the dotted quad IP address with the quads reversed, and with .IN-ADDR.ARPA. appended. For example, to see what hostname was defined for IP address, you'd search for "" Rearranging the quads puts the search term into least-to-most specific order when read backwards, which is how 'normal' domain names are arranged.

public String getRevName(String ipAddr) {
 String revName = null;
 String[] quads = ipAddr.split("\\.");
 //StringBuilder would be better, I know.
 ipAddr = "";
 for (int i = quads.length - 1; i >= 0; i--) {
 ipAddr += quads[i] + ".";
 ipAddr += "";
 Attributes attrs = idc.getAttributes(ipAddr, new String[] {"PTR"});
 Attribute attr = attrs.get("PTR");
 if (attr != null) {
 revName = (String) attr.get(0);
 return revName;

Here's an example with a twist:
If you look up MX records for, one of them is ''. The result of an A record lookup for that hostname yields If you perform the above reverse lookup however, you get the hostname ""! What happened? It turns out that you can map many hostnames to a particular IP address, but an IP address can only map to a single hostname. The A record for "" returns the same IP address as '', but the PTR record for '' points to '' only.

A similar concept are CNAME records. The 'C' in CNAME stands for Canonical, meaning the offical name of the host. Instead of having two A records point to the same IP address, one could configure one A mapping as normal ( A, and any subsequent hostnames that refer to the same IP address would have CNAME records like: CNAME CNAME

The advantage here is that if the IP address of the physical server changes, you only have to adjust it in one place, that being the ns1-> mapping. The other mappings will still work, since in essence they're saying "my IP address is the same as '' The same restriction on reverse lookups that applies to multiple A records also applies to CNAME'ed records. and form such a CNAME pair ( 7185 IN CNAME

What if you'd like to look for any information for a domain or host? You can perform a search that uses wildcards in either the record class or record type fields, or both. Instead of "MX" or "A" or any of the other types, you can use "*" to mean 'ANY'. Querying for type 'ANY' (using dig) or Java code using attribute name {"*"} returns our MX servers and our SOA record: 4664 IN MX 10 4664 IN MX 20 4560 IN SOA 2010061605 10800 3600 604800 3600

"*" and "* *" mean any class of information and any type. "IN *" means any internet type, "* A" means any class of address type.


Hopefully this introduction to DNS access via Java has given you another arrow in your quiver to use when you face the DNS dragon and given you a better idea of the different ways in which the javax.naming classes can be used.


Much more information regarding the mapping of DNS Resource Records and different ways to access DNS information can be found here, and examples of different lookups can be found here.