On a general level I'm trying to decode a DNS response. I've manage to make it as far as retrieving the names from the 'questions' section of the response but cannot manage to extract the IP addresses from the 'answers' section. I'm well aware of InetAddress.getByName() but thats not what I need. I need to figure out how to convert this set of bytes to an IP address... enter image description here

private static void disectQuery(byte[] received) {

    ByteArrayInputStream bais = new ByteArrayInputStream(received);
    DataInputStream DataIS = new DataInputStream (bais);

    DNSResponse Response = new DNSResponse();

    try {
        Response.TID = DataIS.readShort();
        Response.Flags = DataIS.readShort();
        Response.NumQuestions = DataIS.readShort ();
        Response.NumAnswers = DataIS.readShort();
        Response.NumAuthorities = DataIS.readShort ();
        Response.NumAdditional = DataIS.readShort ();

        String rest = null;
        int questionsLeft = Response.NumQuestions;
        while(questionsLeft-- > 0) {
            byte[] buffer = new byte[lastHostQueried.length()+1];
            DataIS.readFully (buffer);
            rest = new String(buffer, "latin1");
            int queryType = DataIS.readShort ();
            int queryClass = DataIS.readShort ();
        }
        int answersLeft = Response.NumAnswers;
        int i=13;
        while(i-- > 0) {
            DataIS.readShort();
        }
        while(answersLeft-- > 0) {
            ????
        }

    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}
有帮助吗?

解决方案

Ok so my primary problem was using readShort() without really paying attention to what it was doing. Using readUnsignedByte() I'm able to extract the same information I was seeing in wireshark. So I just moved all that data into a string then parsed the IP addresses out of it.

        //Move remaining response bytes into string
        String answers = "";
        try {
            while(true) {
                rest = DataIS.readUnsignedByte() + "";
                answers += Integer.parseInt(rest, 10) + " ";
            }
        }
        catch(EOFException ignore) {}
        String[] answersArray = answers.split(" ");

        //Initialize IPAddresses array
        String IPAddresses[] = new String[Response.NumAnswers];
        for(int i=0; i<Response.NumAnswers; i++)
            IPAddresses[i] = "";

        int offset = 12;
        for(int i=0; i<Response.NumAnswers; i++) {


            int j=0;
            while(j++<3) 
                IPAddresses[i] += answersArray[offset+j] + ".";
            IPAddresses[i] += answersArray[offset+j] + "";
            offset += 16;
        }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top