Search code examples
javadnsresolve

Choose DNS server for resolving hostnames in Java


resolving a hostname to an IP address is rather easy in Java by using the InetAddress class like this:

InetAddress address = InetAddress.getByName("www.example.com");

But this method uses the DNS server which is used by the running system.

Is there any way to specify the DNS server that should be used for resolving?


Solution

  • If you use Sun Java, you can use this code:

    //Override system DNS setting with Google free DNS server
    System.setProperty("sun.net.spi.nameservice.nameservers", "8.8.8.8");
    System.setProperty("sun.net.spi.nameservice.provider.1", "dns,sun");
    

    See this blog post: How to set a custom DNS server with Java System properties for more details.