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