我們使用如下代碼在大量系統上工作:
/**
* Detect the default LDAP server
* @return server:port or null
*/
String getDefaultLdapHost() {
try {
Hashtable<String, String> env = new Hashtable();
env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
DirContext dns = new InitialDirContext(env);
InetAddress address = InetAddress.getLocalHost();
String domain = address.getCanonicalHostName();
if(domain.equals(address.getHostAddress())) {
//domain is a ip address
domain = getDnsPtr(dns);
}
int idx = domain.indexOf('.');
if(idx < 0) {
//computer is not in a domain? We will look in the DNS self.
domain = getDnsPtr(dns);
idx = domain.indexOf('.');
if(idx < 0) {
//computer is not in a domain
return null;
}
}
domain = domain.substring(idx + 1);
Attributes attrs = dns.getAttributes("_ldap._tcp." + domain, new String[] { "SRV" });
Attribute attr = attrs.getAll().nextElement();
String srv = attr.get().toString();
String[] parts = srv.split(" ");
return parts[3] + ":" + parts[2];
} catch(Exception ex) {
ex.printStackTrace();
return null;
}
}
/**
* Look for a reverse PTR record on any available ip address
* @param dns DNS context
* @return the PTR value
* @throws Exception if the PTR entry was not found
*/
private String getDnsPtr(DirContext dns) throws Exception {
Exception exception = null;
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while(interfaces.hasMoreElements()) {
NetworkInterface nif = interfaces.nextElement();
if(nif.isLoopback()) {
continue;
}
Enumeration<InetAddress> adresses = nif.getInetAddresses();
while(adresses.hasMoreElements()) {
InetAddress address = adresses.nextElement();
if(address.isLoopbackAddress() || address instanceof Inet6Address) {
continue;
}
String domain = address.getCanonicalHostName();
if(!domain.equals(address.getHostAddress()) && (domain.indexOf('.') > 0)) {
return domain;
}
String ip = address.getHostAddress();
String[] digits = ip.split("\\.");
StringBuilder builder = new StringBuilder();
builder.append(digits[3]).append('.');
builder.append(digits[2]).append('.');
builder.append(digits[1]).append('.');
builder.append(digits[0]).append(".in-addr.arpa.");
try {
Attributes attrs = dns.getAttributes(builder.toString(), new String[] { "PTR" });
return attrs.get("PTR").get().toString();
} catch(Exception ex) {
exception = ex;
}
}
}
if(exception != null) {
throw exception;
}
throw new IllegalStateException("No network");
}