SourceForge Jpcap

net.sourceforge.jpcap.capture
Class JWinPcap

java.lang.Object
  extended by net.sourceforge.jpcap.capture.PacketDispatcher
      extended by net.sourceforge.jpcap.capture.PacketCaptureBase
          extended by net.sourceforge.jpcap.capture.PacketCapture
              extended by net.sourceforge.jpcap.capture.JWinPcap
All Implemented Interfaces:
Closeable, PacketCaptureCapable, PacketDispatchCapable

public class JWinPcap
extends PacketCapture

The JWinPcap class encapsulates the extended functions supported by the WinPcap native library. For obvious reasons it is only available under Windows and any other platforms that may support them. Execution on any platform that doesn't support these extensions will cause an UnsupportedOperationException.

Since:
2.0.0
Version:
$Revision: 1.1 $
Author:
Esmond Pitt

Nested Class Summary
static class JWinPcap.CaptureMode
          Capture mode, for use with setCaptureMode().
static class JWinPcap.OpenFlags
          Open flags, for use with open().
static class JWinPcap.SamplingMethod
          Sampling method for use with setSamplingMethod().
 
Nested classes/interfaces inherited from class net.sourceforge.jpcap.capture.PacketCapture
PacketCapture.Direction, PacketCapture.LoopMode
 
Field Summary
static int DEFAULT_BUFFER_SIZE
          Default buffer size for output streams that write to the network.
static int PCAP_SRC_FILE
          Internal representation of the type of source in use (file, remote/local interface).
static String PCAP_SRC_FILE_STRING
          This string indicates that the user wants to open a capture from a local file.
static String PCAP_SRC_IF_STRING
          This string indicates that the user wants to open a capture from a network interface.
static int PCAP_SRC_IFLOCAL
          This indicates a local interface: the user want to open a capture from a local interface.
static int PCAP_SRC_IFREMOTE
          This indicates a remote interface: the user want to open a capture from an interface on a remote host.
 
Fields inherited from class net.sourceforge.jpcap.capture.PacketCapture
LIB_PCAP_WRAPPER, MAX_SNAPLEN
 
Fields inherited from class net.sourceforge.jpcap.capture.PacketCaptureBase
linkType
 
Fields inherited from interface net.sourceforge.jpcap.capture.PacketCaptureCapable
DEFAULT_SNAPLEN, DEFAULT_TIMEOUT
 
Constructor Summary
JWinPcap()
          Creates a new default instance of JWinPcap.
JWinPcap(CaptureDevice device, EnumSet<JWinPcap.OpenFlags> flags, PasswordAuthentication auth)
          Creates a new instance of JWinPcap with default values for snaplen and timeout.
JWinPcap(CaptureDevice device, int snaplen, EnumSet<JWinPcap.OpenFlags> flags, int timeout, PasswordAuthentication auth)
          Creates a new instance of JWinPcap
JWinPcap(File file)
          Creates a new instance of JWinPcap
 
Method Summary
 void addStatisticsListener(StatisticsListener listener)
          Add a StatisticsListener.
 void close()
           Close cleans up after a packet capture session.
static CaptureDevice findCaptureDevice()
          Returns the first non-loopback device found by lookupCaptureDevices().
 int getBufferSize()
          Return the kernel buffer size.
 JWinPcap.CaptureMode getCaptureMode()
          Return the current capture mode.
 int getMinimumKernelCopy()
          Fetch the minimum amount of data sent by the kernel in a single call.
 PacketOutputStream getOutputStream()
          Return a PacketOutputStream that sends packets to the network device opened by this PacketCapture.
 PacketOutputStream getOutputStream(int bufferSize, boolean timed)
          Return a buffered packet output stream.
 JWinPcap.SamplingMethod getSamplingMethod()
          Get the current sampling method.
 int getSamplingValue()
          Get the current sampling value.
protected  void handlePacket(int length, int caplen, int seconds, int useconds, ByteBuffer bb)
          Handle arriving packets.
 boolean isFilteredOffline(CompiledFilter filter, Packet packet)
          Return true iff the specified filter would filter the specified packet.
