问题背景:
在写邮件服务器时,需要对外部SMTP服务器进行通信,那么就用到DNS解析。dnsjava.jar这个包封装了大量DNS解析查询需要用的方法。
但在查询邮件交换记录时,返回的查询结果为null,getErrorString()得到的network error;但是用命令行>nslookup 163.com,成功获得结果。可以确定是程序的问题,或者的dnsjava包的问题。
解决过程:用以下单元测试代码排错。
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Record;
import org.xbill.DNS.TextParseException;
import org.xbill.DNS.Type;
import java.util.*;
public class lookup
{
static public void main(String args[]){
Record[] records;
String domain = "163.com";
try {
//查询邮件交换记录
Lookup lookup = new Lookup(domain, Type.MX);
lookup.run();
if (lookup.getResult() != Lookup.SUCCESSFUL){
System.out.println("ERROR: " + lookup.getErrorString());
//return;
}
Record[] answers = lookup.getAnswers();
for(Record rec : answers){
System.out.println(rec.toString());
} catch (TextParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return;
}
}
引用:In Brian's own words - "The exception is because dnsjava is unable to determine the name server that it should be sending to, and is falling back to the local machine, which is likely not running a name server. Modern versions of dnsjava use the sun.net.dns.ResolverConfiguration class to determine this, which works much better than the prior Windows-specific code, but the version of dnsjava you're using predates that."
I checked using a later version (2.1.3) and all went well.
出自:http://www.coderanch.com/t/585844/java/java/org-xbill-DNS-Lookup-error
下载dnsjava-2.1.3.jar并引入,项目会报错,是因为在2005年1月以后的dnsjava版本已经不封装dns类,不能直接调用。选用其他方法即可。
使用2.1.3版本后就成功查询到MX记录了。wonderful!
感叹一句:原来的dnsjava包的版本也太老了吧!至少不是同一个世纪的。