从DNS响应中获取IP

时间:2014-04-27 20:08:04

标签: java dns

在一般情况下,我正在尝试解码DNS响应。我已设法将其从响应的“问题”部分检索名称,但无法从“答案”部分提取IP地址。我很清楚InetAddress.getByName()但这不是我需要的。我需要弄清楚如何将这组字节转换为IP地址...... 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();
    }


}

1 个答案:

答案 0 :(得分:0)

好的,所以我的主要问题是使用readShort()而没有真正关注它在做什么。使用readUnsignedByte()我能够提取我在wireshark中看到的相同信息。所以我只是将所有数据移动到一个字符串中,然后从中解析出IP地址。

        //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;
        }