使用dnsjava解析域名的dns记录
有时候需要程序从Dns的记录中读取某些数据,在Github找了个实现。
DNS Java
Maven
<!-- https://mvnrepository.com/artifact/dnsjava/dnsjava -->
<dependency>
<groupId>dnsjava</groupId>
<artifactId>dnsjava</artifactId>
<version>3.0.2</version>
</dependency>
Main Test
import org.xbill.DNS.Lookup;
import org.xbill.DNS.Record;
import org.xbill.DNS.Resolver;
import org.xbill.DNS.SimpleResolver;
import org.xbill.DNS.Type;
public class DnsTest {
public static void main(String[] args) throws Exception {
// 创建解析器,通过构造函数指定DNS服务器地址
Resolver resolver = new SimpleResolver("114.114.114.114");
// 定义要解析的域名,以及解析类型(这里演示的是解析 txt记录)
Lookup lookup = new Lookup("_test.springboot.io", Type.TXT);
lookup.setResolver(resolver);
// 开始解析,获取到解析后的记录
Record[] records = lookup.run();
// 确定解析ok
if (lookup.getResult() == Lookup.SUCCESSFUL) {
// 遍历结果
for (Record record : records) {
System.out.println(record.rdataToString());
}
} else {
// TODO 解析失败
}
}
}