1 package edu.uci.iotproject;
3 import org.pcap4j.core.*;
5 import java.io.EOFException;
6 import java.util.concurrent.TimeoutException;
8 * Opens and reads from a pcap file.
9 * This class is nothing but a simple wrapper around some functionality in {@link Pcaps} and {@link PcapHandle} which
10 * serves to simplify client code.
11 * Note that the file is read in offline mode, i.e., this class does not support live processing of packets.
13 * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
14 * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
16 public class PcapReader {
18 private final PcapHandle mHandle;
21 * Create a new {@code PcapReader} that reads the file specified by the absolute path {@code fileName}.
22 * @param fileName The absolute path to the pcap file to be read.
23 * @param berkeleyPacketFilter A Berkeley Packet Filter to be applied when reading the PCAP file to filter out
24 * unwanted packets immediately. May be {@code null} if no filter is to be applied.
25 * @throws PcapNativeException If an error occurs in the pcap native library.
26 * @throws NotOpenException If the pcap file cannot be opened.
28 public PcapReader(String fileName, String berkeleyPacketFilter) throws PcapNativeException, NotOpenException {
31 handle = Pcaps.openOffline(fileName, PcapHandle.TimestampPrecision.NANO);
32 } catch (PcapNativeException pne) {
33 handle = Pcaps.openOffline(fileName);
35 if(!handle.isOpen()) {
36 throw new NotOpenException("could not open pcap file " + fileName);
38 if (berkeleyPacketFilter != null) {
39 handle.setFilter(berkeleyPacketFilter, BpfProgram.BpfCompileMode.OPTIMIZE);
45 * Reads the next packet in the pcap file.
46 * @return The next packet in the pcap file, or {@code null} if all packets have been read.
48 public PcapPacket readNextPacket() {
50 return mHandle.getNextPacketEx();
51 } catch (EOFException eofe) {
53 } catch (PcapNativeException|TimeoutException|NotOpenException e) {
54 // Wrap checked exceptions in unchecked exceptions to simplify client code.
55 throw new RuntimeException(e);