gpt4 book ai didi

java - 从 DNS 响应获取 IP

转载 作者:太空宇宙 更新时间:2023-11-04 14:54:51 24 4
gpt4 key购买 nike

一般来说,我正在尝试解码 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();
}


}

最佳答案

好吧,我的主要问题是使用 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;
}

关于java - 从 DNS 响应获取 IP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23328379/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com