问题
In using Java's InetAddress.getByName()
to resolve hosts to IPs I want to use Google's DNS instead of the local system's default. Based on other stackoverflow questions as well as the info provided at http://docs.oracle.com/javase/6/docs/technotes/guides/net/properties.html I am using the below to set the appropriate properties:
System.setProperty("sun.net.spi.nameservice.nameservers", "8.8.8.8");
System.setProperty("sun.net.spi.nameservice.provider.1", "dns,sun");
Calling System.getProperty("sun.net.spi.nameservice.nameservers")
later in the program confirms the property is set to 8.8.8.8 - however, network traffic clearly shows all DNS requests are being sent to the system's default and not to Google's DNS. What else should be done to have Java use the requested DNS server?
回答1:
More generally, this is something you will probably have to set outside of Java. It wouldn't really make sense for the JVM to have its own network stack parallel to the one provided by the OS, so DNS resolution is likely to be something you'll need to configure at the OS level.
If DNS resolution is a central requirement for your application, it may actually make more sense for you to do the resolution yourself rather than going through the normal network libraries (which do DNS resolution as a side-effect of normal network operations). I wouldn't doubt you could find a library to help you create the lookup requests.
回答2:
I am facing a similar problem.clean-dns-server-in-jvm
I think that your problem is not because setting DNS property have no effect, but because you are setting those parameters to late in your code, or maybe after a first network connection.
Try to put
System.setProperty("sun.net.spi.nameservice.nameservers", "8.8.8.8");
System.setProperty("sun.net.spi.nameservice.provider.1", "dns,sun");
At the first line of your Main and tell me. Good luck
回答3:
try setting sun.net.spi.nameservice.nameservers 8.8.8.8 in host file under \Windows\System32\drivers. looks like already in your host file sun.net.spi.nameservice.nameservers points to some entry. So try setting try setting sun.net.spi.nameservice.nameservers 8.8.8.8 in last of host file becoz host file gets is first place where host name entries are resolved
来源:https://stackoverflow.com/questions/11957221/setting-dns-property-not-having-any-effect