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?

coroner
  • 513
  • 2
  • 6
  • 13

1 Answers1

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.

Loša
  • 2,621
  • 2
  • 14
  • 19
  • one question. If i resolve domain names fast (300 per Minute), is it heavy/allowed to (e.g Google DNS Servers) DNS Servers? – Giorgos Fandomas Jul 14 '15 at 16:07
  • One potential problem is that this is global. – Paul Draper Nov 15 '15 at 01: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 '17 at 09: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 '17 at 09:24