如何将条目放入 dnsjava 缓存以覆盖 DNS 查找
How to put in an entry into dnsjava cache to override DNS lookup
为了避免出于测试目的从 public DNS 中查找主机名,我基本上需要设置 /etc/hosts 文件,但我并不总是知道我会使用哪些主机名需要覆盖 IP 地址,所以我尝试使用 dnsjava,因为默认 Java DNS 解析不允许直接插入缓存。
基本上,您需要为 dnsjava(A、AAAA 等)获取正确的 DNS 类型缓存。您应该使用 A(对于 IPv4)或 AAAA(对于 IPv6),尽管也支持所有其他 DNS 条目类型。您将需要创建一个 Name 实例,并从中创建一个 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
}
为了避免出于测试目的从 public DNS 中查找主机名,我基本上需要设置 /etc/hosts 文件,但我并不总是知道我会使用哪些主机名需要覆盖 IP 地址,所以我尝试使用 dnsjava,因为默认 Java DNS 解析不允许直接插入缓存。
基本上,您需要为 dnsjava(A、AAAA 等)获取正确的 DNS 类型缓存。您应该使用 A(对于 IPv4)或 AAAA(对于 IPv6),尽管也支持所有其他 DNS 条目类型。您将需要创建一个 Name 实例,并从中创建一个 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
}