PcapReader: provide parameter for specifying a Berkeley Packet Filter
authorJanus Varmarken <varmarken@gmail.com>
Wed, 18 Jul 2018 01:54:51 +0000 (18:54 -0700)
committerJanus Varmarken <varmarken@gmail.com>
Wed, 18 Jul 2018 01:54:51 +0000 (18:54 -0700)
Code/Projects/SmartPlugDetector/src/main/java/edu/uci/iotproject/PcapReader.java

index c8106b242424142cdd4069caf1605e9e3a98d077..bf618eb977d54289aa6a3682553c5b020bb5746d 100644 (file)
@@ -20,15 +20,24 @@ public class PcapReader {
     /**
      * Create a new {@code PcapReader} that reads the file specified by the absolute path {@code fileName}.
      * @param fileName The absolute path to the pcap file to be read.
-     * @throws PcapNativeException If the pcap file cannot be opened.
+     * @param berkeleyPacketFilter A Berkeley Packet Filter to be applied when reading the PCAP file to filter out
+     *                             unwanted packets immediately. May be {@code null} if no filter is to be applied.
+     * @throws PcapNativeException If an error occurs in the pcap native library.
+     * @throws NotOpenException If the pcap file cannot be opened.
      */
-    public PcapReader(String fileName) throws PcapNativeException {
+    public PcapReader(String fileName, String berkeleyPacketFilter) throws PcapNativeException, NotOpenException {
         PcapHandle handle;
         try {
             handle = Pcaps.openOffline(fileName, PcapHandle.TimestampPrecision.NANO);
         } catch (PcapNativeException pne) {
             handle = Pcaps.openOffline(fileName);
         }
+        if(!handle.isOpen()) {
+            throw new NotOpenException("could not open pcap file " + fileName);
+        }
+        if (berkeleyPacketFilter != null) {
+            handle.setFilter(berkeleyPacketFilter, BpfProgram.BpfCompileMode.OPTIMIZE);
+        }
         mHandle = handle;
     }