为了避免为了测试目的从公共DNS中查找主机名,我需要设置/etc/host文件,但我并不总是知道需要覆盖IP地址的主机名,所以我尝试使用dnsjava,因为默认的Java DNS解析不允许直接插入缓存。
发布于 2015-03-30 22:42:37
基本上,您需要为dnsjava (A、AAAA等)获取正确的DNS类型缓存。很可能您应该使用A(用于IPv4)或AAAA (用于IPv6),尽管也支持所有其他的DNS条目类型。您将需要创建一个名称实例,并从该实例中插入到缓存中的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
}https://stackoverflow.com/questions/29357625
复制相似问题