static boolean isSupported()
          Return true iff the other methods of this class are supported on this platform.
static CaptureDevice[] lookupCaptureDevices()
          Lookup capture devices.
static CaptureDevice[] lookupCaptureDevices(URI uri)
          Lookup capture devices.
 void open(String name, boolean promiscuous)
          Open a network device for data capture.
 void open(String name, int snaplen, boolean promiscuous, int timeout)
          Open a network device for data capture.
 void open(String name, int snaplen, EnumSet<JWinPcap.OpenFlags> flags, int timeout, PasswordAuthentication auth)
          Open a capture device or file.
 void openOffline(String filename)
          Open a tcpdump-formatted savefile for reading.
 void removeStatisticsListener(StatisticsListener listener)
          Remove a StatisticsListener.
 void setBufferSize(int bufferSize)
          Set the size of the kernel buffer associated with an adapter.
 void setCaptureMode(JWinPcap.CaptureMode mode)
          Set the capture mode.
 void setMinimumKernelCopy(int minToCopy)
          Set the minimum amount of data sent by the kernel in a single call.
 void setSamplingMethod(JWinPcap.SamplingMethod method, int value)
          Define a sampling method for packet capture.
 
Methods inherited from class net.sourceforge.jpcap.capture.PacketCapture
capture, captureNext, captureTo, compileFilter, configureBlocking, endCapture, finalize, findDevice, getDevice, getInputStream, getLibVersion, getLinkLayerDescription, getLinkLayerDescription, getLinkLayerName, getLinkLayerName, getLinkLayerType, getLinkLayerTypes, getLoopMode, getNetmask, getNetwork, getOutputStream, getSnapshotLength, getStatistics, isBlocking, isClosed, lookupDevices, open, open, setDirection, setFilter, setFilter, setLinkLayerType, setLoopMode
 
Methods inherited from class net.sourceforge.jpcap.capture.PacketDispatcher
addPacketListener, addRawPacketListener, removePacketListener, removeRawPacketListener
 
Methods inherited from class java.lang.Object
clone, equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 
Methods inherited from interface net.sourceforge.jpcap.capture.PacketCaptureCapable
addPacketListener, addRawPacketListener, removePacketListener, removeRawPacketListener
 

Field Detail

DEFAULT_BUFFER_SIZE

public static final int DEFAULT_BUFFER_SIZE
Default buffer size for output streams that write to the network. #see #getOutputStream()

See Also:
Constant Field Values

PCAP_SRC_FILE

public static final int PCAP_SRC_FILE
Internal representation of the type of source in use (file, remote/local interface).

See Also:
Constant Field Values

PCAP_SRC_IFLOCAL

public static final int PCAP_SRC_IFLOCAL
This indicates a local interface: the user want to open a capture from a local interface. This does not involve the RPCAP protocol.

See Also:
Constant Field Values

PCAP_SRC_IFREMOTE

public static final int PCAP_SRC_IFREMOTE
This indicates a remote interface: the user want to open a capture from an interface on a remote host. This does involve the RPCAP protocol.

See Also:
Constant Field Values

PCAP_SRC_FILE_STRING

public static final String PCAP_SRC_FILE_STRING
This string indicates that the user wants to open a capture from a local file.

See Also:
Constant Field Values

PCAP_SRC_IF_STRING

public static final String PCAP_SRC_IF_STRING
This string indicates that the user wants to open a capture from a network interface. This string does not necessarily involve the use of the RPCAP protocol. If the interface required resides on the local host, the RPCAP protocol is not involved and the local functions are used.

See Also:
Constant Field Values
Constructor Detail

JWinPcap

public JWinPcap()
Creates a new default instance of JWinPcap.


JWinPcap

public JWinPcap(CaptureDevice device,
                EnumSet<JWinPcap.OpenFlags> flags,
                PasswordAuthentication auth)
         throws CaptureDeviceOpenException
Creates a new instance of JWinPcap with default values for snaplen and timeout.

