Module org.jnetpcap
Package org.jnetpcap

Class Pcap

java.lang.Object
org.jnetpcap.Pcap
All Implemented Interfaces:
AutoCloseable
Direct Known Subclasses:
Pcap0_4

public abstract sealed class Pcap extends Object implements AutoCloseable permits Pcap0_4
Pcap relies on preview features of the Java platform:
Programs can only use Pcap when preview features are enabled.
Preview features may be removed in a future release, or upgraded to permanent features of the Java platform.
Entry point and base class for all Pcap API methods provided by jNetPcap library.
Author:
Sly Technologies, repos@slytechs.com
  • Field Details

  • Method Details

    • checkPcapVersion

      public static void checkPcapVersion(String applicationVersion) throws PcapVersionException
      Checks runtime version against application version of the java jNetPcap APIs.

      For example Pcap.checkPcapVersion(Pcap.VERSION) when compiled, the Pcap.VERSION will be stored in the application full as a constant and then compared to the runtime Pcap.VERSION, also a constant. Both runtime and application constants will be different as they are compiled at different times and against, possibly, different versions of the pcap libarary.

      This does not perform version checks against the native libpcap library versions. Only the java jNetPcap API versions.

      To check for compatibility with specific native library versions, you can either use libVersion() and do a compare, or try specific PcapX_Y.isSupported() calls to get a boolean weather a particular subclass is supported. Support in version specific classes is done by checking if a very specific to the version, native library symbol is found. A missing symbol indicates that the native library is of lower version, which does not have the symbol defined yet.

      Parameters:
      applicationVersion - the application version
      Throws:
      PcapVersionException - the incompatible pcap runtime exception
    • compileNoPcap

      @Deprecated(since="libpcap 1.11.0 API, jNetPcap 2.1.0") public static BpFilter compileNoPcap(int snaplen, PcapDlt pcapDlt, String str, boolean optimize, int netmask) throws PcapException
      Deprecated.
      Compile a filter expression against a dead handle opened using openDead.

      pcap_compile() is used to compile the string str into a filter program. See pcap-filter(7) for the syntax of that string. fp is a pointer to a bpf_program struct and is filled in by pcap_compile(). optimize controls whether optimization on the resulting full is performed. netmask specifies the IPv4 netmask of the network on which packets are being captured; it is used only when checking for IPv4 broadcast addresses in the filter program. If the netmask of the network on which packets are being captured isn't known to the program, or if packets are being captured on the Linux "any" pseudo-interface that can capture on more than one network, a value of PCAP_NETMASK_UNKNOWN can be supplied; tests for IPv4 broadcast addresses will fail to compile, but all other tests in the filter program will be OK.

      NOTE: in libpcap 1.8.0 and later, pcap_compile() can be used in multiple threads within a single process. However, in earlier versions of libpcap, it is not safe to use pcap_compile() in multiple threads in a single process without some form of mutual exclusion allowing only one thread to call it at any given time.

      Parameters:
      snaplen - the snaplen
      pcapDlt - the dlt
      str - filter expression to be compiled
      optimize - controls whether optimization on the resulting full is performed
      netmask - specifies the IPv4 netmask of the network on which packets are being captured; it is used only when checking for IPv4 broadcast addresses in the filter program. If the netmask of the network on which packets are being captured isn't known to the program, or if packets are being captured on the Linux "any" pseudo-interface that can capture on more than one network, a value of PCAP_NETMASK_UNKNOWN can be supplied; tests for IPv4 broadcast addresses will fail to compile, but all other tests in the filter program will be OK
      Returns:
      the compiled filter
      Throws:
      PcapException - any errors
    • create

      public static Pcap create(PcapIf device) throws PcapException
      Create a live capture handle. create is used to create a packet capture handle to look at packets on the network. source is a string that specifies the network device to open; on Linux systems with 2.2 or later kernels, a source argument of "any" or NULL can be used to capture packets from all interfaces. The returned handle must be activated with pcap_activate() before pack' ets can be captured with it; options for the capture, such as promiscu' ous mode, can be set on the handle before activating it.
      Parameters:
      device - pcap network interface that specifies the network device to open.
      Returns:
      a new pcap object that needs to be activated using activate() call
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 1.0
    • create

      public static Pcap create(String device) throws PcapException
      Create a live capture handle. create is used to create a packet capture handle to look at packets on the network. source is a string that specifies the network device to open; on Linux systems with 2.2 or later kernels, a source argument of "any" or NULL can be used to capture packets from all interfaces. The returned handle must be activated with pcap_activate() before pack' ets can be captured with it; options for the capture, such as promiscu' ous mode, can be set on the handle before activating it.
      Parameters:
      device - a string that specifies the network device to open; on Linux systems with 2.2 or later kernels, a source argument of "any" or NULL can be used to capture packets from all interfaces.
      Returns:
      a new pcap object that needs to be activated using activate() call
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 1.0
    • datalinkNameToVal

      public static PcapDlt datalinkNameToVal(String name)
      Translates a link-layer header type name, which is a DLT_ name with the DLT_ removed, to the corresponding link-layer header type value. The translation is case-insensitive.
      Parameters:
      name - link-layer header type name
      Returns:
      the pcap data link type
      Since:
      libpcap 0.8
    • datalinkValToDescription

      public static String datalinkValToDescription(PcapDlt pcapDlt)
      link-layer header type. NULL is returned if the type value does not correspond to a known DLT_ value..
      Parameters:
      pcapDlt - link-layer header type
      Returns:
      short description of that link-layer header type
      Since:
      libpcap 0.8
    • datalinkValToName

      public static String datalinkValToName(PcapDlt pcapDlt)
      Translates a link-layer header type value to the corresponding link-layer header type name, which is the DLT_ name for the link-layer header type value with the DLT_ removed. NULL is returned if the type value does not correspond to a known DLT_ value..
      Parameters:
      pcapDlt - link-layer header type
      Returns:
      corresponding link-layer header type name
      Since:
      libpcap 0.8
    • findAllDevs

      public static List<PcapIf> findAllDevs() throws PcapException
      Constructs a list of network devices that can be opened with pcap_create(3PCAP) and pcap_activate(3PCAP) or with pcap_open_live(3PCAP). (Note that there may be network devices that cannot be opened by the process calling pcap_findalldevs(), because, for example, that process does not have sufficient privileges to open them for capturing; if so, those devices will not appear on the list.) If pcap_findalldevs() succeeds, the pointer pointed to by alldevsp is set to point to the first element of the list, or to NULL if no devices were found (this is considered success).

      Each element of the list is of type pcap_if_t, and has the following members:

      next
      if not NULL, a pointer to the next element in the list; NULL for the last element of the list
      name
      a pointer to a string giving a name for the device to pass to pcap_open_live()
      description
      if not NULL, a pointer to a string giving a human-readable description of the device
      addresses
      a pointer to the first element of a list of network addresses for the device, or NULL if the device has no addresses
      flags
      device flags:
      PCAP_IF_LOOPBACK
      set if the device is a loopback interface
      PCAP_IF_UP
      set if the device is up
      PCAP_IF_RUNNING
      set if the device is running
      PCAP_IF_WIRELESS
      set if the device is a wireless interface; this includes IrDA as well as radio-based networks such as IEEE 802.15.4 and IEEE 802.11, so it doesn't just mean Wi-Fi
      PCAP_IF_CONNECTION_STATUS
      a bitmask for an indication of whether the adapter is connected or not; for wireless interfaces, "connected" means "associated with a network"
      PCAP_IF_CONNECTION_STATUS_UNKNOWN
      it's unknown whether the adapter is connected or not
      PCAP_IF_CONNECTION_STATUS_CONNECTED
      the adapter is connected
      PCAP_IF_CONNECTION_STATUS_DISCONNECTED
      the adapter is disconnected
      PCAP_IF_CONNECTION_STATUS_NOT_APPLICABLE
      the notion of "connected" and "disconnected" don't apply to this interface; for example, it doesn't apply to a loopback device

      Each element of the list of addresses is of type pcap_addr_t, and has the following members:

      next
      if not NULL, a pointer to the next element in the list; NULL for the last element of the list
      addr
      a pointer to a struct sockaddr containing an address
      netmask
      if not NULL, a pointer to a struct sockaddr that contains the netmask corresponding to the address pointed to by addr
      broadaddr
      if not NULL, a pointer to a struct sockaddr that contains the broadcast address corresponding to the address pointed to by addr; may be null if the device doesn't support broadcasts
      dstaddr
      if not NULL, a pointer to a struct sockaddr that contains the destination address corresponding to the address pointed to by addr; may be null if the device isn't a point-to-point interface

      Note that the addresses in the list of addresses might be IPv4 addresses, IPv6 addresses, or some other type of addresses, so you must check the sa_family member of the struct sockaddr before interpreting the contents of the address; do not assume that the addresses are all IPv4 addresses, or even all IPv4 or IPv6 addresses. IPv4 addresses have the value AF_INET, IPv6 addresses have the value AF_INET6 (which older operating systems that don't support IPv6 might not define), and other addresses have other values. Whether other addresses are returned, and what types they might have is platform-dependent. For IPv4 addresses, the struct sockaddr pointer can be interpreted as if it pointed to a struct sockaddr_in; for IPv6 addresses, it can be interpreted as if it pointed to a struct sockaddr_in6.

      For example

      	List<PcapIf> list = Pcap.findAllDevs()
      
      Returns:
      list of network devices
      Throws:
      PcapException - any pcap errors
      Since:
      libpcap 0.7
    • findAllDevsEx

      public static List<PcapIf> findAllDevsEx(String source, PcapSrc type, String username, String password) throws PcapException
      Create a list of network devices that can be opened with Pcap#open.

      This routine can scan a directory for savefiles, list local capture devices, or list capture devices on a remote machine running an RPCAP server.

      For scanning for savefiles, it can be used on both UN*X systems and Windows systems; for each directory entry it sees, it tries to open the file as a savefile using pcap_open_offline(), and only includes it in the list of files if the open succeeds, so it filters out files for which the user doesn't have read permission, as well as files that aren't valid savefiles readable by libpcap.

      For listing local capture devices, it's just a wrapper around pcap_findalldevs(); full using pcap_findalldevs() will work on more platforms than full using pcap_findalldevs_ex().

      For listing remote capture devices, pcap_findalldevs_ex() is currently the only API available.

      Warning:

      There may be network devices that cannot be opened with pcap_open() by the process calling pcap_findalldevs(), because, for example, that process might not have sufficient privileges to open them for capturing; if so, those devices will not appear on the list.
      Parameters:
      source - This source will be examined looking for adapters (local or remote) (e.g. source can be 'rpcap://' for local adapters or 'rpcap://host:port' for adapters on a remote host) or pcap files (e.g. source can be 'file://c:/myfolder/').
      type - Type of the authentication required
      username - The username that has to be used on the remote machine for authentication
      password - The password that has to be used on the remote machine for authentication
      Returns:
      The list of the devices
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 1.9, early days of WinPcap
    • init

      public static void init(int opts) throws PcapException
      Initialize the native libpcap library.

      Used to initialize the Packet Capture library. opts specifies options for the library; currently, the options are:

      PcapConstants.PCAP_CHAR_ENC_LOCAL
      Treat all strings supplied as arguments, and return all strings to the caller, as being in the local character encoding.
      PcapConstants.PCAP_CHAR_ENC_UTF_8
      Treat all strings supplied as arguments, and return all strings to the caller, as being in UTF-8.

      On UNIX-like systems, the local character encoding is assumed to be UTF-8, so no character encoding transformations are done.

      On Windows, the local character encoding is the local ANSI full page.

      If init(int) is not called, strings are treated as being in the local ANSI full page on Windows, lookupDev() will succeed if there is a device on which to capture, and create(String) makes an attempt to check whether the string passed as an argument is a UTF-16LE string - note that this attempt is unsafe, as it may run past the end of the string - to handle pcap_lookupdev() returning a UTF-16LE string. Programs that don't call init(int) should, on Windows, call native pcap_wsockinit() to initialize Winsock; this is not necessary if init(int) is called, as init(int) will initialize Winsock itself on Windows.

      Parameters:
      opts - the opts
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 1.9
    • init

      public static void init(PcapOption option) throws PcapException
      Initialize the native libpcap library.

      Used to initialize the Packet Capture library. opts specifies options for the library; currently, the options are:

      PcapConstants.PCAP_CHAR_ENC_LOCAL
      Treat all strings supplied as arguments, and return all strings to the caller, as being in the local character encoding.
      PcapConstants.PCAP_CHAR_ENC_UTF_8
      Treat all strings supplied as arguments, and return all strings to the caller, as being in UTF-8.

      On UNIX-like systems, the local character encoding is assumed to be UTF-8, so no character encoding transformations are done.

      On Windows, the local character encoding is the local ANSI full page.

      If init(int) is not called, strings are treated as being in the local ANSI full page on Windows, lookupDev() will succeed if there is a device on which to capture, and create(String) makes an attempt to check whether the string passed as an argument is a UTF-16LE string - note that this attempt is unsafe, as it may run past the end of the string - to handle pcap_lookupdev() returning a UTF-16LE string. Programs that don't call init(int) should, on Windows, call native pcap_wsockinit() to initialize Winsock; this is not necessary if init(int) is called, as init(int) will initialize Winsock itself on Windows.

      Parameters:
      option - a pcap init option
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 1.9
    • isSupported

      public static boolean isSupported()
      Checks if the Pcap subclass at a specific libpcap API version is natively supported. This is a safe method to use anytime on any platform, weather native library is present or not.

      For example, Pcap1_0.isSupported() will accurately ascertain if libpcap API version 1.0 level calls are supported by the system runtime. Also a call such as WinPcap.isSupported() will determine if WinPcap related calls, ie. native WinPcap 4.1.3 or less, are supported and by extension if this is a Microsoft Windows platform.

      Due to libpcap API versioning, it is safe to assume that if Pcap1_10.isSupported() returns true, that at least libpcap API version 1.0 is installed on this platform, and that all lower version calls such as libpcap 0.8 and 0.9 are available as well. The subclass hierarchy of jNetPcap module reflects the versioning of libpcap and its derivatives and the public releases of the native libraries. For example Npcap class extends WinPcap class because Npcap project took over the support for WinPcap where it left off.

      Implementation notes: The check is performed by verifying that certain, subclass specific native symbols were linked with Pcap full which was introduced at a specific libpcap or related API levels.

      Returns:
      true, if pcap is supported up to this specific version level, otherwise false
      See Also:
    • libVersion

      public static String libVersion()
      Get the version information for libpcap.
      Returns:
      a string giving information about the version of the libpcap library being used; note that it contains more information than just a version number
      Since:
      libpcap 0.8
    • loadNativePcapLibrary

      public static boolean loadNativePcapLibrary()
      Checks if native libpcap library is loaded, and if its not,it will attempt to load it. If library loading fails, no error messages are reported but false will be returned.
      Returns:
      true, if is native library was successfully loaded, otherwise false
      See Also:
      • PcapForeignInitializer.loadNativePcapLibrary(boolean)
    • lookupDev

      @Deprecated public static String lookupDev() throws PcapException
      Deprecated.
      use findAllDevs() and use the first device
      Find the default device on which to capture.

      Note: We're deprecating pcap_lookupdev() for various reasons (not thread-safe, can behave weirdly with WinPcap). Callers should use pcap_findalldevs() and use the first device.

      Returns:
      a device name
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 0.4
    • lookupNet

      public static NetIp4Address lookupNet(PcapIf device) throws PcapException
      Find the IPv4 network number and netmask for a device. pcap_lookupnet() is used to determine the IPv4 network number and mask associated with the network device device. Both netp and maskp are bpf_u_int32 pointers.
      Parameters:
      device - the network device name
      Returns:
      A netmasked IPv4 address
      Throws:
      PcapException - any LibpcapApi errors
      Since:
      libpcap 0.4
    • lookupNet

      public static NetIp4Address lookupNet(String device) throws PcapException
      Find the IPv4 network number and netmask for a device. pcap_lookupnet() is used to determine the IPv4 network number and mask associated with the network device device. Both netp and maskp are bpf_u_int32 pointers.
      Parameters:
      device - the network device name
      Returns:
      A netmasked IPv4 address
      Throws:
      PcapException - any LibpcapApi errors
      Since:
      libpcap 0.4
    • offlineFilter

      public static boolean offlineFilter(BpFilter bpFilter, MemorySegmentPREVIEW pktHdr, MemorySegmentPREVIEW pktData)
      Check whether a filter matches a packet.

      checks whether a filter matches a packet. fp is a pointer to a bpf_program struct, usually the result of a call to pcap_compile(3PCAP). h points to the pcap_pkthdr structure for the packet, and pkt points to the data in the packet.

      Parameters:
      bpFilter - the BPF program or filter program
      pktHdr - the packet header
      pktData - the packet data
      Returns:
      true, if filter matched packet otherwise false
      Since:
      Pcap 1.0
    • openDead

      public static Pcap openDead(PcapDlt linktype, int snaplen) throws PcapException
      Open a fake pcap_t for compiling filters or opening a capture for output.

      openDead(org.jnetpcap.constant.PcapDlt, int) and pcap_open_dead_with_tstamp_precision() are used for creating a pcap_t structure to use when calling the other functions in libpcap. It is typically used when just using libpcap for compiling BPF full; it can also be used if using pcap_dump_open(3PCAP), pcap_dump(3PCAP), and pcap_dump_close(3PCAP) to write a savefile if there is no pcap_t that supplies the packets to be written.

      When pcap_open_dead_with_tstamp_precision(), is used to create a pcap_t for use with pcap_dump_open(), precision specifies the time stamp precision for packets; PCAP_TSTAMP_PRECISION_MICRO should be specified if the packets to be written have time stamps in seconds and microseconds, and PCAP_TSTAMP_PRECISION_NANO should be specified if the packets to be written have time stamps in seconds and nanoseconds. Its value does not affect pcap_compile(3PCAP).

      Parameters:
      linktype - specifies the link-layer type for the pcap handle
      snaplen - specifies the snapshot length for the pcap handle
      Returns:
      A dead pcap handle
      Throws:
      PcapException - any errors
      Since:
      libpcap 0.6
    • openDeadWithTstampPrecision

      public static Pcap openDeadWithTstampPrecision(PcapDlt linktype, int snaplen, PcapTStampPrecision precision) throws PcapException
      Open a fake pcap_t for compiling filters or opening a capture for output.

      openDead(PcapDlt, int) and openDeadWithTstampPrecision(PcapDlt, int, PcapTStampPrecision) are used for creating a pcap_t structure to use when calling the other functions in libpcap. It is typically used when just using libpcap for compiling BPF full; it can also be used if using #dumpOpen(String), PcapDumper.dump(MemorySegment, MemorySegment)PREVIEW, and PcapDumper.close() to write a savefile if there is no pcap_t that supplies the packets to be written.

      When openDeadWithTstampPrecision(PcapDlt, int, PcapTStampPrecision), is used to create a Pcap handle for use with dumpOpen(String), precision specifies the time stamp precision for packets; PCAP_TSTAMP_PRECISION_MICRO should be specified if the packets to be written have time stamps in seconds and microseconds, and PCAP_TSTAMP_PRECISION_NANO should be specified if the packets to be written have time stamps in seconds and nanoseconds. Its value does not affect pcap_compile(3PCAP).

      Parameters:
      linktype - specifies the link-layer type for the pcap handle
      snaplen - specifies the snapshot length for the pcap handle
      precision - the requested timestamp precision
      Returns:
      A dead pcap handle
      Throws:
      PcapException - any errors
      Since:
      libpcap 1.5.1
    • openLive

      public static Pcap openLive(PcapIf device, int snaplen, boolean promisc, long timeout, TimeUnit unit) throws PcapException
      Open a device for capturing.

      openLive is used to obtain a packet capture handle to look at packets on the network. device is a string that specifies the network device to open; on Linux systems with 2.2 or later kernels, a device argument of "any" or NULL can be used to capture packets from all interfaces.

      Parameters:
      device - the device name
      snaplen - specifies the snapshot length to be set on the handle
      promisc - specifies whether the interface is to be put into promiscuous mode. If promisc is non-zero, promiscuous mode will be set, otherwise it will not be set
      timeout - the packet buffer timeout, as a non-negative value, in units
      unit - time timeout unit
      Returns:
      the pcap handle
      Throws:
      PcapException - any errors
      Since:
      libpcap 0.4
    • openLive

      public static Pcap openLive(String device, int snaplen, boolean promisc, long timeout, TimeUnit unit) throws PcapException
      Open a device for capturing.

      openLive is used to obtain a packet capture handle to look at packets on the network. device is a string that specifies the network device to open; on Linux systems with 2.2 or later kernels, a device argument of "any" or NULL can be used to capture packets from all interfaces.

      Parameters:
      device - the device name
      snaplen - specifies the snapshot length to be set on the handle
      promisc - specifies whether the interface is to be put into promiscuous mode. If promisc is non-zero, promiscuous mode will be set, otherwise it will not be set
      timeout - the packet buffer timeout, as a non-negative value, in units
      unit - time timeout unit
      Returns:
      the pcap handle
      Throws:
      PcapException - any errors
      Since:
      libpcap 0.4
    • openOffline

      public static Pcap openOffline(File file) throws PcapException
      Open a saved capture file for reading.

      pcap_open_offline() and pcap_open_offline_with_tstamp_precision() are called to open a ``savefile'' for reading.

      Parameters:
      file - the offline capture file
      Returns:
      the pcap handle
      Throws:
      PcapException - any errors
      Since:
      libpcap 0.4
    • openOffline

      public static Pcap openOffline(String fname) throws PcapException
      Open a saved capture file for reading.

      pcap_open_offline() and pcap_open_offline_with_tstamp_precision() are called to open a ``savefile'' for reading.

      Parameters:
      fname - specifies the name of the file to open. The file can have the pcap file format as described in pcap-savefile(5), which is the file format used by, among other programs, tcpdump(1) and tcpslice(1), or can have the pcapng file format, although not all pcapng files can be read
      Returns:
      the pcap handle
      Throws:
      PcapException - any errors
      Since:
      libpcap 0.4
    • statusToStr

      public static String statusToStr(int error)
      Convert an error full value to a string.
      Parameters:
      error - the error full to convert to a string
      Returns:
      the error string for the given full
      Since:
      libpcap 1.0
    • statusToStr

      public static String statusToStr(PcapCode error)
      Convert an error full value to a string.
      Parameters:
      error - the error full to convert to a string
      Returns:
      the error string for the given full
      Since:
      libpcap 1.0
    • strerror

      public static String strerror(int code)
      Convert an error full value to a string. This is a POSIX system error full, not pcap related as libpcap simply passes the errornum as a system call see https://linux.die.net/man/3/strerror.
      Parameters:
      code - the code
      Returns:
      the error string for the given full
      Since:
      libpcap 0.4
    • activate

      public void activate() throws PcapActivatedException, PcapException
      Activate a capture handle

      Is used to activate a packet capture handle to look at packets on the network, with the options that were set on the handle being in effect.

      Throws:
      PcapActivatedException - thrown if this pcap handle is already activated
      PcapException - The possible error values are:
      PCAP_ERROR_ACTIVATED
      The handle has already been activated
      PCAP_ERROR_NO_SUCH_DEVICE
      e capture source specified when the handle was created doesn't exist
      PCAP_ERROR_PERM_DENIED
      The process doesn't have permission to open the capture source
      PCAP_ERROR_PROMISC_PERM_DENIED
      The process has permission to open the capture source but doesn't have permission to put it into promiscuous mode
      PCAP_ERROR_RFMON_NOTSUP
      Monitor mode was specified but the capture source doesn't support monitor mode
      PCAP_ERROR_IFACE_NOT_UP
      The capture source device is not up
      PCAP_ERROR
      Another error occurred
      Since:
      libpcap 1.0
      See Also:
    • breakloop

      public void breakloop()
      Force a dispatch or loop call to return.

      Sets a flag that will force dispatch or loop to return rather than looping; they will return the number of packets that have been processed so far, or PcapConstants.PCAP_ERROR_BREAK if no packets have been processed so far.

      This routine is safe to use inside a signal handler on UNIX or a console control handler on Windows, as it merely sets a flag that is checked within the loop.

      The flag is checked in loops reading packets from the OS - a signal by itself will not necessarily terminate those loops - as well as in loops processing a set of packets returned by the OS. Note that if you are catching signals on UNIX systems that support restarting system calls after a signal, and calling breakloop in the signal handler, you must specify, when catching those signals, that system calls should NOT be restarted by that signal. Otherwise, if the signal interrupted a call reading packets in a live capture, when your signal handler returns after calling breakloop, the call will be restarted, and the loop will not terminate until more packets arrive and the call completes.

      Note also that, in a multi-threaded application, if one thread is blocked in dispatch, loop, pcap_next(3PCAP), or nextEx, a call to breakloop in a different thread will not unblock that thread. You will need to use whatever mechanism the OS provides for breaking a thread out of blocking calls in order to unblock the thread, such as thread cancellation or thread signalling in systems that support POSIX threads, or SetEvent() on the result of pcap_getevent() on a pcap_t on which the thread is blocked on Windows. Asynchronous procedure calls will not work on Windows, as a thread blocked on a pcap_t will not be in an alertable state.

      Note that next and nextEx will, on some platforms, loop reading packets from the OS; that loop will not necessarily be terminated by a signal, so breakloop should be used to terminate packet processing even if next or nextEx is being used.

      breakloop does not guarantee that no further packets will be processed by dispatch or loop after it is called; at most one more packet might be processed.

      If PcapConstants.PCAP_ERROR_BREAK is returned from dispatch or loop, the flag is cleared, so a subsequent call will resume reading packets. If a positive number is returned, the flag is not cleared, so a subsequent call will return PcapConstants.PCAP_ERROR_BREAK and clear the flag.

      Since:
      libpcap 0.8
    • canSetRfmon

      public boolean canSetRfmon() throws PcapException
      check whether monitor mode can be set for a not-yet-activated capture handle.

      Checks whether monitor mode could be set on a capture handle when the handle is activated.

      Returns:
      true, if rfmon is supported otherwise false
      Throws:
      PcapException - The possible error values are:

      PCAP_ERROR_NO_SUCH_DEVICE - The capture source specified when the handle was created doesn't exist

      PCAP_ERROR_PERM_DENIED - The process doesn't have permission to check whether monitor mode could be supported

      PCAP_ERROR_ACTIVATED - The capture handle has already been activated

      PCAP_ERROR - Another error occurred

      Since:
      libpcap 1.0
    • close

      public void close()
      Close a capture device or savefile

      Closes the files associated with p and deallocates resources.

      Specified by:
      close in interface AutoCloseable
      See Also:
    • compile

      public BpFilter compile(String str, boolean optimize) throws PcapException
      Compile a filter expression without a netmask.

      pcap_compile() is used to compile the string str into a filter program. See pcap-filter(7) for the syntax of that string. fp is a pointer to a bpf_program struct and is filled in by pcap_compile(). optimize controls whether optimization on the resulting full is performed. The netmask of the network on which packets are being captured isn't known to the program, or if packets are being captured on the Linux "any" pseudo-interface that can capture on more than one network, a value of PCAP_NETMASK_UNKNOWN can be supplied; tests for IPv4 broadcast addresses will fail to compile, but all other tests in the filter program will be OK.

      NOTE: in libpcap 1.8.0 and later, pcap_compile() can be used in multiple threads within a single process. However, in earlier versions of libpcap, it is not safe to use pcap_compile() in multiple threads in a single process without some form of mutual exclusion allowing only one thread to call it at any given time.

      Parameters:
      str - filter expression to be compiled
      optimize - controls whether optimization on the resulting full is performed
      Returns:
      the compiled filter
      Throws:
      PcapException - any errors
      Since:
      Pcap 0.4
    • compile

      public BpFilter compile(String str, boolean optimize, int netmask) throws PcapException
      Compile a filter expression with netmask.

      pcap_compile() is used to compile the string str into a filter program. See pcap-filter(7) for the syntax of that string. fp is a pointer to a bpf_program struct and is filled in by pcap_compile(). optimize controls whether optimization on the resulting full is performed. netmask specifies the IPv4 netmask of the network on which packets are being captured; it is used only when checking for IPv4 broadcast addresses in the filter program. If the netmask of the network on which packets are being captured isn't known to the program, or if packets are being captured on the Linux "any" pseudo-interface that can capture on more than one network, a value of PCAP_NETMASK_UNKNOWN can be supplied; tests for IPv4 broadcast addresses will fail to compile, but all other tests in the filter program will be OK.

      NOTE: in libpcap 1.8.0 and later, pcap_compile() can be used in multiple threads within a single process. However, in earlier versions of libpcap, it is not safe to use pcap_compile() in multiple threads in a single process without some form of mutual exclusion allowing only one thread to call it at any given time.

      Parameters:
      str - filter expression to be compiled
      optimize - controls whether optimization on the resulting full is performed
      netmask - specifies the IPv4 netmask of the network on which packets are being captured; it is used only when checking for IPv4 broadcast addresses in the filter program. If the netmask of the network on which packets are being captured isn't known to the program, or if packets are being captured on the Linux "any" pseudo-interface that can capture on more than one network, a value of PCAP_NETMASK_UNKNOWN can be supplied; tests for IPv4 broadcast addresses will fail to compile, but all other tests in the filter program will be OK
      Returns:
      the compiled filter
      Throws:
      PcapException - any errors
      Since:
      Pcap 0.4
    • datalink

      public PcapDlt datalink() throws PcapException
      Get the link-layer header type.

      It must not be called on a pcap descriptor created by pcap_create(3PCAP) that has not yet been activated by pcap_activate.

      https://www.tcpdump.org/linktypes.html lists the values pcap_datalink() can return and describes the packet formats that correspond to those values.

      Do NOT assume that the packets for a given capture or ``savefile`` will have any given link-layer header type, such as DLT_EN10MB for Ethernet. For example, the "any" device on Linux will have a link-layer header type of DLT_LINUX_SLL or DLT_LINUX_SLL2 even if all devices on the system at the time the "any" device is opened have some other data link type, such as DLT_EN10MB for Ethernet.

      Returns:
      link-layer header type
      Throws:
      PcapException - any pcap errors
      Since:
      libpcap 0.4
    • dataLinkExt

      public PcapDlt dataLinkExt() throws PcapException
      Gets the link-layer header type for the live capture or ``savefile''.
      Returns:
      link-layer header type
      Throws:
      PcapException - the pcap exception
    • dispatch

      public <U> int dispatch(int count, PcapDumper pcapDumper) throws PcapException
      Process packets from a live capture or savefile and save them directly to dump file.

      Processes packets from a live capture or ``savefile'' until cnt packets are processed, the end of the current bufferful of packets is reached when doing a live capture, the end of the ``savefile'' is reached when reading from a ``savefile'', pcap_breakloop() is called, or an error occurs. Thus, when doing a live capture, cnt is the maximum number of packets to process before returning, but is not a minimum number; when reading a live capture, only one bufferful of packets is read at a time, so fewer than cnt packets may be processed. A value of -1 or 0 for cnt causes all the packets received in one buffer to be processed when reading a live capture, and causes all the packets in the file to be processed when reading a ``savefile''.

      Note that, when doing a live capture on some platforms, if the read timeout expires when there are no packets available, pcap_dispatch() will return 0, even when not in non-blocking mode, as there are no packets to process. Applications should be prepared for this to happen, but must not rely on it happening.

      Callback specifies a pcap_handler routine to be called with three arguments: a u_char pointer which is passed in the user argument to pcap_loop() or pcap_dispatch(), a const struct pcap_pkthdr pointer pointing to the packet time stamp and lengths, and a const u_char pointer to the first caplen (as given in the struct pcap_pkthdr a pointer to which is passed to the callback routine) bytes of data from the packet. The struct pcap_pkthdr and the packet data are not to be freed by the callback routine, and are not guaranteed to be valid after the callback routine returns; if the full needs them to be valid after the callback, it must make a copy of them.

      The bytes of data from the packet begin with a link-layer header. The format of the link-layer header is indicated by the return value of the pcap_datalink(3PCAP) routine when handed the pcap_t value also passed to pcap_loop() or pcap_dispatch(). https://www.tcpdump.org/linktypes.html lists the values pcap_datalink() can return and describes the packet formats that correspond to those values. The value it returns will be valid for all packets received unless and until pcap_set_datalink(3PCAP) is called; after a successful call to pcap_set_datalink(), all subsequent packets will have a link-layer header of the type specified by the link-layer header type value passed to pcap_set_datalink().

      Do NOT assume that the packets for a given capture or ``savefile`` will have any given link-layer header type, such as DLT_EN10MB for Ethernet. For example, the "any" device on Linux will have a link-layer header type of DLT_LINUX_SLL or DLT_LINUX_SLL2 even if all devices on the system at the time the "any" device is opened have some other data link type, such as DLT_EN10MB for Ethernet.

      Type Parameters:
      U - the generic type
      Parameters:
      count - maximum number of packets to process before returning
      pcapDumper - the pcap dumper
      Returns:
      the number of packets processed on success; this can be 0 if no packets were read from a live capture (if, for example, they were discarded because they didn't pass the packet filter, or if, on platforms that support a packet buffer timeout that starts before any packets arrive, the timeout expires before any packets arrive, or if the file descriptor for the capture device is in non-blocking mode and no packets were available to be read) or if no more packets are available in a ``savefile.''
      Throws:
      PcapException - any pcap exceptions during call setup
      Since:
      libpcap 0.4
    • dispatch

      public int dispatch(int count, PcapHandler.NativeCallback handler, MemorySegmentPREVIEW user)
      Process packets from a live capture or savefile and dispatch using low level callback. The native callback is low level, and is only capable of passing native user objects and not compatible with java user objects.

      Processes packets from a live capture or ``savefile'' until cnt packets are processed, the end of the current bufferful of packets is reached when doing a live capture, the end of the ``savefile'' is reached when reading from a ``savefile'', pcap_breakloop() is called, or an error occurs. Thus, when doing a live capture, cnt is the maximum number of packets to process before returning, but is not a minimum number; when reading a live capture, only one bufferful of packets is read at a time, so fewer than cnt packets may be processed. A value of -1 or 0 for cnt causes all the packets received in one buffer to be processed when reading a live capture, and causes all the packets in the file to be processed when reading a ``savefile''.

      Note that, when doing a live capture on some platforms, if the read timeout expires when there are no packets available, pcap_dispatch() will return 0, even when not in non-blocking mode, as there are no packets to process. Applications should be prepared for this to happen, but must not rely on it happening.

      Callback specifies a pcap_handler routine to be called with three arguments: a u_char pointer which is passed in the user argument to pcap_loop() or pcap_dispatch(), a const struct pcap_pkthdr pointer pointing to the packet time stamp and lengths, and a const u_char pointer to the first caplen (as given in the struct pcap_pkthdr a pointer to which is passed to the callback routine) bytes of data from the packet. The struct pcap_pkthdr and the packet data are not to be freed by the callback routine, and are not guaranteed to be valid after the callback routine returns; if the full needs them to be valid after the callback, it must make a copy of them.

      The bytes of data from the packet begin with a link-layer header. The format of the link-layer header is indicated by the return value of the pcap_datalink(3PCAP) routine when handed the pcap_t value also passed to pcap_loop() or pcap_dispatch(). https://www.tcpdump.org/linktypes.html lists the values pcap_datalink() can return and describes the packet formats that correspond to those values. The value it returns will be valid for all packets received unless and until pcap_set_datalink(3PCAP) is called; after a successful call to pcap_set_datalink(), all subsequent packets will have a link-layer header of the type specified by the link-layer header type value passed to pcap_set_datalink().

      Do NOT assume that the packets for a given capture or ``savefile`` will have any given link-layer header type, such as DLT_EN10MB for Ethernet. For example, the "any" device on Linux will have a link-layer header type of DLT_LINUX_SLL or DLT_LINUX_SLL2 even if all devices on the system at the time the "any" device is opened have some other data link type, such as DLT_EN10MB for Ethernet.

      Parameters:
      count - maximum number of packets to process before returning
      handler - the handler
      user - TODO
      Returns:
      the number of packets processed on success; this can be 0 if no packets were read from a live capture (if, for example, they were discarded because they didn't pass the packet filter, or if, on platforms that support a packet buffer timeout that starts before any packets arrive, the timeout expires before any packets arrive, or if the file descriptor for the capture device is in non-blocking mode and no packets were available to be read) or if no more packets are available in a ``savefile.''
      Since:
      libpcap 0.4
    • dispatch

      public <U> int dispatch(int count, PcapHandler.OfArray<U> handler, U user) throws PcapException
      Process packets from a live capture or savefile and copy to a newly allocated array and dispatches to handler.

      Processes packets from a live capture or ``savefile'' until cnt packets are processed, the end of the current bufferful of packets is reached when doing a live capture, the end of the ``savefile'' is reached when reading from a ``savefile'', pcap_breakloop() is called, or an error occurs. Thus, when doing a live capture, cnt is the maximum number of packets to process before returning, but is not a minimum number; when reading a live capture, only one bufferful of packets is read at a time, so fewer than cnt packets may be processed. A value of -1 or 0 for cnt causes all the packets received in one buffer to be processed when reading a live capture, and causes all the packets in the file to be processed when reading a ``savefile''.

      Note that, when doing a live capture on some platforms, if the read timeout expires when there are no packets available, pcap_dispatch() will return 0, even when not in non-blocking mode, as there are no packets to process. Applications should be prepared for this to happen, but must not rely on it happening.

      Callback specifies a pcap_handler routine to be called with three arguments: a u_char pointer which is passed in the user argument to pcap_loop() or pcap_dispatch(), a const struct pcap_pkthdr pointer pointing to the packet time stamp and lengths, and a const u_char pointer to the first caplen (as given in the struct pcap_pkthdr a pointer to which is passed to the callback routine) bytes of data from the packet. The struct pcap_pkthdr and the packet data are not to be freed by the callback routine, and are not guaranteed to be valid after the callback routine returns; if the full needs them to be valid after the callback, it must make a copy of them.

      The bytes of data from the packet begin with a link-layer header. The format of the link-layer header is indicated by the return value of the pcap_datalink(3PCAP) routine when handed the pcap_t value also passed to pcap_loop() or pcap_dispatch(). https://www.tcpdump.org/linktypes.html lists the values pcap_datalink() can return and describes the packet formats that correspond to those values. The value it returns will be valid for all packets received unless and until pcap_set_datalink(3PCAP) is called; after a successful call to pcap_set_datalink(), all subsequent packets will have a link-layer header of the type specified by the link-layer header type value passed to pcap_set_datalink().

      Do NOT assume that the packets for a given capture or ``savefile`` will have any given link-layer header type, such as DLT_EN10MB for Ethernet. For example, the "any" device on Linux will have a link-layer header type of DLT_LINUX_SLL or DLT_LINUX_SLL2 even if all devices on the system at the time the "any" device is opened have some other data link type, such as DLT_EN10MB for Ethernet.

      Type Parameters:
      U - the generic type
      Parameters:
      count - maximum number of packets to process before returning
      handler - specifies a handler method to be called
      user - the user opaque object
      Returns:
      the number of packets processed on success; this can be 0 if no packets were read from a live capture (if, for example, they were discarded because they didn't pass the packet filter, or if, on platforms that support a packet buffer timeout that starts before any packets arrive, the timeout expires before any packets arrive, or if the file descriptor for the capture device is in non-blocking mode and no packets were available to be read) or if no more packets are available in a ``savefile.''
      Throws:
      PcapException - any pcap exceptions during call setup
      Since:
      libpcap 0.4
    • dispatch

      public <U> int dispatch(int count, PcapHandler.OfMemorySegment<U> handler, U user) throws PcapException
      Process packets from a live capture or savefile and dispatch directly to handler. The scope of each memory segment dispatched by this call is only valid for the duration of the dispatch to handler. After that, the packet memory is reused by libpcap and its contents no longer valid if retained.

      Processes packets from a live capture or ``savefile'' until cnt packets are processed, the end of the current bufferful of packets is reached when doing a live capture, the end of the ``savefile'' is reached when reading from a ``savefile'', pcap_breakloop() is called, or an error occurs. Thus, when doing a live capture, cnt is the maximum number of packets to process before returning, but is not a minimum number; when reading a live capture, only one bufferful of packets is read at a time, so fewer than cnt packets may be processed. A value of -1 or 0 for cnt causes all the packets received in one buffer to be processed when reading a live capture, and causes all the packets in the file to be processed when reading a ``savefile''.

      Note that, when doing a live capture on some platforms, if the read timeout expires when there are no packets available, pcap_dispatch() will return 0, even when not in non-blocking mode, as there are no packets to process. Applications should be prepared for this to happen, but must not rely on it happening.

      Callback specifies a pcap_handler routine to be called with three arguments: a u_char pointer which is passed in the user argument to pcap_loop() or pcap_dispatch(), a const struct pcap_pkthdr pointer pointing to the packet time stamp and lengths, and a const u_char pointer to the first caplen (as given in the struct pcap_pkthdr a pointer to which is passed to the callback routine) bytes of data from the packet. The struct pcap_pkthdr and the packet data are not to be freed by the callback routine, and are not guaranteed to be valid after the callback routine returns; if the full needs them to be valid after the callback, it must make a copy of them.

      The bytes of data from the packet begin with a link-layer header. The format of the link-layer header is indicated by the return value of the pcap_datalink(3PCAP) routine when handed the pcap_t value also passed to pcap_loop() or pcap_dispatch(). https://www.tcpdump.org/linktypes.html lists the values pcap_datalink() can return and describes the packet formats that correspond to those values. The value it returns will be valid for all packets received unless and until pcap_set_datalink(3PCAP) is called; after a successful call to pcap_set_datalink(), all subsequent packets will have a link-layer header of the type specified by the link-layer header type value passed to pcap_set_datalink().

      Do NOT assume that the packets for a given capture or ``savefile`` will have any given link-layer header type, such as DLT_EN10MB for Ethernet. For example, the "any" device on Linux will have a link-layer header type of DLT_LINUX_SLL or DLT_LINUX_SLL2 even if all devices on the system at the time the "any" device is opened have some other data link type, such as DLT_EN10MB for Ethernet.

      Type Parameters:
      U - the generic type
      Parameters:
      count - maximum number of packets to process before returning
      handler - specifies a handler method to be called
      user - the user opaque object
      Returns:
      the number of packets processed on success; this can be 0 if no packets were read from a live capture (if, for example, they were discarded because they didn't pass the packet filter, or if, on platforms that support a packet buffer timeout that starts before any packets arrive, the timeout expires before any packets arrive, or if the file descriptor for the capture device is in non-blocking mode and no packets were available to be read) or if no more packets are available in a ``savefile.''
      Throws:
      PcapException - any pcap exceptions during call setup
      Since:
      libpcap 0.4
    • dumpOpen

      public PcapDumper dumpOpen(String fname) throws PcapException
      Open a file to which to write packets.

      pcap_dump_open() is called to open a ``savefile'' for writing. fname specifies the name of the file to open. The file will have the same format as those used by tcpdump(1) and tcpslice(1). If the file does not exist, it will be created; if the file exists, it will be truncated and overwritten. The name "-" is a synonym for stdout. pcap_dump_fopen() is called to write data to an existing open stream fp; this stream will be closed by a subsequent call to pcap_dump_close(3PCAP). The stream is assumed to be at the beginning of a file that has been newly created or truncated, so that writes will start at the beginning of the file. Note that on Windows, that stream should be opened in binary mode.

      p is a capture or ``savefile'' handle returned by an earlier call to pcap_create(3PCAP) and activated by an earlier call to pcap_activate(3PCAP), or returned by an earlier call to pcap_open_offline(3PCAP), pcap_open_live(3PCAP), or pcap_open_dead(3PCAP). The time stamp precision, link-layer type, and snapshot length from p are used as the link-layer type and snapshot length of the output file.

      pcap_dump_open_append() is like pcap_dump_open() but, if the file already exists, and is a pcap file with the same byte order as the host opening the file, and has the same time stamp precision, link-layer header type, and snapshot length as p, it will write new packets at the end of the file.

      Parameters:
      fname - the fname
      Returns:
      the pcap dumper
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 0.4
    • geterr

      public String geterr()
      Get libpcap error message text.
      Returns:
      the error text pertaining to the last pcap library error
      Since:
      libpcap 0.4
    • getName

      public final String getName()
      Gets the name of this pcap handle. The name by default is the offline filename or network interface name, if specified.
      Returns:
      the name of this pcap handle
    • getNonBlock

      public boolean getNonBlock() throws PcapException
      Gets the state of non-blocking mode on a capture device.

      pcap_setnonblock() puts a capture handle into ``non-blocking'' mode, or takes it out of ``non-blocking'' mode, depending on whether the nonblock argument is non-zero or zero. It has no effect on ``savefiles''. If there is an error, PCAP_ERROR is returned and errbuf is filled in with an appropriate error message; otherwise, 0 is returned. In ``non-blocking'' mode, an attempt to read from the capture descriptor with pcap_dispatch(3PCAP) and pcap_next_ex(3PCAP) will, if no packets are currently available to be read, return 0 immediately rather than blocking waiting for packets to arrive.

      pcap_loop(3PCAP) will loop forever, consuming CPU time when no packets are currently available; pcap_dispatch() should be used instead. pcap_next(3PCAP) will return NULL if there are no packets currently available to read; this is indistinguishable from an error, so pcap_next_ex() should be used instead.

      When first activated with pcap_activate(3PCAP) or opened with pcap_open_live(3PCAP), a capture handle is not in ``non-blocking mode''; a call to pcap_setnonblock() is required in order to put it into ``non-blocking'' mode.

      Returns:
      the non block
      Throws:
      PcapException - any pcap errors
      Since:
      libpcap 0.7
    • getTstampPrecision

      public PcapTStampPrecision getTstampPrecision() throws PcapException
      Get the time stamp precision returned in captures.

      Returns the precision of the time stamp returned in packet captures on the pcap descriptor.

      Returns:
      returns PCAP_TSTAMP_PRECISION_MICRO or PCAP_TSTAMP_PRECISION_NANO, which indicates that pcap captures contains time stamps in microseconds or nanoseconds respectively
      Throws:
      PcapException - any pcap errors
      Since:
      libpcap 1.5
    • inject

      public int inject(MemorySegmentPREVIEW packet, int length) throws PcapException
      Transmit a packet.

      pcap_inject() sends a raw packet through the network interface; buf points to the data of the packet, including the link-layer header, and size is the number of bytes in the packet. Note that, even if you successfully open the network interface, you might not have permission to send packets on it, or it might not support sending packets; as pcap_open_live(3PCAP) doesn't have a flag to indicate whether to open for capturing, sending, or capturing and sending, you cannot request an open that supports sending and be notified at open time whether sending will be possible. Note also that some devices might not support sending packets.

      Note that, on some platforms, the link-layer header of the packet that's sent might not be the same as the link-layer header of the packet supplied to pcap_inject(), as the source link-layer address, if the header contains such an address, might be changed to be the address assigned to the interface on which the packet it sent, if the platform doesn't support sending completely raw and unchanged packets. Even worse, some drivers on some platforms might change the link-layer type field to whatever value libpcap used when attaching to the device, even on platforms that do nominally support sending completely raw and unchanged packets.

      pcap_sendpacket() is like pcap_inject(), but it returns 0 on success, rather than returning the number of bytes written. (pcap_inject() comes from OpenBSD; pcap_sendpacket() comes from WinPcap/Npcap. Both are provided for compatibility.)

      Parameters:
      packet - the packet
      length - the packet length
      Returns:
      number of bytes written
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 0.9
    • inject

      public final int inject(byte[] array) throws PcapException
      Transmit a packet.

      pcap_inject() sends a raw packet through the network interface; buf points to the data of the packet, including the link-layer header, and size is the number of bytes in the packet. Note that, even if you successfully open the network interface, you might not have permission to send packets on it, or it might not support sending packets; as pcap_open_live(3PCAP) doesn't have a flag to indicate whether to open for capturing, sending, or capturing and sending, you cannot request an open that supports sending and be notified at open time whether sending will be possible. Note also that some devices might not support sending packets.

      Note that, on some platforms, the link-layer header of the packet that's sent might not be the same as the link-layer header of the packet supplied to pcap_inject(), as the source link-layer address, if the header contains such an address, might be changed to be the address assigned to the interface on which the packet it sent, if the platform doesn't support sending completely raw and unchanged packets. Even worse, some drivers on some platforms might change the link-layer type field to whatever value libpcap used when attaching to the device, even on platforms that do nominally support sending completely raw and unchanged packets.

      pcap_sendpacket() is like pcap_inject(), but it returns 0 on success, rather than returning the number of bytes written. (pcap_inject() comes from OpenBSD; pcap_sendpacket() comes from WinPcap/Npcap. Both are provided for compatibility.)

      Parameters:
      array - the array containing packet data, including the datalink layer
      Returns:
      number of bytes written
      Throws:
      PcapException - the pcap exception
    • inject

      public final int inject(byte[] array, int offset, int length) throws PcapException
      Transmit a packet.

      pcap_inject() sends a raw packet through the network interface; buf points to the data of the packet, including the link-layer header, and size is the number of bytes in the packet. Note that, even if you successfully open the network interface, you might not have permission to send packets on it, or it might not support sending packets; as pcap_open_live(3PCAP) doesn't have a flag to indicate whether to open for capturing, sending, or capturing and sending, you cannot request an open that supports sending and be notified at open time whether sending will be possible. Note also that some devices might not support sending packets.

      Note that, on some platforms, the link-layer header of the packet that's sent might not be the same as the link-layer header of the packet supplied to pcap_inject(), as the source link-layer address, if the header contains such an address, might be changed to be the address assigned to the interface on which the packet it sent, if the platform doesn't support sending completely raw and unchanged packets. Even worse, some drivers on some platforms might change the link-layer type field to whatever value libpcap used when attaching to the device, even on platforms that do nominally support sending completely raw and unchanged packets.

      pcap_sendpacket() is like pcap_inject(), but it returns 0 on success, rather than returning the number of bytes written. (pcap_inject() comes from OpenBSD; pcap_sendpacket() comes from WinPcap/Npcap. Both are provided for compatibility.)

      Parameters:
      array - the array containing packet data, including the datalink layer
      offset - the offset into the byte array
      length - the packet length
      Returns:
      number of bytes written
      Throws:
      PcapException - the pcap exception
    • inject

      public final int inject(ByteBuffer buf) throws PcapException
      Transmit a packet.

      pcap_inject() sends a raw packet through the network interface; buf points to the data of the packet, including the link-layer header, and size is the number of bytes in the packet. Note that, even if you successfully open the network interface, you might not have permission to send packets on it, or it might not support sending packets; as pcap_open_live(3PCAP) doesn't have a flag to indicate whether to open for capturing, sending, or capturing and sending, you cannot request an open that supports sending and be notified at open time whether sending will be possible. Note also that some devices might not support sending packets.

      Note that, on some platforms, the link-layer header of the packet that's sent might not be the same as the link-layer header of the packet supplied to pcap_inject(), as the source link-layer address, if the header contains such an address, might be changed to be the address assigned to the interface on which the packet it sent, if the platform doesn't support sending completely raw and unchanged packets. Even worse, some drivers on some platforms might change the link-layer type field to whatever value libpcap used when attaching to the device, even on platforms that do nominally support sending completely raw and unchanged packets.

      pcap_sendpacket() is like pcap_inject(), but it returns 0 on success, rather than returning the number of bytes written. (pcap_inject() comes from OpenBSD; pcap_sendpacket() comes from WinPcap/Npcap. Both are provided for compatibility.)

      Parameters:
      buf - The packet starts relative to the buffer's position (inclusive) and ends relative to the buffer's limit (exclusive)
      Returns:
      number of bytes written
      Throws:
      PcapException - the pcap exception
    • isSwapped

      public boolean isSwapped() throws PcapException
      Find out whether a savefile has the native byte order.

      Returns true if pcap refers to a ``savefile'' that uses a different byte order than the current system. For a live capture, it always returns false.

      Returns:
      true if swapped, otherwise false
      Throws:
      PcapException - any pcap errors
      Since:
      libpcap 0.4
      See Also:
    • listDataLinks

      public List<PcapDlt> listDataLinks() throws PcapException
      Get a list of link-layer header types supported by a capture device.
      Returns:
      a list of link-layer header types
      Throws:
      PcapException - any pcap errors
      Since:
      libpcap 0.8
    • listTstampTypes

      public List<PcapTstampType> listTstampTypes() throws PcapException
      Get a list of time stamp types supported by a capture device.

      pcap_list_tstamp_types() is used to get a list of the supported time stamp types of the interface associated with the pcap descriptor

      Returns:
      a list of timestamp types
      Throws:
      PcapException - any pcap errors
      Since:
      libpcap 1.2
    • loop

      public <U> int loop(int count, PcapDumper pcapDumper) throws PcapException
      Process packets from a live capture or savefile and save them directly to dump file.

      pcap_loop() processes packets from a live capture or ``savefile'' until cnt packets are processed, the end of the ``savefile'' is reached when reading from a ``savefile'', pcap_breakloop(3PCAP) is called, or an error occurs. It does not return when live packet buffer timeouts occur. A value of -1 or 0 for cnt is equivalent to infinity, so that packets are processed until another ending condition occurs.

      Note that, when doing a live capture on some platforms, if the read timeout expires when there are no packets available, pcap_dispatch() will return 0, even when not in non-blocking mode, as there are no packets to process. Applications should be prepared for this to happen, but must not rely on it happening.

      callback specifies a pcap_handler routine to be called with three arguments: a u_char pointer which is passed in the user argument to pcap_loop() or pcap_dispatch(), a const struct pcap_pkthdr pointer pointing to the packet time stamp and lengths, and a const u_char pointer to the first caplen (as given in the struct pcap_pkthdr a pointer to which is passed to the callback routine) bytes of data from the packet. The struct pcap_pkthdr and the packet data are not to be freed by the callback routine, and are not guaranteed to be valid after the callback routine returns; if the full needs them to be valid after the callback, it must make a copy of them.

      The bytes of data from the packet begin with a link-layer header. The format of the link-layer header is indicated by the return value of the pcap_datalink(3PCAP) routine when handed the pcap_t value also passed to pcap_loop() or pcap_dispatch(). https://www.tcpdump.org/linktypes.html lists the values pcap_datalink() can return and describes the packet formats that correspond to those values. The value it returns will be valid for all packets received unless and until pcap_set_datalink(3PCAP) is called; after a successful call to pcap_set_datalink(), all subsequent packets will have a link-layer header of the type specified by the link-layer header type value passed to pcap_set_datalink().

      Do NOT assume that the packets for a given capture or ``savefile`` will have any given link-layer header type, such as DLT_EN10MB for Ethernet. For example, the "any" device on Linux will have a link-layer header type of DLT_LINUX_SLL or DLT_LINUX_SLL2 even if all devices on the system at the time the "any" device is opened have some other data link type, such as DLT_EN10MB for Ethernet.

      Type Parameters:
      U - the generic user data type
      Parameters:
      count - A value of -1 or 0 for count is equivalent to infinity, so that packets are processed until another ending condition occurs
      pcapDumper - the pcap dumper
      Returns:
      returns 0 if count is exhausted or if, when reading from a ``savefile'', no more packets are available. It returns PCAP_ERROR_BREAK if the loop terminated due to a call to pcap_breakloop() before any packets were processed
      Throws:
      PcapException - any pcap errors
      Since:
      libpcap 0.4
    • loop

      public <U> int loop(int count, PcapHandler.NativeCallback handler, MemorySegmentPREVIEW user)
      Process packets from a live capture or savefile and dispatch using low level callback. The native callback is low level, and is only capable of passing native user objects and not compatible with java user objects.

      pcap_loop() processes packets from a live capture or ``savefile'' until cnt packets are processed, the end of the ``savefile'' is reached when reading from a ``savefile'', pcap_breakloop(3PCAP) is called, or an error occurs. It does not return when live packet buffer timeouts occur. A value of -1 or 0 for cnt is equivalent to infinity, so that packets are processed until another ending condition occurs.

      Note that, when doing a live capture on some platforms, if the read timeout expires when there are no packets available, pcap_dispatch() will return 0, even when not in non-blocking mode, as there are no packets to process. Applications should be prepared for this to happen, but must not rely on it happening.

      callback specifies a pcap_handler routine to be called with three arguments: a u_char pointer which is passed in the user argument to pcap_loop() or pcap_dispatch(), a const struct pcap_pkthdr pointer pointing to the packet time stamp and lengths, and a const u_char pointer to the first caplen (as given in the struct pcap_pkthdr a pointer to which is passed to the callback routine) bytes of data from the packet. The struct pcap_pkthdr and the packet data are not to be freed by the callback routine, and are not guaranteed to be valid after the callback routine returns; if the full needs them to be valid after the callback, it must make a copy of them.

      The bytes of data from the packet begin with a link-layer header. The format of the link-layer header is indicated by the return value of the pcap_datalink(3PCAP) routine when handed the pcap_t value also passed to pcap_loop() or pcap_dispatch(). https://www.tcpdump.org/linktypes.html lists the values pcap_datalink() can return and describes the packet formats that correspond to those values. The value it returns will be valid for all packets received unless and until pcap_set_datalink(3PCAP) is called; after a successful call to pcap_set_datalink(), all subsequent packets will have a link-layer header of the type specified by the link-layer header type value passed to pcap_set_datalink().

      Do NOT assume that the packets for a given capture or ``savefile`` will have any given link-layer header type, such as DLT_EN10MB for Ethernet. For example, the "any" device on Linux will have a link-layer header type of DLT_LINUX_SLL or DLT_LINUX_SLL2 even if all devices on the system at the time the "any" device is opened have some other data link type, such as DLT_EN10MB for Ethernet.

      Type Parameters:
      U - the generic user data type
      Parameters:
      count - A value of -1 or 0 for count is equivalent to infinity, so that packets are processed until another ending condition occurs
      handler - the native handler which receives packets
      user - native user object
      Returns:
      returns 0 if count is exhausted or if, when reading from a ``savefile'', no more packets are available. It returns PCAP_ERROR_BREAK if the loop terminated due to a call to pcap_breakloop() before any packets were processed
      Since:
      libpcap 0.4
    • loop

      public <U> int loop(int count, PcapHandler.OfArray<U> handler, U user) throws PcapException
      Process packets from a live capture or savefile and copy to a newly allocated array and dispatches to handler.

      pcap_loop() processes packets from a live capture or ``savefile'' until cnt packets are processed, the end of the ``savefile'' is reached when reading from a ``savefile'', pcap_breakloop(3PCAP) is called, or an error occurs. It does not return when live packet buffer timeouts occur. A value of -1 or 0 for cnt is equivalent to infinity, so that packets are processed until another ending condition occurs.

      Note that, when doing a live capture on some platforms, if the read timeout expires when there are no packets available, pcap_dispatch() will return 0, even when not in non-blocking mode, as there are no packets to process. Applications should be prepared for this to happen, but must not rely on it happening.

      callback specifies a pcap_handler routine to be called with three arguments: a u_char pointer which is passed in the user argument to pcap_loop() or pcap_dispatch(), a const struct pcap_pkthdr pointer pointing to the packet time stamp and lengths, and a const u_char pointer to the first caplen (as given in the struct pcap_pkthdr a pointer to which is passed to the callback routine) bytes of data from the packet. The struct pcap_pkthdr and the packet data are not to be freed by the callback routine, and are not guaranteed to be valid after the callback routine returns; if the full needs them to be valid after the callback, it must make a copy of them.

      The bytes of data from the packet begin with a link-layer header. The format of the link-layer header is indicated by the return value of the pcap_datalink(3PCAP) routine when handed the pcap_t value also passed to pcap_loop() or pcap_dispatch(). https://www.tcpdump.org/linktypes.html lists the values pcap_datalink() can return and describes the packet formats that correspond to those values. The value it returns will be valid for all packets received unless and until pcap_set_datalink(3PCAP) is called; after a successful call to pcap_set_datalink(), all subsequent packets will have a link-layer header of the type specified by the link-layer header type value passed to pcap_set_datalink().

      Do NOT assume that the packets for a given capture or ``savefile`` will have any given link-layer header type, such as DLT_EN10MB for Ethernet. For example, the "any" device on Linux will have a link-layer header type of DLT_LINUX_SLL or DLT_LINUX_SLL2 even if all devices on the system at the time the "any" device is opened have some other data link type, such as DLT_EN10MB for Ethernet.

      Type Parameters:
      U - the generic user data type
      Parameters:
      count - A value of -1 or 0 for count is equivalent to infinity, so that packets are processed until another ending condition occurs
      handler - array handler which will receive packets
      user - user opaque data to be returned with the callback
      Returns:
      returns 0 if count is exhausted or if, when reading from a ``savefile'', no more packets are available. It returns PCAP_ERROR_BREAK if the loop terminated due to a call to pcap_breakloop() before any packets were processed
      Throws:
      PcapException - any pcap errors
      Since:
      libpcap 0.4
    • loop

      public <U> int loop(int count, PcapHandler.OfMemorySegment<U> handler, U user)
      Process packets from a live capture or savefile and dispatch directly to handler. The scope of each memory segment dispatched by this call is only valid for the duration of the dispatch to handler. After that, the packet memory is reused by libpcap and its contents no longer valid if retained.

      pcap_loop() processes packets from a live capture or ``savefile'' until cnt packets are processed, the end of the ``savefile'' is reached when reading from a ``savefile'', pcap_breakloop(3PCAP) is called, or an error occurs. It does not return when live packet buffer timeouts occur. A value of -1 or 0 for cnt is equivalent to infinity, so that packets are processed until another ending condition occurs.

      Note that, when doing a live capture on some platforms, if the read timeout expires when there are no packets available, pcap_dispatch() will return 0, even when not in non-blocking mode, as there are no packets to process. Applications should be prepared for this to happen, but must not rely on it happening.

      callback specifies a pcap_handler routine to be called with three arguments: a u_char pointer which is passed in the user argument to pcap_loop() or pcap_dispatch(), a const struct pcap_pkthdr pointer pointing to the packet time stamp and lengths, and a const u_char pointer to the first caplen (as given in the struct pcap_pkthdr a pointer to which is passed to the callback routine) bytes of data from the packet. The struct pcap_pkthdr and the packet data are not to be freed by the callback routine, and are not guaranteed to be valid after the callback routine returns; if the full needs them to be valid after the callback, it must make a copy of them.

      The bytes of data from the packet begin with a link-layer header. The format of the link-layer header is indicated by the return value of the pcap_datalink(3PCAP) routine when handed the pcap_t value also passed to pcap_loop() or pcap_dispatch(). https://www.tcpdump.org/linktypes.html lists the values pcap_datalink() can return and describes the packet formats that correspond to those values. The value it returns will be valid for all packets received unless and until pcap_set_datalink(3PCAP) is called; after a successful call to pcap_set_datalink(), all subsequent packets will have a link-layer header of the type specified by the link-layer header type value passed to pcap_set_datalink().

      Do NOT assume that the packets for a given capture or ``savefile`` will have any given link-layer header type, such as DLT_EN10MB for Ethernet. For example, the "any" device on Linux will have a link-layer header type of DLT_LINUX_SLL or DLT_LINUX_SLL2 even if all devices on the system at the time the "any" device is opened have some other data link type, such as DLT_EN10MB for Ethernet.

      Type Parameters:
      U - the generic type
      Parameters:
      count - A value of -1 or 0 for count is equivalent to infinity, so that packets are processed until another ending condition occurs
      handler - array handler which will receive packets
      user - the user opaque java object
      Returns:
      returns 0 if count is exhausted or if, when reading from a ``savefile'', no more packets are available. It returns PCAP_ERROR_BREAK if the loop terminated due to a call to pcap_breakloop() before any packets were processed
      Since:
      libpcap 0.4
    • majorVersion

      public int majorVersion() throws PcapException
      Get the version number of a savefile.

      If p refers to a ``savefile'', majorVersion returns the major number of the file format of the ``savefile''. The version number is stored in the ``savefile''; note that the meaning of its values depends on the type of ``savefile'' (for example, pcap or pcapng).

      If pcap handle refers to a live capture, the values returned by majorVersion and pcap_minor_version() are not meaningful.

      Returns:
      the major number of the file format of the ``savefile''
      Throws:
      PcapException - the pcap exception
    • minorVersion

      public int minorVersion() throws PcapException
      Get the version number of a savefile.

      If p refers to a ``savefile'', minorVersion returns the minor number of the file format of the ``savefile''. The version number is stored in the ``savefile''; note that the meaning of its values depends on the type of ``savefile'' (for example, pcap or pcapng).

      If pcap handle refers to a live capture, the values returned by majorVersion and pcap_minor_version() are not meaningful.

      Returns:
      the minor number of the file format of the ``savefile''
      Throws:
      PcapException - the pcap exception
    • next

      public PcapPacketRefPREVIEW next() throws PcapException
      read the next packet from a handle.

      reads the next packet (by calling dispatch with a cnt of 1) and returns a u_char pointer to the data in that packet. The packet data is not to be freed by the caller, and is not guaranteed to be valid after the next call to nextEx, next, loop, or dispatch; if the full needs it to remain valid, it must make a copy of it. The pcap_pkthdr structure pointed to by h is filled in with the appropriate values for the packet.

      The bytes of data from the packet begin with a link-layer header. The format of the link-layer header is indicated by the return value of the datalink routine when handed the pcap_t value also passed to loop or dispatch. https://www.tcpdump.org/linktypes.html lists the values datalink can return and describes the packet formats that correspond to those values. The value it returns will be valid for all packets received unless and until setDatalink is called; after a successful call to setDatalink, all subsequent packets will have a link-layer header of the type specified by the link-layer header type value passed to setDatalink.

      Do NOT assume that the packets for a given capture or ``savefile`` will have any given link-layer header type, such as DLT_EN10MB for Ethernet. For example, the "any" device on Linux will have a link-layer header type of DLT_LINUX_SLL or DLT_LINUX_SLL2 even if all devices on the system at the time the "any" device is opened have some other data link type, such as DLT_EN10MB for Ethernet.

      Returns:
      a pointer to the packet data on success, and returns NULL if no packets were read from a live capture (if, for example, they were discarded because they didn't pass the packet filter, or if, on platforms that support a packet buffer timeout that starts before any packets arrive, the timeout expires before any packets arrive, or if the file descriptor for the capture device is in non-blocking mode and no packets were available to be read), or if no more packets are available in a ``savefile.'' Unfortunately, there is no way to determine whether an error occurred or not.
      Throws:
      PcapException - Unfortunately, there is no way to determine whether an error occurred or not so exception may be due to no packets being captured and not an actual error.
      Since:
      libpcap 0.4
    • nextEx

      Read the next packet from a pcap handle.

      reads the next packet and returns a success/failure indication. If the packet was read without problems, the pointer pointed to by the pktHeader argument is set to point to the pcap_pkthdr struct for the packet, and the pointer pointed to by the pktData argument is set to point to the data in the packet. The struct pcap_pkthdr and the packet data are not to be freed by the caller, and are not guaranteed to be valid after the next call to nextEx(), next(), loop(int, org.jnetpcap.PcapDumper), or dispatch(int, org.jnetpcap.PcapDumper); if the full needs them to remain valid, it must make a copy of them. *

      The bytes of data from the packet begin with a link-layer header. The format of the link-layer header is indicated by the return value of the datalink routine when handed the pcap_t value also passed to loop or dispatch. https://www.tcpdump.org/linktypes.html lists the values datalink can return and describes the packet formats that correspond to those values. The value it returns will be valid for all packets received unless and until setDatalink is called; after a successful call to setDatalink, all subsequent packets will have a link-layer header of the type specified by the link-layer header type value passed to setDatalink.

      Do NOT assume that the packets for a given capture or ``savefile`` will have any given link-layer header type, such as DLT_EN10MB for Ethernet. For example, the "any" device on Linux will have a link-layer header type of DLT_LINUX_SLL or DLT_LINUX_SLL2 even if all devices on the system at the time the "any" device is opened have some other data link type, such as DLT_EN10MB for Ethernet.

      Returns:
      a native pcap packet reference or null if packets are being read from a ``savefile'' and there are no more packets to read from the savefile.
      Throws:
      PcapException - any pcap errors such as not activated, etc.
      TimeoutException - if packets are being read from a live capture and the packet buffer timeout expired
      Since:
      Pcap 0.8
    • order

      public final ByteOrder order() throws PcapException
      Returns the ByteOrder of the current capture based on results from isSwapped() method call. Calculates the actual byte order of the data. For live captures this will equal the native byte order for capture files, it can be either little or big depending on how the ``savefile'' was saved.
      Returns:
      the byte order
      Throws:
      PcapException - the pcap exception
      See Also:
    • perror

      public Pcap perror(String prefix)
      Print libpcap error message text.

      prints the text of the last pcap library error on stderr, prefixed by prefix

      Parameters:
      prefix - the message prefix
      Returns:
      this pcap handle
    • sendPacket

      public void sendPacket(MemorySegmentPREVIEW packet, int length) throws PcapException
      Transmit a packet.

      pcap_sendpacket() sends a raw packet through the network interface; buf points to the data of the packet, including the link-layer header, and size is the number of bytes in the packet. Note that, even if you successfully open the network interface, you might not have permission to send packets on it, or it might not support sending packets; as pcap_open_live(3PCAP) doesn't have a flag to indicate whether to open for capturing, sending, or capturing and sending, you cannot request an open that supports sending and be notified at open time whether sending will be possible. Note also that some devices might not support sending packets.

      Note that, on some platforms, the link-layer header of the packet that's sent might not be the same as the link-layer header of the packet supplied to pcap_sendpacket(), as the source link-layer address, if the header contains such an address, might be changed to be the address assigned to the interface on which the packet it sent, if the platform doesn't support sending completely raw and unchanged packets. Even worse, some drivers on some platforms might change the link-layer type field to whatever value libpcap used when attaching to the device, even on platforms that do nominally support sending completely raw and unchanged packets.

      Parameters:
      packet - the packet
      length - the length number of bytes to send
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 0.8
    • sendPacket

      public final void sendPacket(byte[] buf) throws PcapException
      Transmit a packet.

      pcap_sendpacket() sends a raw packet through the network interface; buf points to the data of the packet, including the link-layer header, and size is the number of bytes in the packet. Note that, even if you successfully open the network interface, you might not have permission to send packets on it, or it might not support sending packets; as pcap_open_live(3PCAP) doesn't have a flag to indicate whether to open for capturing, sending, or capturing and sending, you cannot request an open that supports sending and be notified at open time whether sending will be possible. Note also that some devices might not support sending packets.

      Note that, on some platforms, the link-layer header of the packet that's sent might not be the same as the link-layer header of the packet supplied to pcap_sendpacket(), as the source link-layer address, if the header contains such an address, might be changed to be the address assigned to the interface on which the packet it sent, if the platform doesn't support sending completely raw and unchanged packets. Even worse, some drivers on some platforms might change the link-layer type field to whatever value libpcap used when attaching to the device, even on platforms that do nominally support sending completely raw and unchanged packets.

      Parameters:
      buf - the buf
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 0.8
    • sendPacket

      public final void sendPacket(byte[] buf, int offset, int length) throws PcapException
      Transmit a packet.

      pcap_sendpacket() sends a raw packet through the network interface; buf points to the data of the packet, including the link-layer header, and size is the number of bytes in the packet. Note that, even if you successfully open the network interface, you might not have permission to send packets on it, or it might not support sending packets; as pcap_open_live(3PCAP) doesn't have a flag to indicate whether to open for capturing, sending, or capturing and sending, you cannot request an open that supports sending and be notified at open time whether sending will be possible. Note also that some devices might not support sending packets.

      Note that, on some platforms, the link-layer header of the packet that's sent might not be the same as the link-layer header of the packet supplied to pcap_sendpacket(), as the source link-layer address, if the header contains such an address, might be changed to be the address assigned to the interface on which the packet it sent, if the platform doesn't support sending completely raw and unchanged packets. Even worse, some drivers on some platforms might change the link-layer type field to whatever value libpcap used when attaching to the device, even on platforms that do nominally support sending completely raw and unchanged packets.

      Parameters:
      buf - array buffer containing packet data to send
      offset - the offset into the buf array
      length - the length number of bytes to send
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 0.8
    • sendPacket

      public final void sendPacket(ByteBuffer buf) throws PcapException
      Transmit a packet.

      pcap_sendpacket() sends a raw packet through the network interface; buf points to the data of the packet, including the link-layer header, and size is the number of bytes in the packet. Note that, even if you successfully open the network interface, you might not have permission to send packets on it, or it might not support sending packets; as pcap_open_live(3PCAP) doesn't have a flag to indicate whether to open for capturing, sending, or capturing and sending, you cannot request an open that supports sending and be notified at open time whether sending will be possible. Note also that some devices might not support sending packets.

      Note that, on some platforms, the link-layer header of the packet that's sent might not be the same as the link-layer header of the packet supplied to pcap_sendpacket(), as the source link-layer address, if the header contains such an address, might be changed to be the address assigned to the interface on which the packet it sent, if the platform doesn't support sending completely raw and unchanged packets. Even worse, some drivers on some platforms might change the link-layer type field to whatever value libpcap used when attaching to the device, even on platforms that do nominally support sending completely raw and unchanged packets.

      Parameters:
      buf - The packet starts relative to the buffer's position (inclusive) and ends relative to the buffer's limit (exclusive)
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 0.8
    • setBufferSize

      public Pcap setBufferSize(int bufferSize) throws PcapException
      Sets the buffer size for a not-yet- activated capture handle.

      sets the buffer size that will be used on a capture handle when the handle is activated to buffer_size, which is in units of bytes

      Parameters:
      bufferSize - the buffer size in units of bytes
      Returns:
      this pcap handle
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 1.0
    • setDatalink

      public Pcap setDatalink(int dlt) throws PcapException
      Set the link-layer header type to be used by a capture device .
      Parameters:
      dlt - link-layer header type
      Returns:
      this pcap handle
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 0.8
    • setDatalink

      public Pcap setDatalink(Optional<PcapDlt> dlt) throws PcapException
      Set the link-layer header type to be used by a capture device .
      Parameters:
      dlt - link-layer header type
      Returns:
      this pcap handle
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 0.8
    • setDatalink

      public Pcap setDatalink(PcapDlt dlt) throws PcapException
      Set the link-layer header type to be used by a capture device .
      Parameters:
      dlt - link-layer header type
      Returns:
      this pcap handle
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 0.8
    • setDirection

      public Pcap setDirection(int dir) throws PcapException

      pcap_setdirection() is used to specify a direction that packets will be captured. d is one of the constants PCAP_D_IN, PCAP_D_OUT or PCAP_D_INOUT. PCAP_D_IN will only capture packets received by the device, PCAP_D_OUT will only capture packets sent by the device and PCAP_D_INOUT will capture packets received by or sent by the device. PCAP_D_INOUT is the default setting if this function is not called. pcap_setdirection() isn't necessarily fully supported on all platforms; some platforms might return an error for all values, and some other platforms might not support PCAP_D_OUT.

      This operation is not supported if a ``savefile'' is being read.

      Parameters:
      dir - one of the constants PCAP_D_IN, PCAP_D_OUT or PCAP_D_INOUT
      Returns:
      this pcap handle
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 0.9
    • setDirection

      public Pcap setDirection(Optional<PcapDirection> dir) throws PcapException
      Set the direction for which packets will be captured.

      pcap_setdirection() is used to specify a direction that packets will be captured. d is one of the constants PCAP_D_IN, PCAP_D_OUT or PCAP_D_INOUT. PCAP_D_IN will only capture packets received by the device, PCAP_D_OUT will only capture packets sent by the device and PCAP_D_INOUT will capture packets received by or sent by the device. PCAP_D_INOUT is the default setting if this function is not called. pcap_setdirection() isn't necessarily fully supported on all platforms; some platforms might return an error for all values, and some other platforms might not support PCAP_D_OUT.

      This operation is not supported if a ``savefile'' is being read.

      Parameters:
      dir - one of the constants PCAP_D_IN, PCAP_D_OUT or PCAP_D_INOUT
      Returns:
      this pcap handle
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 0.9
    • setDirection

      public Pcap setDirection(PcapDirection dir) throws PcapException
      Set the direction for which packets will be captured.

      pcap_setdirection() is used to specify a direction that packets will be captured. d is one of the constants PCAP_D_IN, PCAP_D_OUT or PCAP_D_INOUT. PCAP_D_IN will only capture packets received by the device, PCAP_D_OUT will only capture packets sent by the device and PCAP_D_INOUT will capture packets received by or sent by the device. PCAP_D_INOUT is the default setting if this function is not called. pcap_setdirection() isn't necessarily fully supported on all platforms; some platforms might return an error for all values, and some other platforms might not support PCAP_D_OUT.

      This operation is not supported if a ``savefile'' is being read.

      Parameters:
      dir - one of the constants PCAP_D_IN, PCAP_D_OUT or PCAP_D_INOUT
      Returns:
      this pcap handle
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 0.9
    • setFilter

      public Pcap setFilter(BpFilter bpfProgram) throws PcapException
      set the filter.

      is used to specify a filter program.

      Parameters:
      bpfProgram - bpf_program struct, usually the result of a call to pcap_compile
      Returns:
      this pcap handle
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 0.4
    • setFilter

      public Pcap setFilter(Optional<BpFilter> bpfProgram) throws PcapException
      set the filter.

      is used to specify a filter program.

      Parameters:
      bpfProgram - bpf_program struct, usually the result of a call to pcap_compile
      Returns:
      this pcap handle
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 0.4
    • setImmediateMode

      public Pcap setImmediateMode(boolean enable) throws PcapException
      Set immediate mode for a not-yet- activated capture handle.

      sets whether immediate mode should be set on a capture handle when the handle is activated. In immediate mode, packets are always delivered as soon as they arrive, with no buffering. If immediate_mode is non-zero, immediate mode will be set, otherwise it will not be set.

      Parameters:
      enable - if true, enable immediate mode, otherwise disable
      Returns:
      this pcap handle
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 1.5
    • setNonBlock

      public Pcap setNonBlock(boolean blockMode) throws PcapException
      Sets the state of non-blocking mode on a capture device.

      pcap_setnonblock() puts a capture handle into ``non-blocking'' mode, or takes it out of ``non-blocking'' mode, depending on whether the nonblock argument is non-zero or zero. It has no effect on ``savefiles''. If there is an error, PCAP_ERROR is returned and errbuf is filled in with an appropriate error message; otherwise, 0 is returned. In ``non-blocking'' mode, an attempt to read from the capture descriptor with pcap_dispatch(3PCAP) and pcap_next_ex(3PCAP) will, if no packets are currently available to be read, return 0 immediately rather than blocking waiting for packets to arrive.

      pcap_loop(3PCAP) will loop forever, consuming CPU time when no packets are currently available; pcap_dispatch() should be used instead. pcap_next(3PCAP) will return NULL if there are no packets currently available to read; this is indistinguishable from an error, so pcap_next_ex() should be used instead.

      When first activated with pcap_activate(3PCAP) or opened with pcap_open_live(3PCAP), a capture handle is not in ``non-blocking mode''; a call to pcap_setnonblock() is required in order to put it into ``non-blocking'' mode.

      Parameters:
      blockMode - if true enable non blocking mode, otherwise block
      Returns:
      this pcap handle
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 10.7
    • setPromisc

      public Pcap setPromisc(boolean promiscousMode) throws PcapException
      Set promiscuous mode for a not-yet-activated capture handle.

      pcap_set_promisc() sets whether promiscuous mode should be set on a capture handle when the handle is activated. If promisc is non-zero, promiscuous mode will be set, otherwise it will not be set.

      Parameters:
      promiscousMode - if true enable promiscous mode, otherwise disable it
      Returns:
      this pcap handle
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 1.0
    • setRfmon

      public Pcap setRfmon(boolean rfMonitor) throws PcapException
      Set monitor mode for a not-yet-activated capture handle.

      Sets whether monitor mode should be set on a capture handle when the handle is activated. If rfmon is true, monitor mode will be set, otherwise it will not be set.

      Parameters:
      rfMonitor - the enable rfmon
      Returns:
      this pcap handle
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 1.0
    • setSnaplen

      public Pcap setSnaplen(int snaplen) throws PcapException
      Set the snapshot length for a not-yet-activated capture handle.

      pcap_set_snaplen() sets the snapshot length to be used on a capture handle when the handle is activated to snaplen.

      Parameters:
      snaplen - the snapshot length
      Returns:
      this pcap handle
      Throws:
      PcapException - the pcap exception
    • setTimeout

      public Pcap setTimeout(int timeoutInMillis) throws PcapException
      Set the packet buffer timeout for a not-yet-activated capture handle.

      pcap_set_timeout() sets the packet buffer timeout that will be used on a capture handle when the handle is activated to to_ms, which is in units of milliseconds. (See pcap(3PCAP) for an explanation of the packet buffer timeout.)

      The behavior, if the timeout isn't specified, is undefined, as is the behavior if the timeout is set to zero or to a negative value. We recommend always setting the timeout to a non-zero value unless immediate mode is set, in which case the timeout has no effect. *

      Parameters:
      timeoutInMillis - the timeout in milliseconds
      Returns:
      this pcap handle
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 1.0
    • setTstampPrecision

      public Pcap setTstampPrecision(PcapTStampPrecision precision) throws PcapException
      Set the time stamp precision returned in captures.

      pcap_set_tstamp_precision() sets the precision of the time stamp desired for packets captured on the pcap descriptor to the type specified by tstamp_precision. It must be called on a pcap descriptor created by pcap_create(3PCAP) that has not yet been activated by pcap_activate(3PCAP). Two time stamp precisions are supported, microseconds and nanoseconds. One can use options PCAP_TSTAMP_PRECISION_MICRO and PCAP_TSTAMP_PRECISION_NANO to request desired precision. By default, time stamps are in microseconds.

      Parameters:
      precision - one of the following constants PCAP_TSTAMP_PRECISION_MICRO and PCAP_TSTAMP_PRECISION_NANO
      Returns:
      this pcap handle
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 1.5
    • setTstampType

      public Pcap setTstampType(PcapTstampType type) throws PcapException
      Set the time stamp type to be used by a capture device.

      pcap_set_tstamp_type() sets the type of time stamp desired for packets captured on the pcap descriptor to the type specified by tstamp_type. It must be called on a pcap descriptor created by pcap_create(3PCAP) that has not yet been activated by pcap_activate(3PCAP). pcap_list_tstamp_types(3PCAP) will give a list of the time stamp types supported by a given capture device. See pcap-tstamp(7) for a list of all the time stamp types.

      Parameters:
      type - the type
      Returns:
      this pcap handle
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 1.2
    • snapshot

      public int snapshot() throws PcapException
      Get the snapshot length.

      snapshot returns the snapshot length specified when setSnaplen(int) or openLive(String, int, boolean, long, TimeUnit) was called, for a live capture, or the snapshot length from the capture file, for a ``savefile''.

      Returns:
      the snapshot length
      Throws:
      PcapException - the pcap exception
    • stats

      public PcapStat stats() throws PcapException
      Get capture statistics.

      pcap_stats() fills in the struct pcap_stat pointed to by its second argument. The values represent packet statistics from the start of the run to the time of the call.

      pcap_stats() is supported only on live captures, not on ``savefiles''; no statistics are stored in ``savefiles'', so no statistics are available when reading from a ``savefile''.

      A struct pcap_stat has the following members:

      ps_recv
      number of packets received;
      ps_drop
      number of packets dropped because there was no room in the operating system's buffer when they arrived, because packets weren't being read fast enough;
      ps_ifdrop
      number of packets dropped by the network interface or its driver.

      The statistics do not behave the same way on all platforms. ps_recv might count packets whether they passed any filter set with pcap_setfilter(3PCAP) or not, or it might count only packets that pass the filter. It also might, or might not, count packets dropped because there was no room in the operating system's buffer when they arrived. ps_drop is not available on all platforms; it is zero on platforms where it's not available. If packet filtering is done in libpcap, rather than in the operating system, it would count packets that don't pass the filter. Both ps_recv and ps_drop might, or might not, count packets not yet read from the operating system and thus not yet seen by the application. ps_ifdrop might, or might not, be implemented; if it's zero, that might mean that no packets were dropped by the interface, or it might mean that the statistic is unavailable, so it should not be treated as an indication that the interface did not drop any packets.

      Returns:
      the pcap stat
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 0.4
    • toString

      public String toString()
      Debug info about this pcap handle.
      Overrides:
      toString in class Object
      Returns:
      the string
      See Also:
    • getPcapHeaderABI

      public org.jnetpcap.internal.PcapHeaderABI getPcapHeaderABI()
      Gets the pcap header ABI (Abstract Binary Interface). Pcap ABI is used to interpret native structures such as pcap descriptor, correctly on any specific hardware platform. The ABI abstracts how native integers and primitive types are represented by CPU architecture on a specific platform.
      Returns:
      the ABI of the pcap header for this pcap handle on this CPU architecture
    • setUncaughtExceptionHandler

      public Pcap setUncaughtExceptionHandler(Consumer<? super Throwable> exceptionHandler)
      Sets the uncaught exception handler for loop(int, org.jnetpcap.PcapDumper) and dispatch(int, org.jnetpcap.PcapDumper) methods. Any exception thrown within the user callback methods, will be caught and sent to the specified user exception handler.
      Parameters:
      exceptionHandler - the exception handler
      Returns:
      this pcap
    • setUncaughtExceptionHandler

      public Pcap setUncaughtExceptionHandler(Thread.UncaughtExceptionHandler exceptionHandler)
      Sets the uncaught exception handler for loop(int, org.jnetpcap.PcapDumper) and dispatch(int, org.jnetpcap.PcapDumper) methods. Any exception thrown within the user callback methods, will be caught and sent to the specified user exception handler.
      Parameters:
      exceptionHandler - the exception handler
      Returns:
      this pcap