1
你好我正在爲學校做一項任務,它需要你使用java構建你自己的DNS CLient,而不使用任何現有的庫。 我想出瞭如何解析響應,但在Answer部分有多個記錄時出現錯誤。當存在多個NS記錄時解析dns響應
public void processResponse(DatagramPacket packet) throws IOException{
DataInputStream din = new DataInputStream(new ByteArrayInputStream(packet.getData()));
din.readShort(); //Transaction ID
din.readShort(); //Flags
int questions = din.readShort();
int answers = din.readShort();
int authorities = din.readShort();
int additional = din.readShort();
int recLen = 0;
while ((recLen = din.readByte()) > 0) {
for (int i = 0; i < recLen; i++) {
din.readByte();
}
}
din.readShort(); // Record type for question
din.readShort(); // Class for question
//ANSWERS
//Just looping for one answer here
for(int i=0;i<1;i++){
din.readShort(); // Record name for Answer
String response = "";
int typeOfRec = din.readShort();
din.readShort(); // Class for answers
int ttl = din.readInt();
short resLength = din.readShort();
switch(typeOfRec){
//A
case 1:{
response+="IP\t";
String ip = "";
for (int j = 0; j < resLength; j++) {
ip+=("" + String.format("%d", (din.readByte() & 0xFF)) + ".");
}
response+=ip+"\t"+ttl;
System.out.println(response);
break;
}
//NS
case 2:{
String ip = "";
response+="NS\t";
while ((recLen = din.readByte()) > 0) {
byte[] record = new byte[recLen];
for (int j = 0; j < recLen; j++) {
record[j] = din.readByte();
}
ip+=new String(record, "UTF-8");
ip+=".";
}
response+=ip+"\t"+ttl;
System.out.println(response);
break;
}
//CNAME
case 5:{
response+="CNAME\t";
break;
}
//MX
case 15:{
response+="MX\t";
break;
}
default:{
break;
}
}
}
}
這是最終處理響應數據包以獲取所需數據的函數。但是,當我運行此代碼時,響應僅爲 NS ns-358.awsdns-44。 86399 .com缺失