您好我正在为学校做作业,要求您使用java构建自己的DNS CLient而不使用任何现有库。 我想出了如何解析响应,但是当答案部分中存在多个记录时出现错误。
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缺失
答案 0 :(得分:0)
看起来您需要了解如何以DNS有线格式编码名称。特别是如何压缩它们。 RFC 1035的4.1.4节将是一个很好的起点。