Wednesday, December 29, 2004

dns lookup menggunakan JNDI

import javax.naming.*;

import com.sun.jndi.dns.*;
import java.util.Hashtable;

public class TestDNS {
public static void main(String[] argv) {
Name cn = null;
String name = argv[0];
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.dns.DnsContextFactory");
env.put(Context.PROVIDER_URL, "dns://IP for DNS Server/");

try {
// Create the initial context
Context ctx = new InitialContext(env);
// print the fully qualified name (.)
System.out.println("Name in namespace: "+ctx.getNameInNamespace());
// retrieve the parser associated with the named context
NameParser np = ctx.getNameParser(ctx.getNameInNamespace());
if (argv.length != 1) {
System.out.println("Usage: java TestDNS ");
System.exit(-1);
}
// parse the name into its components and print them
cn = np.parse(name);
System.out.println("Name is: "+cn.toString());
System.out.println("The parsed name has "+cn.size()+" components:");
for (int i=0; i lt cn.size(); i++){
System.out.println(cn.get(i));
}
System.out.print("Trying to lookup ");
// get the prefix (domain) and suffix (hostname)
Name domain = cn.getPrefix(cn.size()-1);
Name host = cn.getSuffix(cn.size()-1);
System.out.println("DNS Host: "+host+" Domain: "+domain);
// retrieve the named object
Object obj = ctx.lookup(domain);
System.out.println(domain.toString()+" is bound to: "+obj);
// retrieve and print the environment in effect
System.out.println("Domain properties: "+ ((Context)obj).getEnvironment());
// retrieve and print the IP address (the DNS A records)
System.out.println("IP for: "+cn+ " is: "+
((DnsContext)obj).getAttributes(host, new String[]{"A"}));

// we're done so close the context
ctx.close();
} catch (NamingException e) {
System.err.println("Problem looking up " + cn + ": " + e);
}
}
}

Before you run this application, make sure you specify the IP address for the DNS server.

Here is a sample run:

prompt> java TestDNS prep.ai.mit.edu


Name in namespace: .
Name is: prep.ai.mit.edu
The parsed name has 4 components:
edu
mit
ai
prep
Trying to lookup DNS Host: prep Domain: ai.mit.edu
ai.mit.edu is bound to: com.sun.jndi.dns.DnsContext@b89838
Domain properties: {java.naming.provider.url=dns://IP for DNS Server/, java.namin
g.factory.initial=com.sun.jndi.dns.DnsContextFactory}
IP for: prep.ai.mit.edu is: {a=A: 199.232.41.9}

0 Comments:

Post a Comment

<< Home