Parameters:
device - Capture device as returned by findCaptureDevice() or lookupCaptureDevices().
flags - Open flags, see JWinPcap.OpenFlags
auth - Password authentication object, or null.
Throws:
CaptureDeviceOpenException - Problem opening the specified capture device.

JWinPcap

public JWinPcap(CaptureDevice device,
                int snaplen,
                EnumSet<JWinPcap.OpenFlags> flags,
                int timeout,
                PasswordAuthentication auth)
         throws CaptureDeviceOpenException
Creates a new instance of JWinPcap

Parameters:
device - Capture device as returned by findCaptureDevice() or lookupCaptureDevices().
snaplen - Snapshot length
flags - Open flags, see JWinPcap.OpenFlags
timeout - Timeout before packet driver starts notifying packet listeners
auth - Password authentication object, or null.
Throws:
CaptureDeviceOpenException - Problem opening the specified capture device.

JWinPcap

public JWinPcap(File file)
         throws CaptureDeviceOpenException
Creates a new instance of JWinPcap

Parameters:
file - tcpdump-formatted savefile to capture from
Throws:
CaptureDeviceOpenException
Method Detail

close

public void close()
Description copied from interface: PacketCaptureCapable
Close cleans up after a packet capture session. It does not terminate a packet capture. PacketCaptureCapable.capture(int) does not return control until 'count' packets are captured.

To signal an end to a capture session before the specified number of packets has been received, first call PacketCaptureCapable.endCapture().

Specified by:
close in interface Closeable
Specified by:
close in interface PacketCaptureCapable
Overrides:
close in class PacketCapture

findCaptureDevice

public static CaptureDevice findCaptureDevice()
                                       throws CaptureDeviceNotFoundException,
                                              CaptureConfigurationException
Returns the first non-loopback device found by lookupCaptureDevices().

Returns:
a CaptureDevice. TODO there should be a version of this that takes host/port/protocol.
Throws:
CaptureDeviceNotFoundException
CaptureConfigurationException

getOutputStream

public PacketOutputStream getOutputStream()
                                   throws IOException
Return a PacketOutputStream that sends packets to the network device opened by this PacketCapture. Repeated calls against the same captor return the same networkOutputStream.

This override calls getOutputStream(int, boolean), with the values DEFAULT_BUFFER_SIZE and false, returning a buffered PacketOutputStream.

Overrides:
getOutputStream in class PacketCapture
Returns:
a packet networkOutputStream.
Throws:
IOException - I/O problem, e.g. the capture device or file is closed.
See Also:
getOutputStream(int, boolean)

getOutputStream

public PacketOutputStream getOutputStream(int bufferSize,
                                          boolean timed)
                                   throws IOException
Return a buffered packet output stream. This is a wrapper for the WinPcap pcap_sendqueue_* family of functions. The output stream is buffered and auto-flushed when bufferSize is reached. This stream is more efficient than the PacketOutputStream returned by PacketCapture.getOutputStream(), because the packets are buffered in the pcap_sendqueue at the JNI/WinPcap level, before being passed to the kernel driver in a single operation when OutputStream.flush() is called (whether internally or by the application), so the number of context switches can be reduced considerably. Therefore, you can expect much better packet throughput.

Parameters:
bufferSize - Size of underlying packet queue.
timed - If true, packets are sent respecting the intervals between the packet timestamps; if false, they are sent as fast as possible.
Returns:
a buffered PacketOutputStream
Throws:
IOException
Since:
2.0.0.

isFilteredOffline

public boolean isFilteredOffline(CompiledFilter filter,
                                 Packet packet)
                          throws InvalidFilterException
Return true iff the specified filter would filter the specified packet.

Parameters:
filter - Filter string
packet - Packet to test
Returns:
true if the filter filters the packet.
Throws:
InvalidFilterException

isSupported

public static boolean isSupported()
Return true iff the other methods of this class are supported on this platform.

Returns:
true or false.

lookupCaptureDevices

public static CaptureDevice[] lookupCaptureDevices()
                                            throws CaptureDeviceLookupException,
                                                   CaptureConfigurationException
