Perform trigger traffic extraction on data from Feb 13 experiment
[pingpong.git] / Code / Projects / SmartPlugDetector / src / main / java / edu / uci / iotproject / PcapReader.java
1 package edu.uci.iotproject;
2
3 import org.pcap4j.core.*;
4
5 import java.io.EOFException;
6 import java.util.concurrent.TimeoutException;
7 /**
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.
12  *
13  * @author Janus Varmarken {@literal <jvarmark@uci.edu>}
14  * @author Rahmadi Trimananda {@literal <rtrimana@uci.edu>}
15  */
16 public class PcapReader {
17
18     private final PcapHandle mHandle;
19
20     /**
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.
27      */
28     public PcapReader(String fileName, String berkeleyPacketFilter) throws PcapNativeException, NotOpenException {
29         PcapHandle handle;
30         try {
31             handle = Pcaps.openOffline(fileName, PcapHandle.TimestampPrecision.NANO);
32         } catch (PcapNativeException pne) {
33             handle = Pcaps.openOffline(fileName);
34         }
35         if(!handle.isOpen()) {
36             throw new NotOpenException("could not open pcap file " + fileName);
37         }
38         if (berkeleyPacketFilter != null) {
39             handle.setFilter(berkeleyPacketFilter, BpfProgram.BpfCompileMode.OPTIMIZE);
40         }
41         mHandle = handle;
42     }
43
44     /**
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.
47      */
48     public PcapPacket readNextPacket() {
49         try {
50             return mHandle.getNextPacketEx();
51         } catch (EOFException eofe) {
52             return null;
53         } catch (PcapNativeException|TimeoutException|NotOpenException e) {
54             // Wrap checked exceptions in unchecked exceptions to simplify client code.
55             throw new RuntimeException(e);
56         }
57     }
58
59 }