Fetching DNS MX and A records

R

Roedy Green

The following code works fine, but it requires hard coding in a DNS
server IP or name. I vaguely recall there is a new way to do this
where it finds a DNS server on its own, or there is a new method to
dynamically find a DNS server.

/**
* Gets all matching dns records as an array of strings.
*
* @param domain domain, e.g. oberon.ark.com or oberon.com which
you want
* the DNS records.
* @param types e.g."MX","A" to describe which types of
* record you want.
*
* @return ArrayList of Strings
*
* @throws NamingException if DNS lookup fails.
*/
private static ArrayList<String> getDNSRecs( String domain,
String... types )
throws NamingException
{
ArrayList<String> results = new ArrayList<String>( 15 );
DirContext ictx = new InitialDirContext();
Attributes attrs =
ictx.getAttributes( "dns://" + DNS_SERVER + "/" +
domain,
types );
for ( Enumeration e = attrs.getAll(); e.hasMoreElements(); )
{
Attribute a = (Attribute) e.nextElement();
int size = a.size();
for ( int i = 0; i < size; i++ )
{
// MX string has priority (lower better) followed by
associated mailserver
// A string is just IP
results.add( (String) a.get( i ) );
}// end inner for
}// end outer for
if ( DEBUGGING && results.size() == 0 )
{
System.err.println( "Failed to find any DNS records for
domain " + domain );
}
return results;
}
 
M

Martin Gregorie

You can look up a domain and its MX records remarkably easily via
DNSJava too. It was your site that put me onto that: thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top