style="display:inline-block;width:728px;height:90px"
data-ad-client="ca-pub-7505528228218001"
data-ad-slot="1225241371">

Step 3 - setup the packet handler

This is the meat of our application and the main loop for us. All the packets come here. We pick out the ip4 packets and we process each one of them.

public class IpReassemblyExample implements 
PcapPacketHandler {

  private Ip4 ip = new Ip4(); // Ip4 header

  public void nextPacket(PcapPacket packet, Object user) {

    if (packet.hasHeader(ip)) {
      final int flags = ip.flags();

      /*
       * Check if we have an IP fragment
       */
      if ((flags & Ip4.FLAG_MORE_FRAGEMNTS) != 0) {
        bufferFragment(packet, ip);

        /*
         * record the last fragment
         */
      } else {
        bufferLastFragment(packet, ip);
      }

      /*
       * Our crude timeout mechanism, should be implemented as a separate thread
       */
      timeoutBuffers();
    }
  }
}

We process each Ip4 packet a little differently depending if the the Ip4.FLAG_MORE_FRAGEMNTS is set. If it is not set that means it is the last fragment, otherwise we received a packet inside fragment. If a packet is not fragmented at all, it only contains a single fragment and is always the last fragment and we treat it as a last segment.

We use to methods, bufferFragment() and bufferLastFragment() to record the fragments in the reassembly buffer. The bufferLastFragment() is a little bit special in that it records the length of the entire ip datagram we are reassembling and if all the fragments arrived in sequence it also means we're done with this buffer.

At the end of this loop, we check the time out queue to see if there is anything ready to be timed out. A better approach would be put this check in a sub thread, but for our purpose this a simple check every time a packet arrives is sufficient.