在Java中针对特定DNS服务器进行查询

4

我正在尝试使用Linux shell和Java查询特定的DNS服务器。

使用dig命令可以正常工作,但Java方法则不行。这是怎么回事?
 dig @dns.nic.it test.it
;; QUESTION SECTION: ;test.it. IN A
;; AUTHORITY SECTION: test.it. 10800 IN NS dns2.technorail.com. test.it. 10800 IN NS dns.technorail.com. test.it. 10800 IN NS dns3.arubadns.net. test.it. 10800 IN NS dns4.arubadns.cz.


Java方法:

        public static void rootDNSLookup(String domainName) throws NamingException{
String server="dns://dns.nic.it";
Hashtable env = new Hashtable(); env.put("java.naming.factory.initial", "com.sun.jndi.dns.DnsContextFactory"); env.put("java.naming.provider.url", server);
DirContext ictx = new InitialDirContext(env); Attributes attrs = ictx.getAttributes(domainName, new String[] {"A", "AAAA", "NS", "SRV"}); System.out.println(attrs); NamingEnumeration e = attrs.getAll(); while(e.hasMoreElements()) { Attribute a = e.next(); System.out.println(a.getID() + " = " + a.get()); }
}

Java输出:

没有属性

这段代码不会打印出“没有属性”。 - user207421
它对你打印了什么吗? - user121196
这段代码中没有打印“no attributes”的内容。请解释一下或修改你的问题。 - user207421
1
System.out.println(attrs); 打印出 "没有属性"。 - user121196
2个回答

2
最好的方法是使用库 dnsjava
你需要找到的特定类是 SimpleResolver。它有两个构造函数。当不带参数使用时,它将使用系统的DNS设置。如果提供IP地址,则会强制将其作为DNS服务器。 你可以在这里找到一个很好的使用示例:dnsjava示例

1
链接已失效。我正在尝试仅使用Java(没有在请求者上安装BIND)进行一些简单的dig模拟。有没有什么提示呢? :) - DraxDomax

0

不要试图同时获取所有属性。

使用:

Attributes attrs = ictx.getAttributes(domainName, new String[] {"A"});

使用一个包含所有所需属性的字符串数组,并迭代调用,传递属性。
String[] attributes = {"A", "AAAA", "NS", "SRV"};
for (String attribute : attributes) {
    ...
    Attributes attrs = ictx.getAttributes(domainName, new String[] {attribute});
    ...
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接