Module org.jnetpcap

Class WinPcap

All Implemented Interfaces:
AutoCloseable
Direct Known Subclasses:
Npcap

public sealed class WinPcap extends Pcap1_10 permits Npcap
WinPcap relies on preview features of the Java platform:
Programs can only use WinPcap when preview features are enabled.
Preview features may be removed in a future release, or upgraded to permanent features of the Java platform.
WinPcap is a wrapper around, windows packet capture library.

News - 15 September 2018

Native WinPcap, though still available for download (v4.1.3), has not seen an upgrade in many years and there are no road map/future plans to update the technology. While community support may persist, technical oversight by Riverbed staff, responses to questions posed by Riverbed resources, and bug reporting are no longer available.
Author:
Sly Technologies Inc, repos@slytechs.com, http://winpcap.org, Mark Bednarczyk
  • Field Details

    • WINPCAP_MODE_CAPT

      public static final int WINPCAP_MODE_CAPT
      The Constant WINPCAP_MODE_CAPT.
      See Also:
    • WINPCAP_MODE_STAT

      public static final int WINPCAP_MODE_STAT
      The Constant WINPCAP_MODE_STAT.
      See Also:
    • WINPCAP_MODE_MON

      public static final int WINPCAP_MODE_MON
      The Constant WINPCAP_MODE_MON.
      See Also:
  • Method Details

    • create

      public static WinPcap 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 Pcap1_0.activate() call
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 1.0
    • createSrcStr

      public static String createSrcStr(PcapSrc type, String host, String port, String name) throws PcapException
      Accept a set of strings (host name, port, ...), and it returns the complete source string according to the new format (e.g. 'rpcap://1.2.3.4/eth0').

      This function is provided in order to help the user creating the source string according to the new format. An unique source string is used in order to make easy for old applications to use the remote facilities. Think about tcpdump, for example, which has only one way to specify the interface on which the capture has to be started. However, GUI-based programs can find more useful to specify hostname, port and interface name separately. In that case, they can use this function to create the source string before passing it to the pcap_open() function.

      Parameters:
      type - its value tells the type of the source we want to create
      host - the host (e.g. "foo.bar.com") we want to connect to. It can be NULL in case we want to open an interface on a local host
      port - the network port (e.g. "2002") we want to use for the RPCAP protocol. It can be NULL in case we want to open an interface on a local host
      name - the interface name we want to use (e.g. "eth0"). It can be NULL in case the return string (i.e. 'source') has to be used with the pcap_findalldevs_ex(), which does not require the interface name.
      Returns:
      contain the complete source string
      Throws:
      PcapException - the pcap exception
    • 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 #openopen.

      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
    • 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:
    • openLive

      public static WinPcap 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
    • openDead

      public static WinPcap 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
    • openOffline

      public static WinPcap 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
    • parseSrcStr

      public static PcapRmt.Source parseSrcStr(String source) throws PcapException
      Parse the source string and returns the pieces in which the source can be split.

      This call is the other way round of pcap_createsrcstr(). It accepts a null-terminated string and it returns the parameters related to the source. This includes:

      • the type of the source (file, winpcap on a remote adapter, winpcap on local adapter), which is determined by the source prefix (PCAP_SRC_IF_STRING and so on)
      • the host on which the capture has to be started (only for remote captures)
      • the 'raw' name of the source (file name, name of the remote adapter, name of the local adapter), without the source prefix. The string returned does not include the type of the source itself (i.e. the string returned does not include "file://" or rpcap:// or such).
      Parameters:
      source - This source in the format (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/').
      Returns:
      parsed source string
      Throws:
      PcapException - the pcap exception
      Since:
      libpcap 1.9, early days of WinPcap
    • wsockInit

      public static int wsockInit()
      Initializes Winsock. on windows platforms (Windows only).

      Programs that don't call pcap_init() should, on Windows, call pcap_wsockinit() to initialize Winsock; this is not necessary if pcap_init() is called, as pcap_init() will initialize Winsock itself on Windows

      Returns:
      status full
    • getEvent

      public MemorySegmentPREVIEW getEvent() throws PcapException
      Return the handle of the event associated with the interface Pcap.

      This event can be passed to functions like WaitForSingleObject() or WaitForMultipleObjects() to wait until the driver's buffer contains some data without performing a read.

      We disourage the use of this function because it is not portable.

      Returns:
      the handle of the Windows event associated
      Throws:
      PcapException - the pcap exception
      Since:
      Microsoft Windows only
    • liveDump

      public void liveDump(String filename, int maxsize, int maxpacks) throws PcapException
      Save a capture to file.

      pcap_live_dump() dumps the network traffic from an interface to a file. Using this function the dump is performed at kernel level, therefore it is more efficient than using pcap_dump().

      The parameters of this function are an interface descriptor (obtained with pcap_open_live()), a string with the name of the dump file, the maximum size of the file (in bytes) and the maximum number of packets that the file will contain. Setting maxsize or maxpacks to 0 means no limit. When maxsize or maxpacks are reached, the dump ends.

      pcap_live_dump() is non-blocking, threfore Return immediately. pcap_live_dump_ended() can be used to check the status of the dump process or to wait until it is finished. pcap_close() can instead be used to end the dump process.

      Note that when one of the two limits is reached, the dump is stopped, but the file remains opened. In order to correctly flush the data and put the file in a consistent state, the adapter must be closed with pcap_close().

      Parameters:
      filename - the filename where to write the file
      maxsize - maximum size of the file (in bytes)
      maxpacks - maximum number of packets that the file will contain
      Throws:
      PcapException - the pcap exception
      Since:
      Microsoft Windows only
    • liveDumpEnded

      public boolean liveDumpEnded(boolean sync)
      Return the status of the kernel dump process, i.e. tells if one of the limits defined with pcap_live_dump() has been reached. pcap_live_dump_ended() informs the user about the limits that were set with a previous call to pcap_live_dump() on the interface pointed by p: if the return value is nonzero, one of the limits has been reched and the dump process is currently stopped. If sync is nonzero, the function blocks until the dump is finished, otherwise Return immediately.
      Warning!
      if the dump process has no limits (i.e. if the maxsize and maxpacks arguments of pcap_live_dump() were both 0), the dump process will never stop, therefore setting sync to TRUE will block the application on this call forever.
      Parameters:
      sync - the sync
      Returns:
      true, if successful
      Since:
      Microsoft Windows only
    • sendQueueTransmit

      public int sendQueueTransmit(PcapSendQueue queue, boolean sync)
      Transmit all packets in the send queue.

      This function transmits the content of a queue to the wire. p is a pointer to the adapter on which the packets will be sent, queue points to a pcap_send_queue structure containing the packets to send (see pcap_sendqueue_alloc() and pcap_sendqueue_queue()), sync determines if the send operation must be synchronized: if it is non-zero, the packets are sent respecting the timestamps, otherwise they are sent as fast as possible.

      The return value is the amount of bytes actually sent. If it is smaller than the size parameter, an error occurred during the send. The error can be caused by a driver/adapter problem or by an inconsistent/bogus send queue.

      Note: Using this function is more efficient than issuing a series of pcap_sendpacket(), because the packets are buffered in the kernel driver, so the number of context switches is reduced. Therefore, expect a better throughput when using pcap_sendqueue_transmit. When Sync is set to TRUE, the packets are synchronized in the kernel with a high precision timestamp. This requires a non-negligible amount of CPU, but allows normally to send the packets with a precision of some microseconds (depending on the accuracy of the performance counter of the machine). Such a precision cannot be reached sending the packets with pcap_sendpacket().

      Parameters:
      queue - the queue
      sync - if true, the packets are synchronized in the kernel with a high precision timestamp
      Returns:
      number of packets transmitted
      Since:
      Microsoft Windows only
    • setBuff

      public void setBuff(int dim) throws PcapException
      Set the size of the kernel buffer associated with an adapter.

      dim specifies the size of the buffer in bytes. The return value is 0 when the call succeeds, -1 otherwise. If an old buffer was already created with a previous call to pcap_setbuff(), it is deleted and its content is discarded. pcap_open_live() creates a 1 MByte buffer by default.

      Parameters:
      dim - size of the buffer in bytes
      Throws:
      PcapException - the pcap exception
      Since:
      Microsoft Windows only
    • setMinToCopy

      public void setMinToCopy(int size) throws PcapException
      Set the minumum amount of data received by the kernel in a single call.

      pcap_setmintocopy() changes the minimum amount of data in the kernel buffer that causes a read from the application to return (unless the timeout expires). If the value of size is large, the kernel is forced to wait the arrival of several packets before copying the data to the user. This guarantees a low number of system calls, i.e. low processor usage, and is a good setting for applications like packet-sniffers and protocol analyzers. Vice versa, in presence of a small value for this variable, the kernel will copy the packets as soon as the application is ready to receive them. This is useful for real time applications that need the best responsiveness from the kernel. pcap_open_live() sets a default mintocopy value of 16000 bytes.

      Parameters:
      size - minimum amount of data in the kernel buffer
      Throws:
      PcapException - the pcap exception
      Since:
      Microsoft Windows only
    • setMode

      public void setMode(int mode) throws PcapException
      Set the working mode of the interface p to mode.

      Valid values for mode are MODE_CAPT (default capture mode) and MODE_STAT (statistical mode).

      Parameters:
      mode - the new mode
      Throws:
      PcapException - the pcap exception
    • setMode

      public void setMode(WinPcapMode winPcapMode) throws PcapException
      Set the working mode of the interface p to mode.

      Valid values for mode are MODE_CAPT (default capture mode) and MODE_STAT (statistical mode).

      Parameters:
      winPcapMode - the new mode
      Throws:
      PcapException - the pcap exception
    • statsEx

      public PcapStatEx statsEx() throws PcapException
      Return statistics on current capture.

      pcap_stats_ex() extends the pcap_stats() allowing to return more statistical parameters than the old call. One of the advantages of this new call is that the pcap_stat structure is not allocated by the user; instead, it is returned back by the system. This allow to extend the pcap_stat structure without affecting backward compatibility on older applications. These will simply check at the values of the members at the beginning of the structure, while only newest applications are able to read new statistical values, which are appended in tail.

      To be sure not to read a piece of mamory which has not been allocated by the system, the variable pcap_stat_size will return back the size of the structure pcap_stat allocated by the system.

      Returns:
      the pcap stat ex
      Throws:
      PcapException - the pcap exception
      Since:
      Microsoft Windows only