从ByteBuffer获取IP数据包数据

时间:2016-05-16 02:54:54

标签: java android packet bytebuffer packet-capture

我正在尝试从数据包中获取源和目标地址。这就是我在阅读数据包的方式:

private void debugPacket(ByteBuffer packet) {
    int buffer = packet.get();
    int ipVersion = buffer >> 4;
    int headerLength = buffer & 0x0F;
    headerLength *= 4;
    buffer = packet.get();      //DSCP + EN
    int totalLength = packet.getChar();  //Total Length
    buffer = packet.getChar();  //Identification
    buffer = packet.getChar();  //Flags + Fragment Offset
    buffer = packet.get();      //Time to Live
    int protocol = packet.get();      //Protocol
    buffer = packet.getChar();  //Header checksum

    String sourceIP  = "";
    buffer = packet.get();  //Source IP 1st Octet
    sourceIP += ((int) buffer) & 0xFF;
    sourceIP += ".";

    buffer = packet.get();  //Source IP 2nd Octet
    sourceIP += ((int) buffer) & 0xFF;
    sourceIP += ".";

    buffer = packet.get();  //Source IP 3rd Octet
    sourceIP += ((int) buffer) & 0xFF;
    sourceIP += ".";

    buffer = packet.get();  //Source IP 4th Octet
    sourceIP += ((int) buffer) & 0xFF;

    String destIP  = "";
    buffer = packet.get();  //Destination IP 1st Octet
    destIP += ((int) buffer) & 0xFF;
    destIP += ".";

    buffer = packet.get();  //Destination IP 2nd Octet
    destIP += ((int) buffer) & 0xFF;
    destIP += ".";

    buffer = packet.get();  //Destination IP 3rd Octet
    destIP += ((int) buffer) & 0xFF;
    destIP += ".";

    buffer = packet.get();  //Destination IP 4th Octet
    destIP += ((int) buffer) & 0xFF;

    String hostName;
    try {
        InetAddress addr = InetAddress.getByName(destIP);
        hostName = addr.getHostName();
    } catch (UnknownHostException e) {
        hostName = "Unresolved";
    }

    Log.d(this.getClass().getSimpleName(), "Packet: IP Version=" + ipVersion + ", Header-Length=" + headerLength + ", Total-Length=" + totalLength
            + ", Destination-IP=" + destIP + ", Hostname=" + hostName + ", Source-IP=" + sourceIP+ ", Protocol=" + protocol);
}

它适用于前几个数据包,但有时我会在其中一个packet.get()行获得一个BufferUnderflowException。我该如何防止这种情况?

1 个答案:

答案 0 :(得分:1)

我不敢相信我之前没有抓住这个。我忘了在packet.clear()之后致电debugPacket(packet)