Lookup capture devices. The CaptureDevice objects returned by this call can only be used with constructors and methods of this class where they override methods of PacketCapture.

Throws:
CaptureDeviceLookupException
CaptureConfigurationException

lookupCaptureDevices

public static CaptureDevice[] lookupCaptureDevices(URI uri)
                                            throws CaptureDeviceLookupException,
                                                   CaptureConfigurationException
Lookup capture devices. The CaptureDevice objects returned by this call can only be used with constructors and methods of this class.

Parameters:
uri - URI, of the form protocol:// host, or host:port, or file://directory.
Throws:
CaptureDeviceLookupException
CaptureConfigurationException

open

public void open(String name,
                 boolean promiscuous)
          throws CaptureDeviceOpenException
Description copied from class: PacketCapture
Open a network device for data capture.

This call is equivalent to


        open(device, DEFAULT_SNAPLEN, promiscuous, DEFAULT_TIMEOUT);

Specified by:
open in interface PacketCaptureCapable
Overrides:
open in class PacketCapture
Parameters:
name - the name of the network device.
promiscuous - whether or not the device should be put into 'promiscuous' mode: true => capture all packets; false => capture packets only to and from this system.
Throws:
CaptureDeviceOpenException
See Also:
PacketCaptureCapable.open(String, int, boolean, int)

open

public void open(String name,
                 int snaplen,
                 boolean promiscuous,
                 int timeout)
          throws CaptureDeviceOpenException
Open a network device for data capture.

Calling this method is equivalent to calling open(name, snaplen, flags, timeout, null) where flags is either EnumSet.of(OpenFlags.Promiscuous) or EnumSet.noneOf(OpenFlags.class) depending on whether promiscuous is true or false.

Specified by:
open in interface PacketCaptureCapable
Overrides:
open in class PacketCapture
Parameters:
name - the name of the network device. Examples of valid network devices on linux are 'eth0' and 'ppp0'.
snaplen - the 'snapshot' length. Defines the maximum number of bytes to save from each captured packet.
promiscuous - whether or not the device should be put into 'promiscuous' mode: true => capture all packets; false => capture packets only to and from this system.
timeout - the packet capture timeout in milliseconds. Defines the maximum amount of time that capture will wait for another packet, if the capture device's buffer isn't full, before notifying the application of the packets already captured. A value of zero means return each packet immediately: this mode is rather inefficient. Timeouts of 500ms-2 seconds are reasonable, or longer if the application can wait longer.
Throws:
CaptureDeviceOpenException - can't open the specified device

open

public void open(String name,
                 int snaplen,
                 EnumSet<JWinPcap.OpenFlags> flags,
                 int timeout,
                 PasswordAuthentication auth)
          throws CaptureDeviceOpenException
Open a capture device or file.

Parameters:
name - Device name as returned by CaptureDevice.getName(), or a file:// URI string of a tcpdump-formatted savefile.
snaplen - Snapshot length
flags - Open flags
timeout - Timeout before calling the listener, to allow the kernel to pass more than one packet into user space at a time
auth - PasswordAuthentication
Throws:
CaptureDeviceOpenException - Problem opening the specified device or file.

openOffline

public void openOffline(String filename)
                 throws CaptureFileOpenException
Description copied from class: PacketCapture
Open a tcpdump-formatted savefile for reading.

Specified by:
openOffline in interface PacketCaptureCapable
Overrides:
openOffline in class PacketCapture
Parameters:
filename - the name of the savefile.
Throws:
CaptureFileOpenException - can't open the specified file

getBufferSize

public int getBufferSize()
Return the kernel buffer size.

Returns:
the kernel buffer size.
See Also:
setBufferSize(int)

setBufferSize

public void setBufferSize(int bufferSize)
                   throws IOException
Set the size of the kernel buffer associated with an adapter.

Parameters:
bufferSize - specifies the size of the buffer in bytes. If an old buffer was already created with a previous call to setBufferSize(), it is deleted and its content is discarded. open(java.lang.String, boolean) creates a 1 MByte buffer by default.
Throws:
IOException
See Also:
getBufferSize()

getCaptureMode

public JWinPcap.CaptureMode getCaptureMode()
Return the current capture mode.

Returns:
the capture mode.

setCaptureMode

public void setCaptureMode(JWinPcap.CaptureMode mode)
                    throws IllegalArgumentException
Set the capture mode.

Parameters:
mode - Capture mode
Throws:
IllegalArgumentException

addStatisticsListener

public void addStatisticsListener(StatisticsListener listener)
Add a StatisticsListener. This method is thread-safe, and safe to call during a StatisticsListener.statisticsArrived() callback.

Parameters:
listener - Listener to add

removeStatisticsListener

public void removeStatisticsListener(StatisticsListener listener)
Remove a StatisticsListener. This method is thread-safe, and safe to call during a StatisticsListener.statisticsArrived() callback.

Parameters:
listener - Listener to remove

handlePacket

protected void handlePacket(int length,
                            int caplen,
                            int seconds,
                            int useconds,
                            ByteBuffer bb)
Handle arriving packets.

Arriving packets are dispatched to registered packet listeners. If caplen is smaller than length, then the packet was truncated because the amount of data on the wire exceeded the snapshot length specified when open() was called.

In the simulator case, fake packets are generated and this method called with the fabricated data. In the case of the capture system, the native library libjpcap calls the method back.

PacketHandler.handlePacket override, to generate statistics events.

Overrides:
handlePacket in class PacketCaptureBase
Parameters:
length - the length of the packet off of the wire.
caplen - the number of bytes actually captured.
seconds - the seconds component of the timestamp.
useconds - the microseconds component of the timestamp.
bb - the contents of the captured packet in a direct ByteBuffer: note that the direct content must be copied out immediately, because it is only valid for the duration of this callback.

getMinimumKernelCopy

public int getMinimumKernelCopy()
Fetch the minimum amount of data sent by the kernel in a single call.

Returns:
Minimum amount of packet data to accumulate before calling listeners.
See Also:
setMinimumKernelCopy(int)

setMinimumKernelCopy

public void setMinimumKernelCopy(int minToCopy)
                          throws IOException
Set the minimum amount of data sent by the kernel in a single call. This method 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 await 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.

Note that the Winpcap documentation of the corresponding pcap_setmintocopy() function, from which the above is taken, is incorrect: it defines the minimum amount of data to copy from the kernel.

Parameters:
minToCopy - Minimum amount of packet data to accumulate before calling listeners.
Throws:
IOException - Problem changing the minimum kernel copy quantum.
See Also:
getMinimumKernelCopy()

getSamplingMethod

public JWinPcap.SamplingMethod getSamplingMethod()
Get the current sampling method.

Returns:
the current sampling method, as per setSamplingMethod(net.sourceforge.jpcap.capture.JWinPcap.SamplingMethod, int).

getSamplingValue

public int getSamplingValue()
Get the current sampling value.

Returns:
the current sampling value, as per setSamplingMethod(net.sourceforge.jpcap.capture.JWinPcap.SamplingMethod, int).

setSamplingMethod

public void setSamplingMethod(JWinPcap.SamplingMethod method,
                              int value)
Define a sampling method for packet capture. This takes effect when you have called setCaptureMode(net.sourceforge.jpcap.capture.JWinPcap.CaptureMode) with mode = JWinPcap.CaptureMode.Statistical.

This function applies a sampling method to the packet capture process. The parameters will be applied as soon as the capture starts.

Warning: Sampling parameters cannot be changed when a capture is active. These parameters must be applied before starting the capture. If they are applied when the capture is in progress, the new settings are ignored.

Sampling works only when capturing data on Win32 or reading from a file. It has not been implemented on other platforms. Sampling works on remote machines provided that the probe (i.e. the capturing device) is a Win32 workstation.

Parameters:
method - Sampling method.
value - Value for N in the sampling method.

Copyright © Patrick Charles & Jonas Lehmann, 2001; Esmond Pitt, 2008.