Friday, July 21, 2006

Java JNDI : Look up IP address by host name

NSLookup using pure Java?


So, is it even possible to do this in pure Java code?
That's the question I was struggling with for one of my recent projects.

If you googled for something like that, you came to the right place.

This is not a tutorial. So without much lecture, here's some sample code that works.


import java.util.Hashtable;

import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class IPLookup {

private static final String IP_ADDR_ATTR = "A";

private static final Log LOG = LogFactory.getLog(IPLookup.class);

private static Hashtable conf = new Hashtable();

public static final void init(String dnsServer, String domain) {
conf.put("java.naming.factory.initial",
"com.sun.jndi.dns.DnsContextFactory");
conf.put("java.naming.provider.url", "dns://" + dnsServer + "/"
+ domain);
}

public static final String lookupIPAddress(String dnsHostName) {
String ipAddress = null;

try {
DirContext ictx = new InitialDirContext(conf);
System.out.println("Created initial context. Looking up "
+ dnsHostName + "...");
Attributes attrs = ictx.getAttributes(dnsHostName,
new String[] { IP_ADDR_ATTR });
Attribute ipAddrAttr = attrs.get(IP_ADDR_ATTR);
if (ipAddrAttr != null) {
ipAddress = (String) ipAddrAttr.get();
}
} catch (NamingException ne) {
LOG.error("Failed to Lookup IP address for " + dnsHostName, ne);
}
return ipAddress;
}

}

Comments: Post a Comment



<< Home

This page is powered by Blogger. Isn't yours?