1 package edu.uci.iotproject.analysis;
3 import org.pcap4j.core.*;
5 import java.io.EOFException;
6 import java.util.concurrent.TimeoutException;
9 * Reads packets from a {@link PcapHandle} (online or offline) and delivers those packets that pass the test exercised
10 * by the provided {@link PcapPacketFilter} onto the provided {@link PacketListener}s.
12 * @author Janus Varmarken
14 public class PcapHandleReader {
16 private final PcapPacketFilter mPacketFilter;
17 private final PcapHandle mHandle;
18 private final PacketListener[] mPacketListeners;
20 public PcapHandleReader(PcapHandle handle, PcapPacketFilter packetFilter, PacketListener... packetListeners) {
22 mPacketFilter = packetFilter;
23 mPacketListeners = packetListeners;
28 * Start reading (and filtering) packets from the provided {@link PcapHandle}.
29 * @throws PcapNativeException if an error occurs in the pcap native library.
30 * @throws NotOpenException if the provided {@code PcapHandle} is not open.
31 * @throws TimeoutException if packets are being read from a live capture and the timeout expired.
33 public void readFromHandle() throws PcapNativeException, NotOpenException, TimeoutException {
35 PcapPacket prevPacket = null;
37 while ((packet = mHandle.getNextPacketEx()) != null) {
38 if (prevPacket != null && packet.getTimestamp().isBefore(prevPacket.getTimestamp())) {
39 // Fail early if assumption doesn't hold.
41 throw new AssertionError("Packets not in ascending temporal order");
43 if (mPacketFilter.shouldIncludePacket(packet)) {
44 // Packet accepted for inclusion; deliver it to observing client code.
45 for (PacketListener consumer : mPacketListeners) {
46 consumer.gotPacket(packet);
51 } catch (EOFException eof) {
52 // Reached end of file. All good.
53 System.out.println(String.format("%s: finished reading pcap file", getClass().getSimpleName()));