Search code examples
javaincrementmemory-mapped-filesmappedbytebuffer

MappedbyteBuffer.get() increments position by too much


The relevant part of my file is this:

82 0a 96 c9 82 0a 96 d3 00 66 13 08

I open the file in a mappedbytebuffer and set the position to the beginning. Then I do this:

MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
...
buffer.position(packetInfos.get(idPacket).getStartPos());

//getting the time from the packet header
time = Math.addExact(Math.multiplyExact((long) buffer.order(ByteOrder.LITTLE_ENDIAN).getInt(), 1000), Math.floorDiv(buffer.order(ByteOrder.LITTLE_ENDIAN).getInt(), 1000));

//getting the source ip from the ip frame
buffer.position(packetInfos.get(idPacket).getStartPos() + PACKET_IPSOURCE_OFFS); // puts the buffers position at the part of the file shown above
source = byteToUnsigned(buffer.get()) + "." + byteToUnsigned(buffer.get()) + "." + byteToUnsigned(buffer.get()) + "." + byteToUnsigned(buffer.get());

//getting the destination ip from the ip frame
destination = byteToUnsigned(buffer.get()) + "." + byteToUnsigned(buffer.get()) + "." + byteToUnsigned(buffer.get()) + "." + byteToUnsigned(buffer.get());

The byteToUnsigned method simply does:

public static int byteToUnsigned(byte b){
    return b & 0xFF;
}

source ends up being: "130.10.150.211" when it should be "130.10.150.201". For some reason the get() method increments the position of the buffer by 1 in most cases, but by 5 after the third time? As you might have guessed I'm trying to decode the destination ip afterwards and it starts reading after the "D3", resulting in "0.102.19.8"


Even before the byteToUnsigned calls the source Ip is "-126.10.-106.-45".


After debugging step by step through this line:

source = byteToUnsigned(buffer.get()) + "." + byteToUnsigned(buffer.get()) + "." + byteToUnsigned(buffer.get()) + "." + byteToUnsigned(buffer.get());

Watching buffer.position() and buffer.get(), I could see the following:

  • first get(): buffer.position()=70, buffer.get()=-126
  • second get(): buffer.position()=71, buffer.get()=10
  • third get(): buffer.position()=72, buffer.get()=-106
  • fourth get(): buffer.position()=73, buffer.get()=-45

So the position is incremented correctly, but the bytes between the 72nd and the 77th are not visible to the buffer somehow?


The Api plainly states:

public abstract byte get()
Relative get method. Reads the byte at this buffer's current position, and then increments the position.

What am I missing?


Solution

  • Turns out I'm an enormous idiot. I did not notice the bytes 82 0a 96 repeat just a few bytes to the right. Which is where I accidentally placed the position of the buffer. Don't worry, I'm ashamed.