Java DNS Lookup for SRV records
Asked Answered
N

1

7

In the below java code, I am making a DNS SRV record lookup to resolve the target domain name and associated port for a given domain name such as [email protected]. The lookup function indicated with /HERE/ below returns null somehow and I cannot get a a query result (i.e. record array is null). As a consequence, a null pointer exception is thrown when records array is accessed in the for loop.

What do you think I am missing to make the following code work. I am using using dnsjava and the related API jar file is available at http://www.dnsjava.org/download/ (at the bottom of the page). Thanks in advance for your suggestion.

     import org.xbill.DNS.Lookup;
     import org.xbill.DNS.Record;
     import org.xbill.DNS.SRVRecord;
     import org.xbill.DNS.TextParseException;
     import org.xbill.DNS.Type;

     public class DNSLookup {

        public static void main(String[] args) {

          if (args.length < 1) {
             System.err.println("Usage: java -jar DNSLookup <hostname>");
             System.exit(1);
          }

          String query = "_ssh._tcp." + args[0];

          try {
            /*****HERE*********/
            Record[] records = new Lookup(query, Type.SRV).run();

            for (Record record : records) {
                 SRVRecord srv = (SRVRecord) record;

            String hostname = srv.getTarget().toString().replaceFirst("\\.$", "");
            int port = srv.getPort();

            System.out.println(hostname + ":" + port);
          }
          } catch (TextParseException e) {
             e.printStackTrace();
          }
       }
      }
Noninterference answered 13/4, 2012 at 10:2 Comment(1)
If you'd like to run this code 8 years later, when the linked .jar file turns out to be 404 status page, you can use the dependency available in Maven repo: mvnrepository.com/artifact/dnsjava/dnsjavaVegetate
S
5

Your code is fine, except that Lookup.run() returns null (not an empty array) if no records are found.

For example, if you replace _ssh._tcp with _nicname._tcp and then look up uk you'll find an SRV record for the .UK whois server.

If there's a problem it's with your input parameters.

Stivers answered 14/4, 2012 at 8:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.