Skip to content

Instantly share code, notes, and snippets.

@mpellegrini
Created November 13, 2014 04:50
Show Gist options
  • Save mpellegrini/c8b93426af52d6931601 to your computer and use it in GitHub Desktop.
Save mpellegrini/c8b93426af52d6931601 to your computer and use it in GitHub Desktop.
Get LDAP Servers Programmatically
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.spi.NamingManager;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Hashtable;
import java.util.List;
import java.util.TreeMap;
public class DiscoverLdapServers {
// Reference: http://stackoverflow.com/questions/3091984/authenticating-from-java-linux-to-active-directory-using-ldap-without-servername
private static final String[] SRV = new String[] { "SRV" };
public static Collection<InetSocketAddress> srv(String name) throws NamingException {
DirContext ctx = new InitialDirContext();
Attributes attributes = ctx.getAttributes("dns:/" + name, SRV);
if(attributes.get("SRV") == null)
{
return Collections.emptyList();
}
NamingEnumeration<?> e = attributes.get("SRV").getAll();
List<InetSocketAddress> result = new ArrayList<InetSocketAddress>();
while(e.hasMoreElements()) {
String line = (String) e.nextElement();
// The line is priority weight port host
String[] parts = line.split("\\s+");
//int prio = Integer.parseInt(parts[0]);
int port = Integer.parseInt(parts[2]);
String host = parts[3].substring(0, parts[3].length() - 1);
result.add(new InetSocketAddress(host, port));
}
return result;
}
public static void main(String[] args) throws Exception {
LdapTest test = new LdapTest();
// Note that the string contains the environment name. Would need to substitue
// with the respective environment app is running in.
Collection<InetSocketAddress> srvRecords = test.srv("_ldap._tcp.<domain_name>");
for (InetSocketAddress srvRecord : srvRecords) {
System.out.println(srvRecord);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment