Class NetPcap
- All Implemented Interfaces:
com.slytechs.sdk.common.util.Named, AutoCloseable
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
| Method | Use Case | Activated |
|---|---|---|
create(String) |
Two-stage live capture — configure then activate | No |
openLive(String, int, boolean, Duration) |
One-shot live capture | Yes |
openOffline(String) |
Read pcap/pcapng file | Yes |
openDead(PcapDlt, int) |
Filter compilation or dump file writing | Yes |
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 Summary
FieldsFields inherited from class BaseNetPcap
pcapApi -
Method Summary
Modifier and TypeMethodDescriptionvoidactivate()Activates this capture handle.static voidExplicitly activates the SDK license using automatic key resolution.static voidactivateLicense(String key) Explicitly activates the SDK license using the specified key.static voidcheckVersion(String applicationVersion) Checks that the application version is compatible with this library version.static NetPcapcreate(com.slytechs.sdk.jnetpcap.PcapIf device) Creates a capture handle for the specified device using two-stage configuration.static NetPcapcreate(com.slytechs.sdk.jnetpcap.PcapIf device, com.slytechs.sdk.protocol.core.PacketSettings settings) Creates a capture handle for the specified device with custom packet settings.static NetPcapCreates a capture handle for the named device using two-stage configuration.static NetPcapCreates a capture handle for the named device with custom packet settings.<U> intdispatch(int count, PacketHandler.OfPacket<U> handler, U user) Processes up tocountpackets, passing each to the handler with a user context object.intdispatch(int count, PacketHandler.OfPacketConsumer handler) Processes up tocountpackets, passing each to a consumer-style handler.static List<com.slytechs.sdk.jnetpcap.PcapIf> Returns all network interfaces available for capture on this system.static List<com.slytechs.sdk.jnetpcap.PcapIf> findAllDevsEx(String source, com.slytechs.sdk.jnetpcap.constant.PcapSrc type, String username, String password) Returns network interfaces from a remote RPCAP source or directory of savefiles.intinject(com.slytechs.sdk.protocol.core.Packet packet) Injects a packet on the network, returning the number of bytes sent.booleanReturns whether this handle has been activated.<U> intloop(int count, PacketHandler.OfPacket<U> handler, U user) Processes packets in a loop with a user context object.intloop(int count, PacketHandler.OfPacketConsumer handler) Processes packets in a loop with a consumer-style handler.static voidname()com.slytechs.sdk.protocol.core.Packetnext()Returns the next available packet without blocking indefinitely.com.slytechs.sdk.protocol.core.PacketnextEx()Returns the next available packet, distinguishing timeout from EOF.static NetPcapopenDead(com.slytechs.sdk.jnetpcap.constant.PcapDlt linktype, int snaplen) Creates a "dead" handle for filter compilation or dump file writing.static NetPcapopenDead(com.slytechs.sdk.jnetpcap.constant.PcapDlt linktype, int snaplen, com.slytechs.sdk.protocol.core.PacketSettings settings) Creates a "dead" handle with custom packet settings.static NetPcapopenDeadWithTstampPrecision(com.slytechs.sdk.jnetpcap.constant.PcapDlt linktype, int snaplen, com.slytechs.sdk.jnetpcap.constant.PcapTStampPrecision precision) Creates a "dead" handle with specific timestamp precision.static NetPcapopenDeadWithTstampPrecision(com.slytechs.sdk.jnetpcap.constant.PcapDlt linktype, int snaplen, com.slytechs.sdk.jnetpcap.constant.PcapTStampPrecision precision, com.slytechs.sdk.protocol.core.PacketSettings settings) Creates a "dead" handle with specific timestamp precision and custom packet settings.static NetPcapopenLive(com.slytechs.sdk.jnetpcap.PcapIf device, int snaplen, boolean promisc, long timeout, TimeUnit unit) Opens a network interface for live packet capture.static NetPcapopenLive(com.slytechs.sdk.jnetpcap.PcapIf device, int snaplen, boolean promisc, long timeout, TimeUnit unit, com.slytechs.sdk.protocol.core.PacketSettings settings) Opens a network interface for live packet capture with custom packet settings.static NetPcapOpens a network interface for live packet capture.static NetPcapopenLive(String device, int snaplen, boolean promisc, long timeout, TimeUnit unit, com.slytechs.sdk.protocol.core.PacketSettings settings) Opens a network interface for live packet capture with custom packet settings.static NetPcapOpens a network interface for live packet capture.static NetPcapopenLive(String device, int snaplen, boolean promisc, Duration timeout, com.slytechs.sdk.protocol.core.PacketSettings settings) Opens a network interface for live packet capture with custom packet settings.static NetPcapopenOffline(File file) Opens a pcap or pcapng capture file for reading.static NetPcapopenOffline(File file, com.slytechs.sdk.protocol.core.PacketSettings settings) Opens a capture file for reading with custom packet settings.static NetPcapopenOffline(String fname) Opens a pcap or pcapng capture file for reading.static NetPcapopenOffline(String fname, com.slytechs.sdk.protocol.core.PacketSettings settings) Opens a capture file for reading with custom packet settings.Prints error message to stderr.voidsendPacket(com.slytechs.sdk.protocol.core.Packet packet) Transmits a packet on the network.setBufferSize(int bufferSize) Sets the kernel buffer size for the capture.setBufferSize(long size, com.slytechs.sdk.common.memory.MemoryUnit unit) Sets the kernel capture buffer size.setDatalink(int dlt) Sets the data link type for the capture.setDatalink(com.slytechs.sdk.jnetpcap.constant.PcapDlt dlt) Sets the data link type.setDatalink(Optional<com.slytechs.sdk.jnetpcap.constant.PcapDlt> dlt) Sets the data link type using an Optional.setDirection(int dir) Sets the capture direction.setDirection(com.slytechs.sdk.jnetpcap.constant.PcapDirection dir) Sets the capture direction.setDirection(Optional<com.slytechs.sdk.jnetpcap.constant.PcapDirection> dir) Sets the capture direction using an Optional.setFilter(com.slytechs.sdk.jnetpcap.BpFilter bpfProgram) Sets the BPF filter program.Compiles and applies a BPF filter expression.Compiles and applies a BPF filter expression with optimization control.Sets the BPF filter using an Optional.setImmediateMode(boolean enable) Enables or disables immediate mode.setNonBlock(boolean nonBlock) Enables or disables non-blocking mode.setPromisc(boolean promiscuousMode) Enables or disables promiscuous mode.setRfmon(boolean rfMonitor) Enables or disables monitor mode (wireless).setSnaplen(int snaplen) Sets the snapshot length.setTimeout(int timeoutInMillis) Sets the read timeout in milliseconds.setTimeout(long timeout, TimeUnit unit) Sets the read timeout with an explicit time unit.setTimeout(Duration timeout) Sets the read timeout using aDuration.setTstampPrecision(com.slytechs.sdk.jnetpcap.constant.PcapTStampPrecision precision) Sets the timestamp precision.setTstampType(com.slytechs.sdk.jnetpcap.constant.PcapTstampType type) Sets the timestamp type.setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler exceptionHandler) Sets the uncaught exception handler.setUncaughtExceptionHandler(Consumer<? super Throwable> exceptionHandler) Sets the uncaught exception handler using a Consumer.toString()Returns a string representation of this handle including the device name and activation state.Methods inherited from class BaseNetPcap
breakloop, canSetRfmon, close, compile, compile, datalink, dataLinkExt, dispatch, dispatch, dispatch, dispatch, dumpOpen, geterr, getName, getNonBlock, getPcapHeaderABI, getTstampPrecision, inject, inject, inject, inject, isSwapped, listDataLinks, listTstampTypes, loop, loop, loop, loop, majorVersion, minorVersion, order, sendPacket, sendPacket, sendPacket, sendPacket, snapshot, statsMethods inherited from class Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, waitMethods inherited from interface AutoCloseable
closeMethods inherited from interface com.slytechs.sdk.common.util.Named
defaultName, setName
-
Field Details
-
VERSION
-
-
Method Details
-
activateLicense
public static void activateLicense() throws com.slytechs.sdk.common.license.LicenseExceptionExplicitly 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
NetPcapoperation. 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:
- Environment variable
JNETPCAP_LICENSE_KEY - Environment variable
JNETPCAP_LICENSE_DIR→jnetpcap.lic - System property
jnetpcap.license.key - System property
jnetpcap.license.dir→jnetpcap.lic - Environment variable
LICENSE_KEY - Environment variable
LICENSE_DIR→jnetpcap.lic - System property
license.key - System property
license.dir→jnetpcap.lic - Container secrets:
/run/secrets/jnetpcap.lic - User home:
~/.jnetpcap/jnetpcap.lic - System path:
/etc/jnetpcap/jnetpcap.lic(Linux) or%PROGRAMFILES%\jnetpcap\jnetpcap.lic(Windows) - Universal home:
~/.license/jnetpcap.lic - Universal system:
/etc/license/jnetpcap.lic - 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:
- Environment variable
-
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 failsIllegalArgumentException- 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 defaultPacketSettings.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
NetPcaphandle - 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 onsettings- packet structure and dissection configuration- Returns:
- a new, unactivated
NetPcaphandle - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if handle creation fails- See Also:
-
create
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
NetPcaphandle - 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
NetPcaphandle - 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.PcapExceptionReturns 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
PcapIfprovides:name()— interface name to pass tocreate(PcapIf)oropenLive(PcapIf, int, boolean, long, TimeUnit)description()— human-readable description (optional)addresses()— list of network addresses (IPv4, IPv6, or other)isLoopback(),isUp(),isRunning(),isWireless()— interface flags
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 tofindAllDevs())"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 savefilestype- authentication type for remote sourcesusername- 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
- 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 (viaBaseNetPcap.dumpOpen(String)) without an active capture.Uses default
PacketSettings.- Parameters:
linktype- the link-layer type for the dead handlesnaplen- the snapshot length- Returns:
- an activated dead
NetPcaphandle - 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 handlesnaplen- the snapshot lengthsettings- packet structure and dissection configuration- Returns:
- an activated dead
NetPcaphandle - 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 typesnaplen- the snapshot lengthprecision- the timestamp precision- Returns:
- an activated dead
NetPcaphandle - 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 typesnaplen- the snapshot lengthprecision- the timestamp precisionsettings- packet structure and dissection configuration- Returns:
- an activated dead
NetPcaphandle - 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 onsnaplen- maximum bytes to capture per packet (use 65535 for full packets)promisc-trueto enable promiscuous modetimeout- read timeoutunit- timeout unit- Returns:
- an activated
NetPcaphandle - 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 onsnaplen- maximum bytes to capture per packetpromisc-trueto enable promiscuous modetimeout- read timeoutunit- timeout unitsettings- packet structure and dissection configuration- Returns:
- an activated
NetPcaphandle - 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 packetpromisc-trueto enable promiscuous modetimeout- read timeout asDuration- Returns:
- an activated
NetPcaphandle - 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 namesnaplen- maximum bytes to capture per packetpromisc-trueto enable promiscuous modetimeout- read timeout asDurationsettings- packet structure and dissection configuration- Returns:
- an activated
NetPcaphandle - 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 namesnaplen- maximum bytes to capture per packetpromisc-trueto enable promiscuous modetimeout- read timeout valueunit- timeout unit- Returns:
- an activated
NetPcaphandle - 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 namesnaplen- maximum bytes to capture per packetpromisc-trueto enable promiscuous modetimeout- read timeout valueunit- timeout unitsettings- packet structure and dissection configuration- Returns:
- an activated
NetPcaphandle - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if the interface cannot be opened
-
openOffline
Opens a pcap or pcapng capture file for reading.Uses default
PacketSettings.- Parameters:
file- the capture file- Returns:
- an activated
NetPcaphandle - 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 filesettings- packet structure and dissection configuration- Returns:
- an activated
NetPcaphandle - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if the file cannot be opened
-
openOffline
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
NetPcaphandle - 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 filesettings- packet structure and dissection configuration- Returns:
- an activated
NetPcaphandle - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if the file cannot be opened
-
activate
public void activate() throws com.slytechs.sdk.jnetpcap.PcapExceptionActivates 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:
activatein classBaseNetPcap- Throws:
com.slytechs.sdk.jnetpcap.PcapException- if activation fails (e.g., insufficient privileges, device not found)- See Also:
-
dispatch
public <U> int dispatch(int count, PacketHandler.OfPacket<U> handler, U user) throws com.slytechs.sdk.jnetpcap.PcapException Processes up tocountpackets, 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
Packetwith protocol headers accessible viahasHeader().Returns after processing
countpackets, after a read timeout, or afterBaseNetPcap.breakloop()is called. Unlikeloop(int, PacketHandler.OfPacket, U), this method respects the read timeout configured viasetTimeout(Duration).The
Packetpassed to the handler is only valid for the duration of the callback. CallPersistable.persist()to retain it beyond the callback.- Type Parameters:
U- the user context type- Parameters:
count- maximum packets to process; use-1for unlimitedhandler- the packet handleruser- user context passed to each handler invocation- Returns:
- number of packets processed,
0on timeout,-1on error,-2ifBaseNetPcap.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 tocountpackets, passing each to a consumer-style handler.Equivalent to
dispatch(int, OfPacket, Object)without a user context object. The handler is a standardConsumerofPacket.The
Packetpassed to the handler is only valid for the duration of the callback. CallPersistable.persist()to retain it beyond the callback.- Parameters:
count- maximum packets to process; use-1for unlimitedhandler- the packet consumer- Returns:
- number of packets processed,
0on timeout,-1on error,-2ifBaseNetPcap.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:
trueifactivate()has been called or the handle was created viaopenLive(PcapIf, int, boolean, long, TimeUnit),openOffline(File), oropenDead(PcapDlt, int)
-
loop
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 exactlycountpackets are processed orBaseNetPcap.breakloop()is called. Usecount = -1for infinite capture.The
Packetpassed to the handler is only valid for the duration of the callback. CallPersistable.persist()to retain it beyond the callback.- Type Parameters:
U- the user context type- Parameters:
count- packets to process; use-1for infinitehandler- the packet handleruser- user context passed to each handler invocation- Returns:
- number of packets processed,
-1on error,-2ifBaseNetPcap.breakloop()was called - See Also:
-
loop
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 exactlycountpackets are processed orBaseNetPcap.breakloop()is called. Usecount = -1for infinite capture.The
Packetpassed to the handler is only valid for the duration of the callback. CallPersistable.persist()to retain it beyond the callback.- Parameters:
count- packets to process; use-1for infinitehandler- the packet consumer- Returns:
- number of packets processed,
-1on error,-2ifBaseNetPcap.breakloop()was called - See Also:
-
name
- Specified by:
namein interfacecom.slytechs.sdk.common.util.Named
-
next
public com.slytechs.sdk.protocol.core.Packet next() throws com.slytechs.sdk.jnetpcap.PcapExceptionReturns the next available packet without blocking indefinitely.Returns
nullif 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 viahasHeader().Lifetime warning: The returned
Packetis only valid until the next call tonext(),nextEx(),dispatch(), orloop(). CallPersistable.persist()if you need to retain it.- Specified by:
nextin classBaseNetPcap- Returns:
- the next dissected packet, or
nullon 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, TimeoutExceptionReturns the next available packet, distinguishing timeout from EOF.Unlike
next(), this method throwsTimeoutExceptionon read timeout, allowing the caller to distinguish between timeout (no packet yet) and end-of-file (no more packets).Lifetime warning: The returned
Packetis only valid until the next call to any dispatch method. CallPersistable.persist()if you need to retain it.- Specified by:
nextExin classBaseNetPcap- Returns:
- the next dissected packet
- Throws:
com.slytechs.sdk.jnetpcap.PcapException- if capture fails or EOF is reached on an offline captureTimeoutException- if the read timeout expires with no packet available- See Also:
-
perror
Prints error message to stderr.- Overrides:
perrorin classBaseNetPcap- Parameters:
prefix- prefix for the error message- Returns:
- this
NetPcapfor method chaining - See Also:
-
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
0tocaptureLength()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
Sets the kernel buffer size for the capture.- Overrides:
setBufferSizein classBaseNetPcap- Parameters:
bufferSize- the buffer size in bytes- Returns:
- this
NetPcapfor method chaining - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if operation fails- See Also:
-
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 valueunit- the size unit (e.g.,MemoryUnit.MEGABYTES)- Returns:
- this
NetPcapfor method chaining - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if the operation fails
-
setDatalink
Sets the data link type for the capture.- Overrides:
setDatalinkin classBaseNetPcap- Parameters:
dlt- the data link type value- Returns:
- this
NetPcapfor method chaining - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if operation fails- See Also:
-
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:
setDatalinkin classBaseNetPcap- Parameters:
dlt- the optional data link type- Returns:
- this
NetPcapfor method chaining - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if operation fails- See Also:
-
setDatalink
public NetPcap setDatalink(com.slytechs.sdk.jnetpcap.constant.PcapDlt dlt) throws com.slytechs.sdk.jnetpcap.PcapException Sets the data link type.- Overrides:
setDatalinkin classBaseNetPcap- Parameters:
dlt- the data link type- Returns:
- this
NetPcapfor method chaining - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if operation fails- See Also:
-
setDirection
Sets the capture direction.- Overrides:
setDirectionin classBaseNetPcap- Parameters:
dir- the direction value- Returns:
- this
NetPcapfor method chaining - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if operation fails- See Also:
-
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:
setDirectionin classBaseNetPcap- Parameters:
dir- the optional direction- Returns:
- this
NetPcapfor method chaining - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if operation fails- See Also:
-
setDirection
public NetPcap setDirection(com.slytechs.sdk.jnetpcap.constant.PcapDirection dir) throws com.slytechs.sdk.jnetpcap.PcapException Sets the capture direction.- Overrides:
setDirectionin classBaseNetPcap- Parameters:
dir- the direction- Returns:
- this
NetPcapfor method chaining - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if operation fails- See Also:
-
setFilter
public NetPcap setFilter(com.slytechs.sdk.jnetpcap.BpFilter bpfProgram) throws com.slytechs.sdk.jnetpcap.PcapException Sets the BPF filter program.- Overrides:
setFilterin classBaseNetPcap- Parameters:
bpfProgram- the compiled filter program- Returns:
- this
NetPcapfor method chaining - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if operation fails- See Also:
-
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:
setFilterin classBaseNetPcap- Parameters:
bpfProgram- the optional filter program- Returns:
- this
NetPcapfor method chaining - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if operation fails- See Also:
-
setFilter
Compiles and applies a BPF filter expression.Must be called after
activate(). The filter is compiled with optimization enabled. For optimization control usesetFilter(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
NetPcapfor 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 expressionoptimize-trueto optimize the compiled filter- Returns:
- this
NetPcapfor method chaining - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if the expression is invalid or cannot be applied
-
setImmediateMode
Enables or disables immediate mode.Must be called before
activate().- Overrides:
setImmediateModein classBaseNetPcap- Parameters:
enable- true to enable immediate mode- Returns:
- this
NetPcapfor method chaining - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if operation fails- See Also:
-
setNonBlock
Enables or disables non-blocking mode.- Overrides:
setNonBlockin classBaseNetPcap- Parameters:
nonBlock- true for non-blocking mode- Returns:
- this
NetPcapfor method chaining - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if operation fails- See Also:
-
setPromisc
Enables or disables promiscuous mode.Must be called before
activate().- Overrides:
setPromiscin classBaseNetPcap- Parameters:
promiscuousMode- true for promiscuous mode- Returns:
- this
NetPcapfor method chaining - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if operation fails- See Also:
-
setRfmon
Enables or disables monitor mode (wireless).Must be called before
activate(). Only supported on wireless interfaces.- Overrides:
setRfmonin classBaseNetPcap- Parameters:
rfMonitor- true to enable monitor mode- Returns:
- this
NetPcapfor method chaining - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if operation fails- See Also:
-
setSnaplen
Sets the snapshot length.Must be called before
activate().- Overrides:
setSnaplenin classBaseNetPcap- Parameters:
snaplen- maximum bytes to capture per packet- Returns:
- this
NetPcapfor method chaining - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if operation fails- See Also:
-
setTimeout
Sets the read timeout using aDuration.Must be called before
activate().- Parameters:
timeout- the read timeout- Returns:
- this
NetPcapfor method chaining - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if the operation fails
-
setTimeout
Sets the read timeout in milliseconds.Must be called before
activate().- Overrides:
setTimeoutin classBaseNetPcap- Parameters:
timeoutInMillis- timeout in milliseconds- Returns:
- this
NetPcapfor method chaining - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if operation fails- See Also:
-
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 valueunit- the time unit- Returns:
- this
NetPcapfor 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:
setTstampPrecisionin classBaseNetPcap- Parameters:
precision- the timestamp precision- Returns:
- this
NetPcapfor method chaining - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if operation fails- See Also:
-
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:
setTstampTypein classBaseNetPcap- Parameters:
type- the timestamp type- Returns:
- this
NetPcapfor method chaining - Throws:
com.slytechs.sdk.jnetpcap.PcapException- if operation fails- See Also:
-
setUncaughtExceptionHandler
Sets the uncaught exception handler using a Consumer.- Overrides:
setUncaughtExceptionHandlerin classBaseNetPcap- Parameters:
exceptionHandler- the exception handler- Returns:
- this
NetPcapfor method chaining - See Also:
-
setUncaughtExceptionHandler
Sets the uncaught exception handler.- Overrides:
setUncaughtExceptionHandlerin classBaseNetPcap- Parameters:
exceptionHandler- the exception handler- Returns:
- this
NetPcapfor method chaining - See Also:
-
toString
-