1 package edu.uci.iotproject.io;
3 import edu.uci.iotproject.analysis.PcapPacketFilter;
4 import org.pcap4j.core.*;
6 import java.io.EOFException;
7 import java.util.concurrent.TimeoutException;
10 * Reads packets from a {@link PcapHandle} (online or offline) and delivers those packets that pass the test exercised
11 * by the provided {@link PcapPacketFilter} onto the provided {@link PacketListener}s.
13 * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
14 * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
16 public class PcapHandleReader {
18 private final PcapPacketFilter mPacketFilter;
19 private final PcapHandle mHandle;
20 private final PacketListener[] mPacketListeners;
23 * Create a {@code PcapHandleReader}.
24 * @param handle An <em>open</em> {@link PcapHandle} that packets will be read from.
25 * @param packetFilter A {@link PcapPacketFilter} that dictates which of the packets read from {@code handle} should
26 * be delivered to {@code packetListeners}. Note that while a value of {@code null} is not
27 * permitted here, the caller can instead simply provide an implementation that always returns
28 * {@code true} if they want to include all packets read from {@code handle}.
29 * @param packetListeners One or more {@link PacketListener}s to which those packets read from {@code handle} that
30 * pass through {@code packetFilter} are delivered.
32 public PcapHandleReader(PcapHandle handle, PcapPacketFilter packetFilter, PacketListener... packetListeners) {
34 mPacketFilter = packetFilter;
35 mPacketListeners = packetListeners;
40 * Start reading (and filtering) packets from the provided {@link PcapHandle}.
41 * @throws PcapNativeException if an error occurs in the pcap native library.
42 * @throws NotOpenException if the provided {@code PcapHandle} is not open.
43 * @throws TimeoutException if packets are being read from a live capture and the timeout expired.
45 public void readFromHandle() throws PcapNativeException, NotOpenException, TimeoutException {
47 PcapPacket prevPacket = null;
49 while ((packet = mHandle.getNextPacketEx()) != null) {
50 if (prevPacket != null && packet.getTimestamp().isBefore(prevPacket.getTimestamp())) {
51 System.out.println("Out-of-order (in terms of timestamp) packet detected");
53 // Fail early if assumption doesn't hold.
55 throw new AssertionError("Packets not in ascending temporal order");
58 if (mPacketFilter.shouldIncludePacket(packet)) {
59 // Packet accepted for inclusion; deliver it to observing client code.
60 for (PacketListener consumer : mPacketListeners) {
61 consumer.gotPacket(packet);
66 } catch (EOFException eof) {
67 // Reached end of file. All good.
68 System.out.println(String.format("%s: finished reading pcap file", getClass().getSimpleName()));