我试图解析数据包以获取目标IP地址并将其转换为主机名。问题是我得到了一个负面的目的地址,如下所示:
int buffer = packet.get();
int version;
int headerlength;
version = buffer >> 4;
headerlength = buffer & 0x0F;
headerlength *= 4;
Log.d(TAG, "IP Version:"+version);
Log.d(TAG, "Header Length:"+headerlength);
String status = "";
status += "Header Length:"+headerlength;
buffer = packet.get(); //DSCP + EN
buffer = packet.getChar(); //Total Length
Log.d(TAG, "Total Length:"+buffer);
buffer = packet.getChar(); //Identification
buffer = packet.getChar(); //Flags + Fragment Offset
buffer = packet.get(); //Time to Live
buffer = packet.get(); //Protocol
Log.d(TAG, "Protocol:"+buffer);
status += " Protocol:"+buffer;
buffer = packet.getChar(); //Header checksum
String sourceIP = "";
buffer = packet.get(); //Source IP 1st Octet
sourceIP += buffer;
sourceIP += ".";
buffer = packet.get(); //Source IP 2nd Octet
sourceIP += buffer;
sourceIP += ".";
buffer = packet.get(); //Source IP 3rd Octet
sourceIP += buffer;
sourceIP += ".";
buffer = packet.get(); //Source IP 4th Octet
sourceIP += buffer;
Log.d(TAG, "Source IP:"+sourceIP);
status += " Source IP:"+sourceIP;
String destIP = "";
buffer = packet.get(); //Destination IP 1st Octet
destIP += buffer;
destIP += ".";
buffer = packet.get(); //Destination IP 2nd Octet
destIP += buffer;
destIP += ".";
buffer = packet.get(); //Destination IP 3rd Octet
destIP += buffer;
destIP += ".";
buffer = packet.get(); //Destination IP 4th Octet
destIP += buffer;
Log.d(TAG, "Destination IP:" + destIP);
status += " Destination IP:"+destIP;
try {
InetAddress addr = InetAddress.getByName(destIP);
String host = addr.getHostName();
Log.d(TAG, "Hostname:" + host);
}
catch (UnknownHostException e) {
Log.d(TAG,"Unknown host");
}
我做错了吗?我该怎么做呢?
答案 0 :(得分:3)
packet.get()
返回byte
。在java byte
已签名时,您会期望无符号值。使用byte
可获得任何字节的负值,该值应大于127
byte b = 0xFF; // 255
System.out.println(b == -1); // prints true
要将byte
“转换”为正确的无符号值,您必须使用一个使用多于1个字节的基本整数类型,然后执行一些技巧来获取无符号值:
byte b = // your value goes here
int printInt = ((int) b) & 0xFF;
// printInt contains the unsigned value of the byte.