为了避免出于测试目的从公共 DNS 中查找主机名,我基本上需要设置 /etc/hosts 文件,但我并不总是知道需要覆盖哪些主机名来覆盖 IP 地址,所以我'我正在尝试使用 dnsjava,因为默认的 Java DNS 解析不允许直接插入缓存。
问问题
2697 次
1 回答
-2
基本上,您需要为 dnsjava(A、AAAA 等)获取正确的 DNS 类型缓存。尽管也支持所有其他 DNS 条目类型,但很可能应该使用 A(对于 IPv4)或 AAAA(对于 IPv6)。您需要创建一个 Name 实例,并从中创建一个 ARecord,该 ARecord 将被插入到缓存中。示例如下:
public void addHostToCacheAs(String hostname, String ipAddress) throws UnknownHostException, TextParseException {
//add an ending period assuming the hostname is truly an absolute hostname
Name host = new Name(hostname + ".");
//putting in a good long TTL, and using an A record, but AAAA might be desired as well for IPv6
Record aRec = new ARecord(host, Type.A, 9999999, getInetAddressFromString(ipAddress));
Lookup.getDefaultCache(Type.A).addRecord(aRec, Credibility.NORMAL,this);
}
public InetAddress getInetAddressFromString(String ip) throws UnknownHostException {
//Assume we are using IPv4
byte[] bytes = new byte[4];
String[] ipParts = ip.split("\\.");
InetAddress addr = null;
//if we only have one part, it must actually be a hostname, rather than a real IP
if (ipParts.length <= 1) {
addr = InetAddress.getByName(ip);
} else {
for (int i = 0; i < ipParts.length; i++) {
bytes[i] = Byte.parseByte(ipParts[i]);
}
addr = InetAddress.getByAddress(bytes);
}
return addr
}
于 2015-03-30T22:42:37.257 回答