Search code examples
javaandroidpacketbytebufferpacket-capture

Get IP packet data from ByteBuffer


I'm trying to get the source and destination address from a packet. This is how i am reading the packet:

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

It works fine for the first few packets, but then sometimes i get a BufferUnderflowException at one of the packet.get() lines. How can i prevent this?


Solution

  • I cant believe i didn't catch this earlier. I forgot to call packet.clear() after debugPacket(packet).