Capturing the packets without the callback

Handling a callback is sometimes not practical, it often makes the program more complex. So we need an alternative method to capture the packets without a callback.

Note: Both "PacketHeader" and "PacketBuffer" is not freed by the caller, and not guaranteed to be valid after the next call. If you needs it to remain valid, you must make a copy of it.

Docs: libpcap, javadoc.

public static void main(String[] _args)
    throws ErrorException, PermissionDeniedException, PromiscuousModePermissionDeniedException,
        TimestampPrecisionNotSupportedException, RadioFrequencyModeNotSupportedException,
        NoSuchDeviceException, ActivatedException, InterfaceNotUpException,
        InterfaceNotSupportTimestampTypeException {
  var service = Service.Creator.create("PcapService");
  try (var pcap = service.live(service.interfaces(), new DefaultLiveOptions())) {
    PacketHeader header = pcap.allocate(PacketHeader.class);
    PacketBuffer buffer = pcap.allocate(PacketBuffer.class);
    for (int i = 0; i < 10; i++) {
      try {
        pcap.nextEx(header, buffer);
        System.out.println("Header   : " + header);
        System.out.println("Packet   : " + buffer);
      } catch (BreakException e) {
        System.err.println(e.getMessage());
      } catch (TimeoutException e) {
        System.err.println(e.getMessage());
      }
    }
  }
}

Last updated