Class NetPcap

java.lang.Object
com.slytechs.sdk.jnetpcap.api.BaseNetPcap
com.slytechs.sdk.jnetpcap.api.NetPcap
All Implemented Interfaces:
com.slytechs.sdk.common.util.Named, AutoCloseable

public final class NetPcap extends BaseNetPcap implements com.slytechs.sdk.common.util.Named, AutoCloseable
High-level packet capture and protocol dissection API.

NetPcap wraps the low-level Pcap bindings and integrates protocol dissection so that packets delivered through dispatch(int, PacketHandler.OfPacket, U), loop(int, PacketHandler.OfPacket, U), next(), and nextEx() are fully dissected before reaching the caller. Protocol headers are accessible via the zero-allocation hasHeader() pattern.

License activation is implicit — the Community Edition activates automatically on the first NetPcap operation. No setup is required. Commercial keys are resolved from environment variables, system properties, file paths, and container secrets. See activateLicense() for the full resolution order if manual activation is needed.

Factory Methods

NetPcap factory methods
MethodUse CaseActivated
create(String) Two-stage live capture — configure then activateNo
openLive(String, int, boolean, Duration) One-shot live captureYes
openOffline(String) Read pcap/pcapng fileYes
openDead(PcapDlt, int) Filter compilation or dump file writingYes

Usage Examples

Live Capture with BPF Filter

try (NetPcap pcap = NetPcap.create("eth0")) {
    pcap.setSnaplen(65535)
        .setPromisc(true)
        .setTimeout(Duration.ofMillis(100))
        .activate();

    pcap.setFilter("tcp port 443");

    Ip4 ip4 = new Ip4();
    Tcp tcp = new Tcp();

    pcap.loop(-1, packet -> {
        if (packet.hasHeader(ip4) && packet.hasHeader(tcp))
            System.out.printf("%s:%d -> %s:%d%n",
                ip4.src(), tcp.srcPort(),
                ip4.dst(), tcp.dstPort());
    });
}

Offline File Reading with Protocol Dissection

PacketSettings settings = new PacketSettings().dissect();

try (NetPcap pcap = NetPcap.openOffline("capture.pcap", settings)) {
    Ethernet eth = new Ethernet();
    Ip4 ip4 = new Ip4();

    pcap.loop(-1, packet -> {
        if (packet.hasHeader(eth) && packet.hasHeader(ip4))
            System.out.printf("%s -> %s%n", ip4.src(), ip4.dst());
    });
}

Multi-threaded Producer-Consumer

BlockingQueue<Packet> queue = new LinkedBlockingQueue<>(10000);

// Capture thread
try (NetPcap pcap = NetPcap.openLive("eth0", 65535, true, Duration.ofSeconds(1))) {
    pcap.loop(-1, packet -> {
        if (filter(packet))
            queue.put(packet.persist());   // persist before callback returns
    });
}

