Java基于resolv.conf更改DNS服务器动态

时间:2017-10-18 02:32:42

标签: java dns

在要求中,/ etc / resolv.conf将被其他系统修改。例如,首先resolv.conf是1.1.1.1

nameserver 1.1.1.1

事实上,这个DNS服务器无法解析网址

InetAddress addr1 = InetAddress.getByName("www.google.com");
System.out.println(addr1.getHostAddress());

它会抛出异常

java.net.UnknownHostException: www.google.com: unknown error
    at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
    at java.net.InetAddress$2.lookupAllHostAddr(InetAddress.java:928)
    at java.net.InetAddress.getAddressesFromNameService(InetAddress.java:1323)
    at java.net.InetAddress.getAllByName0(InetAddress.java:1276)
    at java.net.InetAddress.getAllByName(InetAddress.java:1192)
    at java.net.InetAddress.getAllByName(InetAddress.java:1126)
    at java.net.InetAddress.getByName(InetAddress.java:1076)

其次,我们将/etc/resolv.conf修改为正常的DNS服务器

nameserver 8.8.8.8

继续使用代码连接到网址

InetAddress addr2 = InetAddress.getByName("www.google.com");
System.out.println(addr2.getHostAddress());

但它仍然会抛出异常,如上所述。

我尝试使用jndi在Java中使用DNS服务器,发现下面更改了resolv.conf并且在更改之后,dnsServer都是1.1.1.1

Hashtable env =  new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.dns.DnsContextFactory");
DirContext ictx = new InitialDirContext(env);
String dnsServers = (String) ictx.getEnvironment().get("java.naming.provider.url");
System.out.println(dnsServers); 

那么JVM如何基于Linux系统动态使用dns服务器

0 个答案:

没有答案