Used to wrap low-lavel memory address (native buffer/off-heap buffer).
This buffer use network-byte-order (big endian) by default.
Using Packet Buffer.
Allocate and Deallocate buffer
finalPcap pcap =..;// allocate 8 bytes memory block.finalPacketBuffer buffer =pcap.allocate(PacketBuffer.class).capacity(8);// deallocate ( free buffer).asserttrue==buffer.release();// double free is not allowed.assertfalse==buffer.release();
Slice and Unslice buffer
// allocate 8 bytes memory block.finalPacketBuffer buffer =pcap.allocate(PacketBuffer.class).capacity(8);finalPacketBuffer sliced =buffer.slice();finalPacketBuffer unSliced = ((PacketBuffer.Sliced) sliced).unSlice();assert buffer != sliced;assert buffer == unSliced;// Whatever you do with either sliced or unSliced buffer will affect the original buffer.// for example when calling release() on the sliced buffer.asserttrue==sliced.release();assertfalse==buffer.release();assertfalse==unSliced.release();
What happen if I forget to call release() before it's garbage collected?
PacketBuffer uses phantom reference for handling that case. Off-heap (native) buffer will be freed automatically when the object that wraps the off-heap buffer is garbage collected. Instead of waiting for unused buffer object garbage collected, you can free the off-heap buffer immediately by calling release() to avoid a large amount of unused off-heap memory.
You can enable memory leak detection by setting the properties "pcap.leakDetection" to "true". It can be useful to find where is the buffer that you forgot to release.
What happen when I read/write (accessing) freed/closed buffer?
MemoryAccessException will be thrown when you are trying to access the freed/closed buffer.
finalPcap pcap =..;finalPacketHeader header =pcap.allocate(PacketHeader.class);// no need to call buffer.capacity(..); no malloc needed.finalPacketBuffer buffer =pcap.allocate(PacketBuffer.class);pcap.nextEx(header, buffer);// buffer is not guaranteed to be valid after the next call// copy the buffer if necessaryfinal copied =buffer.copy();asserttrue==copied.release();// no need to call buffer.release();