javadnsdnsjava

How to put in an entry into dnsjava cache to override DNS lookup


In trying to avoid having a hostname looked up from the public DNS for testing purposes, I need to essentially set /etc/hosts file, but I don't always know what hostnames I'll need to override the IP address for, so I'm trying to use dnsjava since the default Java DNS resolving doesn't allow for inserting directly into the cache.


Solution

  • Basically, you need to grab the correct DNS Type cache for dnsjava (A, AAAA, etc). Most likely A (for IPv4) or AAAA (for IPv6) is what you should use, although all of the other DNS entry types are also supported. You'll need to create a Name instance, and from that an ARecord which will be inserted into the Cache. Example is as below:

    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
    }