为什么我从数据包中获得负目的地址

时间:2014-07-03 13:57:17

标签: java tcp ip packet

我试图解析数据包以获取目标IP地址并将其转换为主机名。问题是我得到了一个负面的目的地址,如下所示:

  • IP版本:4
  • 标题长度:20
  • 总长度:60
  • 协议:6
  • 来源IP:10.0.2.0
  • 目的地IP:-83.-4.102.16
  • 未知主持人

  • IP版本:4
  • 标题长度:20
  • 总长度:92
  • 协议:6
  • 来源IP:-64.-88.1.5
  • 目的地IP:54。-9.-67.-15

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");
    }

我做错了吗?我该怎么做呢?

1 个答案:

答案 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.