Search This Blog

nslookup get SRV record using Java

package test;

import java.util.Hashtable;

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

public class NSLookup {

    public static void main(String[] args) throws Throwable {

        String domainName = "unimelb.edu.au";

        System.out.println();
        System.out.println("LDAP SRV records ");
        print(getLdapSRVRecord(domainName));

        System.out.println();
        System.out.println("Kerberos SRV record: ");
        print(getKerberosSRVRecord(domainName));
    }

    static void print(Attribute attr) throws Throwable {
        for (int i = 0; i < attr.size(); i++) {
            String v = String.valueOf(attr.get(i));
            System.out.println(v);
        }
    }

    public static Attribute getLdapSRVRecord(String domainName) throws Throwable {
        return getSRVRecord("ldap", "tcp", domainName);
    }

    public static Attribute getKerberosSRVRecord(String domainName) throws Throwable {
        return getSRVRecord("kerberos", "tcp", domainName);
    }

    public static Attribute getSRVRecord(String serviceType, String protocol, String domainName) throws Throwable {
        Hashtable<String, String> env = new Hashtable<String, String>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
        env.put("java.naming.provider.url", "dns:");
        DirContext ctx = new InitialDirContext(env);
        Attributes attributes = ctx.getAttributes("_" + serviceType + "._" + protocol + "." + domainName,
                new String[] { "SRV" });
        return attributes.get("SRV");
    }

}

No comments:

Post a Comment