Write the packets to a capture file

Capture the packets and write them to a capture file.

Note: Pcap.dumpOpen(String) will override if the "savefile" already exists; If you need to add a captured packet to the existing "savefile" you can use Pcap.dumpOpenAppend(String) instead.

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())) {
    try (var dumper = pcap.dumpOpen("savefile.pcap")) {
      try {
        pcap.loop(
            10,
            (args, header, buffer) -> {
              System.out.println("Args     : " + args);
              System.out.println("Header   : " + header);
              System.out.println("Packet   : " + buffer);
              dumper.dump(header, buffer);
            },
            "Hello pcap!");
      } catch (BreakException e) {
        System.err.println(e.getMessage());
      } catch (ErrorException e) {
        System.err.println(e.getMessage());
      }
    }
  }
}

Last updated