选择用于在 Java 中解析主机名的 DNS 服务器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17444862/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-01 02:01:28  来源:igfitidea点击:

Choose DNS server for resolving hostnames in Java

javadnsresolve

提问by coroner

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

通过使用InetAddress类,在 Java 中将主机名解析为 IP 地址相当容易:

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

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

但是这种方法使用的是运行系统使用的DNS服务器。

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

有没有办法指定应该用于解析的DNS服务器?

回答by Lo?a

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

如果您使用 Sun Java,则可以使用以下代码:

//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 propertiesfor more details.

有关更多详细信息,请参阅此博客文章:如何使用 Java System 属性设置自定义 DNS 服务器