Skip to content

Instantly share code, notes, and snippets.

@scaryghost
Created October 16, 2013 10:33
Show Gist options
  • Save scaryghost/7005796 to your computer and use it in GitHub Desktop.
Save scaryghost/7005796 to your computer and use it in GitHub Desktop.
Example of how to do a dnssd query in Java
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import javax.naming.ldap.InitialLdapContext;
/**
* Example of how to do a dnssd query in Java. Code based on answer from:
* http://stackoverflow.com/questions/738750/querying-the-dns-service-records-to-find-the-hostname-and-tcp-ip
* @author etsai
*/
public class JDnsSD {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws NamingException {
DirContext ctx = new InitialLdapContext();
ctx.addToEnvironment("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory");
ctx.addToEnvironment("java.naming.provider.url", "dns:");
Attributes attrs = (Attributes) ctx.getAttributes(args[0] new String[] { "SRV", "TXT" });
System.out.println(String.format("TXT Record%n==========%n%s", attrs.get("TXT").get(0)));
System.out.println (String.format("%nSRV Records%n==========="));
String[] propNames= {"priority", "weight", "port", "hostname"};
for(NamingEnumeration<?> e= attrs.get("SRV").getAll(); e.hasMoreElements();) {
String values= (String)e.nextElement(), strVal;
String[] properties= values.split(" ");
strVal= "{";
for(int i= 0; i < propNames.length; i++) {
if (i != 0) {
strVal+= ", ";
}
strVal+= propNames[i] + ": " + (i == propNames.length - 1 ? properties[i].substring(0, properties[i].length()-1) : properties[i]);
}
strVal+= "}";
System.out.println(strVal);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment