'Choose root DNS server to use

I want to choose what DNS server to use. I will make potentially multiple choices in the same JVM. I want to resolve IP addresses from hostnames.

Things I have considered:

  • Using System.setProperty to set DNS settings for Java, but scoping it using classloaders. However, it appears that the System class cannot be loaded differently.

  • Using the dnsjava project. However, I don't see this feature supported. At best, it appears that I would have to handle A record, CNAME records, AAAA records, etc. correctly to get this to work.

What is the easiest way to use a different DNS server in a non-global way?



Solution 1:[1]

This wasn't in the examples for dnsjava, but I figured this out:

(in Scala)

import org.xbill.DNS._

val resolver = new SimpleResolver("8.8.8.8")
val lookup = new Lookup("example.com")
lookup.setResolver(resolver)
val records = lookup.run()
val address = records.asInstanceOf[ARecord].getAddress()

Solution 2:[2]

import org.xbill.DNS.*;
public Class ChoseDNSServer
{
    private SimpleResolver sp;
    private Lookup look;

    public ChoseDNSServer(String ip)
    {
          //Provide ip of server you want to choose for your DNS query
          sp = new SimpleResolver(ip);
          look = new Lookup("URL");
          look.setResolver(sp);          
          //Above method is used for setting up default DNS server.
    }

    public switchToServer(String ip)
    {
         sp = new SimpleResolver(ip);
         look.setResolver(sp);
    }

    public Record lookup(String url)
    {
         look = new Lookup(url);
         return look.run();
    }

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 droptheplot
Solution 2 BHARAT ARYA