How to configure host name resolution to use a custom DNS server in Java?

java.net.InetAddress by default resolves host names using the default permission of the default host name on the local computer:

Host IP address resolution is performed using a combination of local machine configuration information and network naming conventions, such as a DNS system and Network Information Service (NIS). Used specific named services by default on the local computer configured on . For any host name, its corresponding IP address is returned. [a source]

How can we customize this behavior without changing the default machine name for the default host?

For example, is there a way to configure java.net.InetAddress so that it resolves host names through OpenDNS (208.67.222.222, 208.67. 220.220) or Google Public DNS (2001: 4860: 4860 :: 8888, 2001: 4860: 4860: : 8844)?

Or is it the only solution to explicitly create DNS packet requests, send them to servers via java.net.DatagramSocket or java.net.Socket and analyze the answers?

+7
source share
2 answers

Java 9 removed this feature. You will need to use a third-party DNS client library.

If you are using Java 8 or later, you can:

You can set the system property sun.net.spi.nameservice.nameservers as described on this site.

+8
source

Here is the code I wrote for the hard code a foo system name. DNS resolution in Java for passing test cases. Its advantage is to add your specific settings for standard DNS resolution during Java execution.

I recommend not to run it during production . The reflection classes and the Java runtime are used without user intervention.

 private static final String FOO_IP = "10.10.8.111"; /** Fake "foo" DNS resolution */ @SuppressWarnings("restriction") public static class MyHostNameService implements sun.net.spi.nameservice.NameService { @Override public InetAddress[] lookupAllHostAddr(String paramString) throws UnknownHostException { if ("foo".equals(paramString) || "foo.domain.tld".equals(paramString)) { final byte[] arrayOfByte = sun.net.util.IPAddressUtil.textToNumericFormatV4(FOO_IP); final InetAddress address = InetAddress.getByAddress(paramString, arrayOfByte); return new InetAddress[] { address }; } else { throw new UnknownHostException(); } } @Override public String getHostByAddr(byte[] paramArrayOfByte) throws UnknownHostException { throw new UnknownHostException(); } } static { // Force to load fake hostname resolution for tests to pass try { List<sun.net.spi.nameservice.NameService> nameServices = (List<sun.net.spi.nameservice.NameService>) org.apache.commons.lang3.reflect.FieldUtils.readStaticField(InetAddress.class, "nameServices", true); nameServices.add(new MyHostNameService()); } catch (IllegalAccessException e) { e.printStackTrace(); } } 

Hope this helps, but again, to be careful!

+1
source

All Articles