在尝试避免从公共DNS中查找主机名以进行测试时,我需要实际设置/ etc / hosts文件,但我并不总是知道我需要覆盖哪些主机名IP地址,因此我尝试使用dnsjava,因为默认的Java DNS解析不允许直接插入缓存。
答案 0 :(得分:-1)
基本上,您需要为dnsjava(A,AAAA等)获取正确的DNS类型缓存。尽管所有其他DNS条目类型也受支持,但很可能是您应该使用A(对于IPv4)或AAAA(对于IPv6)。您需要创建一个Name实例,并从中创建一个将插入到Cache中的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
}