从 ByteBuffer 中获取 IP 包数据

Get IP packet data from ByteBuffer

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

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。我该如何防止这种情况?

真不敢相信我没早点发现这个。我忘记在 debugPacket(packet) 之后调用 packet.clear()