// Worker thread — each needs its own header instances
Tcp tcp = new Tcp();
while (running) {
    Packet p = queue.poll(100, TimeUnit.MILLISECONDS);
    if (p != null) {
        if (p.hasHeader(tcp)) process(tcp);
        p.recycle();
    }
}
Author:
Mark Bednarczyk [mark@slytechs.com], Sly Technologies Inc.
See Also:
  • Field Details

  • Method Details

    • activateLicense

      public static void activateLicense() throws com.slytechs.sdk.common.license.LicenseException
      Explicitly activates the SDK license using automatic key resolution.

      In most cases this method does not need to be called — the license activates automatically on the first NetPcap operation. Call this method only if you need to activate before any capture operations, or to force a specific key resolution.

      The key is resolved from the following sources in order:

      1. Environment variable JNETPCAP_LICENSE_KEY
      2. Environment variable JNETPCAP_LICENSE_DIRjnetpcap.lic
      3. System property jnetpcap.license.key
      4. System property jnetpcap.license.dirjnetpcap.lic
      5. Environment variable LICENSE_KEY
      6. Environment variable LICENSE_DIRjnetpcap.lic
      7. System property license.key
      8. System property license.dirjnetpcap.lic
      9. Container secrets: /run/secrets/jnetpcap.lic
      10. User home: ~/.jnetpcap/jnetpcap.lic
      11. System path: /etc/jnetpcap/jnetpcap.lic (Linux) or %PROGRAMFILES%\jnetpcap\jnetpcap.lic (Windows)
      12. Universal home: ~/.license/jnetpcap.lic
      13. Universal system: /etc/license/jnetpcap.lic
      14. Classpath: /license/jnetpcap.lic (embedded Community Edition key)

      If no commercial key is found the embedded Community Edition key is used, providing unlimited captures with telemetry enabled.

      Throws:
      com.slytechs.sdk.common.license.LicenseException - if no valid key is found or activation fails
      See Also:
    • activateLicense

      public static void activateLicense(String key) throws com.slytechs.sdk.common.license.LicenseException, IllegalArgumentException
      Explicitly activates the SDK license using the specified key.

      Use this method when the license key is obtained programmatically or stored in a location not covered by the automatic resolution order in activateLicense().

      Parameters:
      key - the license key string
      Throws:
      com.slytechs.sdk.common.license.LicenseException - if the key is invalid or activation fails
      IllegalArgumentException - if key is null or malformed
      See Also:
    • checkVersion

      public static void checkVersion(String applicationVersion) throws com.slytechs.sdk.jnetpcap.util.PcapVersionException
      Checks that the application version is compatible with this library version.
      Parameters:
      applicationVersion - the version string the application was built against
      Throws:
      com.slytechs.sdk.jnetpcap.util.PcapVersionException - if the versions are incompatible
    • create

      public static NetPcap create(com.slytechs.sdk.jnetpcap.PcapIf device) throws com.slytechs.sdk.jnetpcap.PcapException
      Creates a capture handle for the specified device using two-stage configuration.

      The handle is not yet active. Call configuration setters then activate() before dispatching packets. Uses default PacketSettings.

      try (NetPcap pcap = NetPcap.create(device)) {
          pcap.setSnaplen(65535)
              .setPromisc(true)
              .setTimeout(Duration.ofMillis(100))
              .activate();
      
          pcap.setFilter("tcp");
          pcap.loop(-1, handler);
      }
      
      Parameters:
      device - the network interface to capture on
      Returns:
      a new, unactivated NetPcap handle
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if handle creation fails
      See Also:
    • create

      public static NetPcap create(com.slytechs.sdk.jnetpcap.PcapIf device, com.slytechs.sdk.protocol.core.PacketSettings settings) throws com.slytechs.sdk.jnetpcap.PcapException
      Creates a capture handle for the specified device with custom packet settings.
      Parameters:
      device - the network interface to capture on
      settings - packet structure and dissection configuration
      Returns:
      a new, unactivated NetPcap handle
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if handle creation fails
      See Also:
    • create

      public static NetPcap create(String device) throws com.slytechs.sdk.jnetpcap.PcapException
      Creates a capture handle for the named device using two-stage configuration.

      Uses default PacketSettings.

      Parameters:
      device - the device name (e.g., "eth0", "en0")
      Returns:
      a new, unactivated NetPcap handle
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if handle creation fails
      See Also:
    • create

      public static NetPcap create(String device, com.slytechs.sdk.protocol.core.PacketSettings settings) throws com.slytechs.sdk.jnetpcap.PcapException
      Creates a capture handle for the named device with custom packet settings.
      Parameters:
      device - the device name (e.g., "eth0", "en0")
      settings - packet structure and dissection configuration
      Returns:
      a new, unactivated NetPcap handle
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if handle creation fails
      See Also:
    • findAllDevs

      public static List<com.slytechs.sdk.jnetpcap.PcapIf> findAllDevs() throws com.slytechs.sdk.jnetpcap.PcapException
      Returns all network interfaces available for capture on this system.

      Interfaces that the calling process cannot open (e.g., insufficient privileges) are silently omitted from the returned list. An empty list is a valid result and does not indicate an error.

      Each PcapIf provides:

      NetPcap.findAllDevs().stream()
          .filter(d -> d.isUp() && !d.isLoopback())
          .forEach(d -> System.out.println(d.name()));
      
      Returns:
      list of available network interfaces, possibly empty
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if the underlying pcap call fails
      Since:
      libpcap 0.7
    • findAllDevsEx

      public static List<com.slytechs.sdk.jnetpcap.PcapIf> findAllDevsEx(String source, com.slytechs.sdk.jnetpcap.constant.PcapSrc type, String username, String password) throws com.slytechs.sdk.jnetpcap.PcapException
      Returns network interfaces from a remote RPCAP source or directory of savefiles.

      Extends findAllDevs() with support for remote capture via the RPCAP protocol and for scanning a directory of pcap savefiles.

      Source format examples:

      • "rpcap://" — local interfaces (equivalent to findAllDevs())
      • "rpcap://host:2002" — interfaces on a remote RPCAP host
      • "file:///path/to/dir" — pcap savefiles in a directory
      Parameters:
      source - the source URI to scan for interfaces or savefiles
      type - authentication type for remote sources
      username - username for remote authentication (or null)
      password - password for remote authentication (or null)
      Returns:
      list of available interfaces or savefiles
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if the source cannot be reached or enumeration fails
      Since:
      libpcap 1.9 / WinPcap
    • main

      public static void main(String[] args) throws com.slytechs.sdk.jnetpcap.PcapException
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException
    • openDead

      public static NetPcap openDead(com.slytechs.sdk.jnetpcap.constant.PcapDlt linktype, int snaplen) throws com.slytechs.sdk.jnetpcap.PcapException
      Creates a "dead" handle for filter compilation or dump file writing.

      A dead handle is not bound to any live interface and cannot capture packets. It is used to compile BPF filters (via BaseNetPcap.compile(String, boolean)) or to write pcap dump files (via BaseNetPcap.dumpOpen(String)) without an active capture.

      Uses default PacketSettings.

      Parameters:
      linktype - the link-layer type for the dead handle
      snaplen - the snapshot length
      Returns:
      an activated dead NetPcap handle
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if handle creation fails
      See Also:
    • openDead

      public static NetPcap openDead(com.slytechs.sdk.jnetpcap.constant.PcapDlt linktype, int snaplen, com.slytechs.sdk.protocol.core.PacketSettings settings) throws com.slytechs.sdk.jnetpcap.PcapException
      Creates a "dead" handle with custom packet settings.
      Parameters:
      linktype - the link-layer type for the dead handle
      snaplen - the snapshot length
      settings - packet structure and dissection configuration
      Returns:
      an activated dead NetPcap handle
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if handle creation fails
    • openDeadWithTstampPrecision

      public static NetPcap openDeadWithTstampPrecision(com.slytechs.sdk.jnetpcap.constant.PcapDlt linktype, int snaplen, com.slytechs.sdk.jnetpcap.constant.PcapTStampPrecision precision) throws com.slytechs.sdk.jnetpcap.PcapException
      Creates a "dead" handle with specific timestamp precision.

      Uses default PacketSettings.

      Parameters:
      linktype - the link-layer type
      snaplen - the snapshot length
      precision - the timestamp precision
      Returns:
      an activated dead NetPcap handle
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if handle creation fails
    • openDeadWithTstampPrecision

      public static NetPcap openDeadWithTstampPrecision(com.slytechs.sdk.jnetpcap.constant.PcapDlt linktype, int snaplen, com.slytechs.sdk.jnetpcap.constant.PcapTStampPrecision precision, com.slytechs.sdk.protocol.core.PacketSettings settings) throws com.slytechs.sdk.jnetpcap.PcapException
      Creates a "dead" handle with specific timestamp precision and custom packet settings.
      Parameters:
      linktype - the link-layer type
      snaplen - the snapshot length
      precision - the timestamp precision
      settings - packet structure and dissection configuration
      Returns:
      an activated dead NetPcap handle
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if handle creation fails
    • openLive

      public static NetPcap openLive(com.slytechs.sdk.jnetpcap.PcapIf device, int snaplen, boolean promisc, long timeout, TimeUnit unit) throws com.slytechs.sdk.jnetpcap.PcapException
      Opens a network interface for live packet capture.

      The returned handle is already activated. Uses default PacketSettings.

      Parameters:
      device - the network interface to capture on
      snaplen - maximum bytes to capture per packet (use 65535 for full packets)
      promisc - true to enable promiscuous mode
      timeout - read timeout
      unit - timeout unit
      Returns:
      an activated NetPcap handle
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if the interface cannot be opened
      See Also:
    • openLive

      public static NetPcap openLive(com.slytechs.sdk.jnetpcap.PcapIf device, int snaplen, boolean promisc, long timeout, TimeUnit unit, com.slytechs.sdk.protocol.core.PacketSettings settings) throws com.slytechs.sdk.jnetpcap.PcapException
      Opens a network interface for live packet capture with custom packet settings.
      Parameters:
      device - the network interface to capture on
      snaplen - maximum bytes to capture per packet
      promisc - true to enable promiscuous mode
      timeout - read timeout
      unit - timeout unit
      settings - packet structure and dissection configuration
      Returns:
      an activated NetPcap handle
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if the interface cannot be opened
    • openLive

      public static NetPcap openLive(String device, int snaplen, boolean promisc, Duration timeout) throws com.slytechs.sdk.jnetpcap.PcapException
      Opens a network interface for live packet capture.

      Uses default PacketSettings.

      Parameters:
      device - the device name (e.g., "eth0", "en0")
      snaplen - maximum bytes to capture per packet
      promisc - true to enable promiscuous mode
      timeout - read timeout as Duration
      Returns:
      an activated NetPcap handle
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if the interface cannot be opened
    • openLive

      public static NetPcap openLive(String device, int snaplen, boolean promisc, Duration timeout, com.slytechs.sdk.protocol.core.PacketSettings settings) throws com.slytechs.sdk.jnetpcap.PcapException
      Opens a network interface for live packet capture with custom packet settings.
      Parameters:
      device - the device name
      snaplen - maximum bytes to capture per packet
      promisc - true to enable promiscuous mode
      timeout - read timeout as Duration
      settings - packet structure and dissection configuration
      Returns:
      an activated NetPcap handle
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if the interface cannot be opened
    • openLive

      public static NetPcap openLive(String device, int snaplen, boolean promisc, long timeout, TimeUnit unit) throws com.slytechs.sdk.jnetpcap.PcapException
      Opens a network interface for live packet capture.

      Uses default PacketSettings.

      Parameters:
      device - the device name
      snaplen - maximum bytes to capture per packet
      promisc - true to enable promiscuous mode
      timeout - read timeout value
      unit - timeout unit
      Returns:
      an activated NetPcap handle
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if the interface cannot be opened
    • openLive

      public static NetPcap openLive(String device, int snaplen, boolean promisc, long timeout, TimeUnit unit, com.slytechs.sdk.protocol.core.PacketSettings settings) throws com.slytechs.sdk.jnetpcap.PcapException
      Opens a network interface for live packet capture with custom packet settings.
      Parameters:
      device - the device name
      snaplen - maximum bytes to capture per packet
      promisc - true to enable promiscuous mode
      timeout - read timeout value
      unit - timeout unit
      settings - packet structure and dissection configuration
      Returns:
      an activated NetPcap handle
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if the interface cannot be opened
    • openOffline

      public static NetPcap openOffline(File file) throws com.slytechs.sdk.jnetpcap.PcapException
      Opens a pcap or pcapng capture file for reading.

      Uses default PacketSettings.

      Parameters:
      file - the capture file
      Returns:
      an activated NetPcap handle
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if the file cannot be opened or is not a valid capture file
      See Also:
    • openOffline

      public static NetPcap openOffline(File file, com.slytechs.sdk.protocol.core.PacketSettings settings) throws com.slytechs.sdk.jnetpcap.PcapException
      Opens a capture file for reading with custom packet settings.
      Parameters:
      file - the capture file
      settings - packet structure and dissection configuration
      Returns:
      an activated NetPcap handle
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if the file cannot be opened
    • openOffline

      public static NetPcap openOffline(String fname) throws com.slytechs.sdk.jnetpcap.PcapException
      Opens a pcap or pcapng capture file for reading.

      Uses default PacketSettings.

      try (NetPcap pcap = NetPcap.openOffline("capture.pcap")) {
          pcap.loop(-1, packet -> System.out.println(packet));
      }
      
      Parameters:
      fname - the path to the capture file
      Returns:
      an activated NetPcap handle
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if the file cannot be opened or is not a valid capture file
      See Also:
    • openOffline

      public static NetPcap openOffline(String fname, com.slytechs.sdk.protocol.core.PacketSettings settings) throws com.slytechs.sdk.jnetpcap.PcapException
      Opens a capture file for reading with custom packet settings.
      PacketSettings settings = new PacketSettings().dissect();
      
      try (NetPcap pcap = NetPcap.openOffline("capture.pcap", settings)) {
          Ip4 ip4 = new Ip4();
          pcap.loop(-1, packet -> {
              if (packet.hasHeader(ip4))
                  System.out.println(ip4.src() + " -> " + ip4.dst());
          });
      }
      
      Parameters:
      fname - the path to the capture file
      settings - packet structure and dissection configuration
      Returns:
      an activated NetPcap handle
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if the file cannot be opened
    • activate

      public void activate() throws com.slytechs.sdk.jnetpcap.PcapException
      Activates this capture handle.

      Must be called after create(PcapIf) and before any packet dispatch methods. Configuration setters (setSnaplen, setPromisc, etc.) must be called before activation. setFilter(BpFilter) must be called after activation.

      Overrides:
      activate in class BaseNetPcap
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if activation fails (e.g., insufficient privileges, device not found)
      See Also:
      • Pcap.activate()
    • dispatch

      public <U> int dispatch(int count, PacketHandler.OfPacket<U> handler, U user) throws com.slytechs.sdk.jnetpcap.PcapException
      Processes up to count packets, passing each to the handler with a user context object.

      Packets are dissected through the protocol pipeline before the handler is called. The handler receives a fully dissected Packet with protocol headers accessible via hasHeader().

      Returns after processing count packets, after a read timeout, or after BaseNetPcap.breakloop() is called. Unlike loop(int, PacketHandler.OfPacket, U), this method respects the read timeout configured via setTimeout(Duration).

      The Packet passed to the handler is only valid for the duration of the callback. Call Persistable.persist() to retain it beyond the callback.

      Type Parameters:
      U - the user context type
      Parameters:
      count - maximum packets to process; use -1 for unlimited
      handler - the packet handler
      user - user context passed to each handler invocation
      Returns:
      number of packets processed, 0 on timeout, -1 on error, -2 if BaseNetPcap.breakloop() was called
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if capture fails
      See Also:
    • dispatch

      public int dispatch(int count, PacketHandler.OfPacketConsumer handler) throws com.slytechs.sdk.jnetpcap.PcapException
      Processes up to count packets, passing each to a consumer-style handler.

      Equivalent to dispatch(int, OfPacket, Object) without a user context object. The handler is a standard Consumer of Packet.

      The Packet passed to the handler is only valid for the duration of the callback. Call Persistable.persist() to retain it beyond the callback.

      Parameters:
      count - maximum packets to process; use -1 for unlimited
      handler - the packet consumer
      Returns:
      number of packets processed, 0 on timeout, -1 on error, -2 if BaseNetPcap.breakloop() was called
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if capture fails
      See Also:
    • inject

      public int inject(com.slytechs.sdk.protocol.core.Packet packet) throws com.slytechs.sdk.jnetpcap.PcapException
      Injects a packet on the network, returning the number of bytes sent.

      Functionally equivalent to sendPacket(Packet) but returns the byte count rather than void. Prefer this method when the sent byte count needs to be verified.

      Parameters:
      packet - the packet to inject
      Returns:
      the number of bytes injected
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if injection fails
      See Also:
    • isActivated

      public boolean isActivated()
      Returns whether this handle has been activated.
      Returns:
      true if activate() has been called or the handle was created via openLive(PcapIf, int, boolean, long, TimeUnit), openOffline(File), or openDead(PcapDlt, int)
    • loop

      public <U> int loop(int count, PacketHandler.OfPacket<U> handler, U user)
      Processes packets in a loop with a user context object.

      Unlike dispatch(int, PacketHandler.OfPacket, U), this method ignores the read timeout and blocks until exactly count packets are processed or BaseNetPcap.breakloop() is called. Use count = -1 for infinite capture.

      The Packet passed to the handler is only valid for the duration of the callback. Call Persistable.persist() to retain it beyond the callback.

      Type Parameters:
      U - the user context type
      Parameters:
      count - packets to process; use -1 for infinite
      handler - the packet handler
      user - user context passed to each handler invocation
      Returns:
      number of packets processed, -1 on error, -2 if BaseNetPcap.breakloop() was called
      See Also:
    • loop

      public int loop(int count, PacketHandler.OfPacketConsumer handler)
      Processes packets in a loop with a consumer-style handler.

      Unlike dispatch(int, PacketHandler.OfPacket, U), this method ignores the read timeout and blocks until exactly count packets are processed or BaseNetPcap.breakloop() is called. Use count = -1 for infinite capture.

      The Packet passed to the handler is only valid for the duration of the callback. Call Persistable.persist() to retain it beyond the callback.

      Parameters:
      count - packets to process; use -1 for infinite
      handler - the packet consumer
      Returns:
      number of packets processed, -1 on error, -2 if BaseNetPcap.breakloop() was called
      See Also:
    • name

      public String name()
      Specified by:
      name in interface com.slytechs.sdk.common.util.Named
    • next

      public com.slytechs.sdk.protocol.core.Packet next() throws com.slytechs.sdk.jnetpcap.PcapException
      Returns the next available packet without blocking indefinitely.

      Returns null if no packet is available within the read timeout, or at end-of-file for offline captures. The returned packet is fully dissected with headers accessible via hasHeader().

      Lifetime warning: The returned Packet is only valid until the next call to next(), nextEx(), dispatch(), or loop(). Call Persistable.persist() if you need to retain it.

      Specified by:
      next in class BaseNetPcap
      Returns:
      the next dissected packet, or null on timeout or EOF
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if capture fails
      See Also:
    • nextEx

      public com.slytechs.sdk.protocol.core.Packet nextEx() throws com.slytechs.sdk.jnetpcap.PcapException, TimeoutException
      Returns the next available packet, distinguishing timeout from EOF.

      Unlike next(), this method throws TimeoutException on read timeout, allowing the caller to distinguish between timeout (no packet yet) and end-of-file (no more packets).

      Lifetime warning: The returned Packet is only valid until the next call to any dispatch method. Call Persistable.persist() if you need to retain it.

      Specified by:
      nextEx in class BaseNetPcap
      Returns:
      the next dissected packet
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if capture fails or EOF is reached on an offline capture
      TimeoutException - if the read timeout expires with no packet available
      See Also:
    • perror

      public NetPcap perror(String prefix)
      Prints error message to stderr.
      Overrides:
      perror in class BaseNetPcap
      Parameters:
      prefix - prefix for the error message
      Returns:
      this NetPcap for method chaining
      See Also:
      • Pcap.perror(String)
    • sendPacket

      public void sendPacket(com.slytechs.sdk.protocol.core.Packet packet) throws com.slytechs.sdk.jnetpcap.PcapException
      Transmits a packet on the network.

      The packet's raw bytes from position 0 to captureLength() are transmitted. Any header modifications made before calling this method are reflected in the transmitted data.

      Parameters:
      packet - the packet to transmit
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if transmission fails (e.g., insufficient privileges, network error)
      See Also:
    • setBufferSize

      public NetPcap setBufferSize(int bufferSize) throws com.slytechs.sdk.jnetpcap.PcapException
      Sets the kernel buffer size for the capture.
      Overrides:
      setBufferSize in class BaseNetPcap
      Parameters:
      bufferSize - the buffer size in bytes
      Returns:
      this NetPcap for method chaining
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if operation fails
      See Also:
      • Pcap.setBufferSize(int)
    • setBufferSize

      public NetPcap setBufferSize(long size, com.slytechs.sdk.common.memory.MemoryUnit unit) throws com.slytechs.sdk.jnetpcap.PcapException
      Sets the kernel capture buffer size.

      Must be called before activate().

      Parameters:
      size - the buffer size value
      unit - the size unit (e.g., MemoryUnit.MEGABYTES)
      Returns:
      this NetPcap for method chaining
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if the operation fails
    • setDatalink

      public NetPcap setDatalink(int dlt) throws com.slytechs.sdk.jnetpcap.PcapException
      Sets the data link type for the capture.
      Overrides:
      setDatalink in class BaseNetPcap
      Parameters:
      dlt - the data link type value
      Returns:
      this NetPcap for method chaining
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if operation fails
      See Also:
      • Pcap.setDatalink(int)
    • setDatalink

      public NetPcap setDatalink(Optional<com.slytechs.sdk.jnetpcap.constant.PcapDlt> dlt) throws com.slytechs.sdk.jnetpcap.PcapException
      Sets the data link type using an Optional.
      Overrides:
      setDatalink in class BaseNetPcap
      Parameters:
      dlt - the optional data link type
      Returns:
      this NetPcap for method chaining
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if operation fails
      See Also:
      • Pcap.setDatalink(Optional)
    • setDatalink

      public NetPcap setDatalink(com.slytechs.sdk.jnetpcap.constant.PcapDlt dlt) throws com.slytechs.sdk.jnetpcap.PcapException
      Sets the data link type.
      Overrides:
      setDatalink in class BaseNetPcap
      Parameters:
      dlt - the data link type
      Returns:
      this NetPcap for method chaining
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if operation fails
      See Also:
      • Pcap.setDatalink(PcapDlt)
    • setDirection

      public NetPcap setDirection(int dir) throws com.slytechs.sdk.jnetpcap.PcapException
      Sets the capture direction.
      Overrides:
      setDirection in class BaseNetPcap
      Parameters:
      dir - the direction value
      Returns:
      this NetPcap for method chaining
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if operation fails
      See Also:
      • Pcap.setDirection(int)
    • setDirection

      public NetPcap setDirection(Optional<com.slytechs.sdk.jnetpcap.constant.PcapDirection> dir) throws com.slytechs.sdk.jnetpcap.PcapException
      Sets the capture direction using an Optional.
      Overrides:
      setDirection in class BaseNetPcap
      Parameters:
      dir - the optional direction
      Returns:
      this NetPcap for method chaining
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if operation fails
      See Also:
      • Pcap.setDirection(Optional)
    • setDirection

      public NetPcap setDirection(com.slytechs.sdk.jnetpcap.constant.PcapDirection dir) throws com.slytechs.sdk.jnetpcap.PcapException
      Sets the capture direction.
      Overrides:
      setDirection in class BaseNetPcap
      Parameters:
      dir - the direction
      Returns:
      this NetPcap for method chaining
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if operation fails
      See Also:
      • Pcap.setDirection(PcapDirection)
    • setFilter

      public NetPcap setFilter(com.slytechs.sdk.jnetpcap.BpFilter bpfProgram) throws com.slytechs.sdk.jnetpcap.PcapException
      Sets the BPF filter program.
      Overrides:
      setFilter in class BaseNetPcap
      Parameters:
      bpfProgram - the compiled filter program
      Returns:
      this NetPcap for method chaining
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if operation fails
      See Also:
      • Pcap.setFilter(BpFilter)
    • setFilter

      public NetPcap setFilter(Optional<com.slytechs.sdk.jnetpcap.BpFilter> bpfProgram) throws com.slytechs.sdk.jnetpcap.PcapException
      Sets the BPF filter using an Optional.
      Overrides:
      setFilter in class BaseNetPcap
      Parameters:
      bpfProgram - the optional filter program
      Returns:
      this NetPcap for method chaining
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if operation fails
      See Also:
      • Pcap.setFilter(Optional)
    • setFilter

      public NetPcap setFilter(String expression) throws com.slytechs.sdk.jnetpcap.PcapException
      Compiles and applies a BPF filter expression.

      Must be called after activate(). The filter is compiled with optimization enabled. For optimization control use setFilter(String, boolean).

      pcap.setFilter("tcp port 80 or tcp port 443");
      pcap.setFilter("host 192.168.1.1 and not port 22");
      pcap.setFilter("tcp[tcpflags] & tcp-syn != 0");  // SYN packets only
      
      Parameters:
      expression - the BPF filter expression
      Returns:
      this NetPcap for method chaining
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if the expression is invalid or cannot be applied
      See Also:
    • setFilter

      public NetPcap setFilter(String expression, boolean optimize) throws com.slytechs.sdk.jnetpcap.PcapException
      Compiles and applies a BPF filter expression with optimization control.
      Parameters:
      expression - the BPF filter expression
      optimize - true to optimize the compiled filter
      Returns:
      this NetPcap for method chaining
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if the expression is invalid or cannot be applied
    • setImmediateMode

      public NetPcap setImmediateMode(boolean enable) throws com.slytechs.sdk.jnetpcap.PcapException
      Enables or disables immediate mode.

      Must be called before activate().

      Overrides:
      setImmediateMode in class BaseNetPcap
      Parameters:
      enable - true to enable immediate mode
      Returns:
      this NetPcap for method chaining
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if operation fails
      See Also:
      • Pcap.setImmediateMode(boolean)
    • setNonBlock

      public NetPcap setNonBlock(boolean nonBlock) throws com.slytechs.sdk.jnetpcap.PcapException
      Enables or disables non-blocking mode.
      Overrides:
      setNonBlock in class BaseNetPcap
      Parameters:
      nonBlock - true for non-blocking mode
      Returns:
      this NetPcap for method chaining
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if operation fails
      See Also:
      • Pcap.setNonBlock(boolean)
    • setPromisc

      public NetPcap setPromisc(boolean promiscuousMode) throws com.slytechs.sdk.jnetpcap.PcapException
      Enables or disables promiscuous mode.

      Must be called before activate().

      Overrides:
      setPromisc in class BaseNetPcap
      Parameters:
      promiscuousMode - true for promiscuous mode
      Returns:
      this NetPcap for method chaining
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if operation fails
      See Also:
      • Pcap.setPromisc(boolean)
    • setRfmon

      public NetPcap setRfmon(boolean rfMonitor) throws com.slytechs.sdk.jnetpcap.PcapException
      Enables or disables monitor mode (wireless).

      Must be called before activate(). Only supported on wireless interfaces.

      Overrides:
      setRfmon in class BaseNetPcap
      Parameters:
      rfMonitor - true to enable monitor mode
      Returns:
      this NetPcap for method chaining
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if operation fails
      See Also:
      • Pcap.setRfmon(boolean)
    • setSnaplen

      public NetPcap setSnaplen(int snaplen) throws com.slytechs.sdk.jnetpcap.PcapException
      Sets the snapshot length.

      Must be called before activate().

      Overrides:
      setSnaplen in class BaseNetPcap
      Parameters:
      snaplen - maximum bytes to capture per packet
      Returns:
      this NetPcap for method chaining
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if operation fails
      See Also:
      • Pcap.setSnaplen(int)
    • setTimeout

      public NetPcap setTimeout(Duration timeout) throws com.slytechs.sdk.jnetpcap.PcapException
      Sets the read timeout using a Duration.

      Must be called before activate().

      Parameters:
      timeout - the read timeout
      Returns:
      this NetPcap for method chaining
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if the operation fails
    • setTimeout

      public NetPcap setTimeout(int timeoutInMillis) throws com.slytechs.sdk.jnetpcap.PcapException
      Sets the read timeout in milliseconds.

      Must be called before activate().

      Overrides:
      setTimeout in class BaseNetPcap
      Parameters:
      timeoutInMillis - timeout in milliseconds
      Returns:
      this NetPcap for method chaining
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if operation fails
      See Also:
      • Pcap.setTimeout(int)
    • setTimeout

      public NetPcap setTimeout(long timeout, TimeUnit unit) throws com.slytechs.sdk.jnetpcap.PcapException
      Sets the read timeout with an explicit time unit.

      Must be called before activate().

      Parameters:
      timeout - the timeout value
      unit - the time unit
      Returns:
      this NetPcap for method chaining
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if the operation fails
    • setTstampPrecision

      public NetPcap setTstampPrecision(com.slytechs.sdk.jnetpcap.constant.PcapTStampPrecision precision) throws com.slytechs.sdk.jnetpcap.PcapException
      Sets the timestamp precision.

      Must be called before activate().

      Overrides:
      setTstampPrecision in class BaseNetPcap
      Parameters:
      precision - the timestamp precision
      Returns:
      this NetPcap for method chaining
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if operation fails
      See Also:
      • Pcap.setTstampPrecision(PcapTStampPrecision)
    • setTstampType

      public NetPcap setTstampType(com.slytechs.sdk.jnetpcap.constant.PcapTstampType type) throws com.slytechs.sdk.jnetpcap.PcapException
      Sets the timestamp type.

      Must be called before activate().

      Overrides:
      setTstampType in class BaseNetPcap
      Parameters:
      type - the timestamp type
      Returns:
      this NetPcap for method chaining
      Throws:
      com.slytechs.sdk.jnetpcap.PcapException - if operation fails
      See Also:
      • Pcap.setTstampType(PcapTstampType)
    • setUncaughtExceptionHandler

      public NetPcap setUncaughtExceptionHandler(Consumer<? super Throwable> exceptionHandler)
      Sets the uncaught exception handler using a Consumer.
      Overrides:
      setUncaughtExceptionHandler in class BaseNetPcap
      Parameters:
      exceptionHandler - the exception handler
      Returns:
      this NetPcap for method chaining
      See Also:
      • Pcap.setUncaughtExceptionHandler(Consumer)
    • setUncaughtExceptionHandler

      public NetPcap setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler exceptionHandler)
      Sets the uncaught exception handler.
      Overrides:
      setUncaughtExceptionHandler in class BaseNetPcap
      Parameters:
      exceptionHandler - the exception handler
      Returns:
      this NetPcap for method chaining
      See Also:
      • Pcap.setUncaughtExceptionHandler(UncaughtExceptionHandler)
    • toString

      public String toString()
      Returns a string representation of this handle including the device name and activation state.
      Overrides:
      toString in class Object
      Returns:
      e.g., "NetPcap[eth0, activated=true]"