18

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?

1
  • There are DNS libraries in Java, you can use them
    – fge
    Jul 3, 2013 at 9:54

1 Answer 1

17

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.

4
  • one question. If i resolve domain names fast (300 per Minute), is it heavy/allowed to (e.g Google DNS Servers) DNS Servers? Jul 14, 2015 at 16:07
  • One potential problem is that this is global. Nov 15, 2015 at 1:36
  • Running Oracle jre 1.8.0_111. Prefer set the above properties via the command line (i.e. -Dsun.net.spi.nameservice.provider.1="dns,sun" -Dsun.net.spi.nameservice.nameservers=8.8.8.8) so they are not buried in code and forgotten about.
    – paulh
    Oct 25, 2017 at 9:18
  • On linux verification of which DNS server is being used can be done with tcpdump -n 'udp port 53' And many java implementations only cache a DNS lookup for 30 seconds and it is often a good idea to extend this using the sun.net.inetaddr.ttl flag, for example -Dsun.net.inetaddr.ttl=1800 will not result in another lookup for a particular domain until 30 minutes has passed.
    – paulh
    Oct 25, 2017 at 9:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.