org.jnetpcap
Class Pcap

java.lang.Object
  extended by org.jnetpcap.Pcap
Direct Known Subclasses:
WinPcap

public class Pcap
extends java.lang.Object

This class is the main class peered with native pcap_t structure in libpcap and winpcap library impelementations. It provides a direct mapping of various library methods from Java.

Getting started

Pcap class provides several static methods which allow discovery of networking interfaces and then subsequently open up either openLive, openDead or openOffline pcap capture sessions. In all 3 cases a Pcap object is returned. The object is backed by a C pcap_t structure outside of java VM address space. Any non-static operations on the Pcap object, are translated using java JNI API into corresponding Libpcap C calls and the appropriate pcap_t C structure is supplied to complete the call.

After aquiring a Pcap object from above mentioned static methods, you must call on close() call to release any Libpcap resources and the backing C structure. The Pcap object does implicitly call the close() method from its finalize() method, but that will only happen when the Pcap is garabage collected. Its best practice to remember to always call on close() when Pcap object and capture session is no longer needed.

If Pcap object is closed and any of its non-static methods are called on, after the close, IllegalStateException will be thrown.

Getting a list of network interfaces from Pcap

Lets get started with little example on how to inquire about available interfaces, ask the user to pick one of those interfaces for us, open it for capture, compile and install a capture filter and then start processing some packets captured as a result. This is all loosely based on examples you will find on tcpdump.org website but updated for jNetPCAP. As with libpcap, we first want to find out and get network interface names so we can tell jNetPCAP to open one or more for reading. So first we inquire about the list of interfaces on the system:
 StringBuilder errbuf = new StringBuilder();
 List<PcapIf> ifs = new ArrayList<PcapIf>(); // Will hold list of devices
 int statusCode = Pcap.findAllDevs(ifs, errbuf);
 if (statusCode != Pcap.OK) {
        System.out.println("Error occured: " + errbuf.toString());
        return;
 }
 // We have a list of PcapIf devices to work with now.
 
 

Note: the return value from findAllDevs(java.util.List, java.lang.StringBuilder) is an integer result code, just like in the C counter part. The ifs list is filled in with all the network devices as found from the corresponding C structure pcap_if linked list returned from the C function call findAllDevs.

Now that we have a list of devices, we we print out the list of them and ask the user to pick one to open for capture:

 for (int i = 0; i < ifs.size(); i++) {
        System.out.println("#" + i + ": " + ifs.get(i).getName());
 }
 
 String l = System.in.readline().trim();
 Integer i = Integer.valueOf(l);
 
 PcapIf netInterface = ifs.get(i);
 

Opening a network interface for live capture

Next we open up a live capture from the network interface using openLive(String, int, int, int, StringBuilder):
 int snalen = 2048; // Truncate packet at this size
 
 int promiscous = Pcap.MODE_PROMISCUOUS;
 
 int timeout = 60 * 1000; // In milliseconds
 
 Pcap pcap =
     Pcap.openLive(netInterface.getName(), snaplen, promiscous, timeout, errbuf);
 
Last argument is a buffer that will hold an error string, if error occures. On error openLive will return null.

Compiling and applying a filter to network interface

Once we have an open interface for capture we can apply a filter to reduce amount of packets captured to something that is interesting to us:
 PcapBpfProgram filter = new PcapBpfProgram();
 String expression = "port 23"
 int optimize = 0; // 1 means true, 0 means false
 int netmask = 0;
 
 int r = pcap.compile(filter, expression, optimize, netmask);
 if (r != Pcap.OK) {
   System.out.println("Filter error: " + pcap.getErr());
 }
 pcap.setFilter(filter);
 

If filter expression contained a syntax error, the return code will be -1 and exact error message can be retrieved using getErr() method.

Note of caution: the PcapBpfProgram at the top of the previous code section, can not be accessed until successfully filled in with values in the pcap.compile code. If you try and access any of its methods an IllegalStateException will be thrown. Only after a successful call to compile does the object become usable. The object is peered with C structure and until properly intialized, can not be accessed from java.

Dispatcher to receive packets as they arrive

And lastly lets do something with the data.
 
 PcapHandler handler = new PcapHandler() {
 
        public void newPacket(Object userData, int caplen, int len, int seconds,
            int usecs, ByteBuffer buffer) {
 
                PrintStream out = (PrintStream) userData;
                out.println("Packet captured on: " + new Date(seconds * 1000).toString());
        }
 };
 
 int cnt = 10; // Capture packet count
 PrintStream out = System.out; // Our custom object to send into the handler
 
 pcap.loop(cnt, handler, out); // Each packet will be dispatched to the handler
 
 pcap.close();
 

This sets up PCAP to capture 10 packets and notify our handler of each packet as each one is captured. Then after 10 packets the loop exits and we call pcap.close() to free up all the resources and we can safely throw away our pcap object. Also you may be curious why we pass System.out as userData to the loop handler. This is simply to demonstrate the typical usage for this kind of parameter. In our case we could easily pass a different PrintStream bound to lets say a network socket and our handler would produce output to it.

Alternative way of capturing packets from any of the open pcap sessions is to use dispatch(int, PcapHandler, Object) method, which works very similarly to loop(int, PcapHandler, Object). You can also use next(PcapPktHdr) and nextEx(PcapPktHdr, PcapPktBuffer) methods which will deliver 1 packet at a time.

No packet data copies!

The packet data is delivered in a java.nio.ByteBuffer. The data is not copied into the buffer, but a direct byte buffer is allocated and wrapped around the packet data as returned from libpcap. No in memory copies are performed, so if the native operating system supports no-copy packet captures, the packet are delived to Java without copies. Only a single ByteBuffer object allocation is incured.

Omitted methods from standard lipcap API

Certain deprecated methods from libpcap API have been omitted such as lookupDev, lookupNet. Also any methods that return FILE * since that is not appropriate for java environment.

Author:
Mark Bednarczyk, Sly Technologies, Inc.

Field Summary
static int DISPATCH_BUFFER_FULL
          Value of packet count argument for dispatch method call which indicates that only as many packets should be returned as will fit in a single buffer , unless an error occured or breakloop call was used to interrupt the dispatcher.
static java.lang.String JNETPCAP_LIBRARY_NAME
          Name of the native library that wraps around libpcap and extensions
static int LOOP_INFINATE
          Value of packet count argument for loop method call which indicates that the loop should never exit, unless an error occured or breakloop call was used to interrupt the dispatcher.
static int LOOP_INTERRUPTED
          Pcap status return code for loop and dispatch methods.
static int MODE_BLOCKING
          Flag which can be used with setNonBlock method to set the previously opened pcap descriptor into 'blocking' mode.
static int MODE_NON_BLOCKING
          Flag which can be used with setNonBlock method to set the previously opened pcap descriptor into 'non-blocking' mode.
static int MODE_NON_PROMISCUOUS
          Flag used with openLive to specify that the interface should not be put into promisuous mode, but only if poassible.
static int MODE_PROMISCUOUS
          Flag used with openLive to specify that the interface should be put into promisuous mode.
static int NEXT_EX_EOF
          Exit code for nextEx method which indicates that pcap reached end of file while reading a 'savefile'.
static int NEXT_EX_NOT_OK
          Exit code for nextEx method which indicates failure of some kind.
static int NEXT_EX_OK
          Exit code for nextEx method which indicates success.
static int NEXT_EX_TIMEDOUT
          Exit code for nextEx method which indicates timeout has expired before a packet was captured.
static int NOT_OK
          Pcap status return code for most of the methods defined here.
static int OK
          Pcap status return code for most of the methods defined here.
 
Constructor Summary
Pcap()
          Pcap object can only be created by calling one of the static openLive(java.lang.String, int, int, int, java.lang.StringBuilder) methods.
 
Method Summary
 void breakloop()
           set a flag that will force pcap_dispatch() or pcap_loop() to return rather than looping.
protected  void checkIsActive()
          Checks if the current Pcap structure is active and open.
 void close()
          pcap_close() closes the files associated with p and deallocates resources.
 int compile(PcapBpfProgram program, java.lang.String str, int optimize, int netmask)
          Compile a packet filter, converting a high level filtering expression in to a progra that can be interpreted by the kernel-level filtering engine.
static int compileNoPcap(int snaplen, int dlt, PcapBpfProgram program, java.lang.String str, int optimize, int netmask)
           Compile a packet filter without the need of opening an adapter.
 int datalink()
          Returns the link layer of an adapter.
static int datalinkNameToVal(java.lang.String name)
          Translates a data link type name, which is a DLT_ name with the DLT_ removed, to the corresponding data link type value.
static java.lang.String datalinkValToDescription(int dlt)
          Translates a data link type value to a short description of that data link type.
static java.lang.String datalinkValToName(int dlt)
          Translates a data link type value to the corresponding data link type name.
<T> int
dispatch(int cnt, PcapHandler<T> handler, T user)
           Collect a group of packets.
 PcapDumper dumpOpen(java.lang.String fname)
          Open a file to write packets.
protected  void finalize()
          Cleanup before we're GCed.
static int findAllDevs(java.util.List<PcapIf> alldevs, java.lang.StringBuilder errbuf)
          pcap_findalldevs() constructs a list of network devices that can be opened with pcap_open_live().
static void freeAllDevs(java.util.List<PcapIf> alldevs, byte[] errbuf)
          This method does nothing.
static void freecode(PcapBpfProgram program)
          This frees up the code structures, but does not released the peered base bpf_program peer structure.
 java.lang.String getErr()
          return the error text pertaining to the last pcap library error.
 int getNonBlock(java.lang.StringBuilder errbuf)
          pcap_getnonblock() returns the current ``non-blocking'' state of the capture descriptor; it always returns 0 on ``savefiles''.
 int inject(byte[] buf)
          This method allows to send a raw packet to the network.
 int inject(byte[] buf, int offset, int length)
          This method allows to send a raw packet to the network.
 int inject(java.nio.ByteBuffer buf)
          This method allows to send a raw packet to the network.
static boolean isInjectSupported()
          Checks if the current platform has support for pcap_inject call.
static boolean isSendPacketSupported()
          Checks if the current platform has support for pcap_sendpacket call.
 int isSwapped()
          returns true if the current savefile uses a different byte order than the current system
static java.lang.String libVersion()
          Returns a pointer to a string giving information about the version of the libpcap library being used; note that it contains more information than just a version number
static java.lang.String lookupDev(java.lang.StringBuilder errbuf)
          Returns a network device suitable for use with openLive and lookupNet.
static int lookupNet(java.lang.String device, PcapInteger netp, PcapInteger maskp, java.lang.StringBuilder errbuf)
          Determines the network number and mask associated with the network device.
<T> int
loop(int cnt, PcapHandler<T> handler, T user)
          Collect a group of packets.
 int majorVersion()
          Return the major version number of the pcap library used to write the savefile.
 int minorVersion()
          Return the minor version number of the pcap library used to write the savefile.
 java.nio.ByteBuffer next(PcapPktHdr pkt_header)
          Return the next available packet.
 int nextEx(PcapPktHdr pkt_header, PcapPktBuffer buffer)
          Read a packet from an interface or from an offline capture.
static Pcap openDead(int linktype, int snaplen)
          Create a pcap_t structure without starting a capture.
static Pcap openLive(java.lang.String device, int snaplen, int promisc, int timeout, java.lang.StringBuilder errbuf)
           Open a live capture associated with the specified network interface device.
static Pcap openOffline(java.lang.String fname, java.lang.StringBuilder errbuf)
          Open a savefile in the tcpdump/libpcap format to read packets.
 int sendPacket(byte[] buf)
          This method allows to send a raw packet to the network.
 int sendPacket(byte[] buf, int offset, int length)
          This method allows to send a raw packet to the network.
 int sendPacket(java.nio.ByteBuffer buf)
          This method allows to send a raw packet to the network.
 int setDatalink(int dlt)
          Set the current data link type of the pcap descriptor to the type specified by dlt.
 int setFilter(PcapBpfProgram program)
          Associate a filter to a capture.
 int setNonBlock(int nonBlock, java.lang.StringBuilder errbuf)
          pcap_setnonblock() puts a capture descriptor, opened with pcap_open_live(), into ``non-blocking'' mode, or takes it out of ``non-blocking'' mode, depending on whether the nonblock argument is non-zero or zero.
 int snapshot()
          Return the dimension of the packet portion (in bytes) that is delivered to the application.
 int stats(PcapStat stats)
          Returns statistics on the current capture.
 java.lang.String toString()
          Prints libVersion that Pcap is based on.
 
Methods inherited from class java.lang.Object
clone, equals, getClass, hashCode, notify, notifyAll, wait, wait, wait
 

Field Detail

DISPATCH_BUFFER_FULL

public static final int DISPATCH_BUFFER_FULL
Value of packet count argument for dispatch method call which indicates that only as many packets should be returned as will fit in a single buffer , unless an error occured or breakloop call was used to interrupt the dispatcher. Note, that this constant is only appropriate value for dispatch method call. Loop method uses LOOP_INFINATE for something similar, but definately not identical to this option.

See Also:
Constant Field Values

JNETPCAP_LIBRARY_NAME

public static final java.lang.String JNETPCAP_LIBRARY_NAME
Name of the native library that wraps around libpcap and extensions

See Also:
Constant Field Values

LOOP_INFINATE

public static final int LOOP_INFINATE
Value of packet count argument for loop method call which indicates that the loop should never exit, unless an error occured or breakloop call was used to interrupt the dispatcher. Note, that this constant is not appropriate value for dispatch method call, which has a different meaning.

See Also:
Constant Field Values

LOOP_INTERRUPTED

public static final int LOOP_INTERRUPTED
Pcap status return code for loop and dispatch methods. This status code indicates that the the dispatcher was interrupted by a call to breakloop call.

See Also:
Constant Field Values

MODE_BLOCKING

public static final int MODE_BLOCKING
Flag which can be used with setNonBlock method to set the previously opened pcap descriptor into 'blocking' mode. The flag can also be the return code from getNonBlock. The flag has no affect on 'savefiles'.

See Also:
Constant Field Values

MODE_NON_BLOCKING

public static final int MODE_NON_BLOCKING
Flag which can be used with setNonBlock method to set the previously opened pcap descriptor into 'non-blocking' mode. The flag can also be the return code from getNonBlock. The flag has no affect on 'savefiles'.

See Also:
Constant Field Values

MODE_NON_PROMISCUOUS

public static final int MODE_NON_PROMISCUOUS
Flag used with openLive to specify that the interface should not be put into promisuous mode, but only if poassible. Note, the even though the flag is specified, the interface could still be opened in promiscous mode for other reasons, such as a different process had already put the interface into promiscuous mode.

See Also:
Constant Field Values

MODE_PROMISCUOUS

public static final int MODE_PROMISCUOUS
Flag used with openLive to specify that the interface should be put into promisuous mode.

See Also:
Constant Field Values

NEXT_EX_EOF

public static final int NEXT_EX_EOF
Exit code for nextEx method which indicates that pcap reached end of file while reading a 'savefile'.

See Also:
Constant Field Values

NEXT_EX_NOT_OK

public static final int NEXT_EX_NOT_OK
Exit code for nextEx method which indicates failure of some kind. Use getErr() to retrieve the error message.

See Also:
Constant Field Values

NEXT_EX_OK

public static final int NEXT_EX_OK
Exit code for nextEx method which indicates success.

See Also:
Constant Field Values

NEXT_EX_TIMEDOUT

public static final int NEXT_EX_TIMEDOUT
Exit code for nextEx method which indicates timeout has expired before a packet was captured. The packet header and packet buffer do no point to any valid data.

See Also:
Constant Field Values

NOT_OK

public static final int NOT_OK
Pcap status return code for most of the methods defined here. All methods that return an intenger as a status code, use this constants as meaning the call failed.

See Also:
Constant Field Values

OK

public static final int OK
Pcap status return code for most of the methods defined here. All methods that return an intenger as a status code, use this constants as meaning the call succeeded.

See Also:
Constant Field Values
Constructor Detail

Pcap

public Pcap()
Pcap object can only be created by calling one of the static openLive(java.lang.String, int, int, int, java.lang.StringBuilder) methods.

Method Detail

compileNoPcap

public static int compileNoPcap(int snaplen,
                                int dlt,
                                PcapBpfProgram program,
                                java.lang.String str,
                                int optimize,
                                int netmask)

Compile a packet filter without the need of opening an adapter. This function converts an high level filtering expression (see Filtering expression syntax) in a program that can be interpreted by the kernel-level filtering engine.

pcap_compile_nopcap() is similar to pcap_compile() except that instead of passing a pcap structure, one passes the snaplen and linktype explicitly. It is intended to be used for compiling filters for direct BPF usage, without necessarily having called pcap_open(). (pcap_compile_nopcap() is a wrapper around pcap_open_dead(), pcap_compile(), and pcap_close(); the latter three routines can be used directly in order to get the error text for a compilation error.)

Look at the Filtering expression syntax section for details on the str parameter.

Parameters:
snaplen - generate code to truncate packets to this length upon a match
dlt - the first header type within the packet, or data link type of the interface
program - initially empty, but after the method call will contain the compiled BPF program
str - a string containing the textual expression to be compiled
optimize - 1 means to do optimizations, any other value means no
netmask - netmask needed to determine the broadcast address
Returns:
a return of -1 indicates an error; the error text is unavailable

datalinkNameToVal

public static int datalinkNameToVal(java.lang.String name)
Translates a data link type name, which is a DLT_ name with the DLT_ removed, to the corresponding data link type value. The translation is case-insensitive. -1 is returned on failure.

Parameters:
name - data link type name
Returns:
data link type value or -1 on failure

datalinkValToDescription

public static java.lang.String datalinkValToDescription(int dlt)
Translates a data link type value to a short description of that data link type. NULL is returned on failure.

Parameters:
dlt - data link type value
Returns:
short description of that data link type, NULL is returned on failure

datalinkValToName

public static java.lang.String datalinkValToName(int dlt)
Translates a data link type value to the corresponding data link type name. NULL is returned on failure.

Parameters:
dlt - data link type value
Returns:
data link type value to the corresponding data link type name, NULL is returned on failure

findAllDevs

public static int findAllDevs(java.util.List<PcapIf> alldevs,
                              java.lang.StringBuilder errbuf)
pcap_findalldevs() constructs a list of network devices that can be opened with pcap_open_live(). (Note that there may be network devices that cannot be opened with pcap_open_live() 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.) alldevs is set to point to the first element of the list; each element of the list is of type pcap_if_t, and has the following members: Each element of the list of addresses is of type pcap_addr_t, and has the following members:

Parameters:
alldevs - the list is filled in with PcapIf interface objects; the list must not be immutable
errbuf - error buffer containing error message as a string on failure
Returns:
-1 is returned on failure, in which case errbuf is filled in with an appropriate error message; 0 is returned on success

freeAllDevs

public static void freeAllDevs(java.util.List<PcapIf> alldevs,
                               byte[] errbuf)
This method does nothing. jNetPcap implementation frees up the device list immediately after its copied into Java objects in java space. The source structures are immediately released. pcap_freealldevs() is used to free a list allocated by pcap_findalldevs().

Parameters:
alldevs - is set to point to the first element of the list; each element of the list is of type PcapIf
errbuf - error buffer containing error message as a string on failure

freecode

public static void freecode(PcapBpfProgram program)
This frees up the code structures, but does not released the peered base bpf_program peer structure. Only the allocated storage to hold the code is freedup. The peered bpf_program structure is only freed when the program object is garbage collected.

Parameters:
program - program to free up the backend resources for

isInjectSupported

public static boolean isInjectSupported()
Checks if the current platform has support for pcap_inject call. The support is libpcap version and platform dependent.

Returns:
true means inject(byte[]) is supported, otherwise not
See Also:
inject(byte[])

isSendPacketSupported

public static boolean isSendPacketSupported()
Checks if the current platform has support for pcap_sendpacket call. The support is libpcap version and platform dependent.

Returns:
true means sendPacket(byte[]) is supported, otherwise not
See Also:
inject(byte[])

libVersion

public static java.lang.String libVersion()
Returns a pointer to a string giving information about the version of the libpcap library being used; note that it contains more information than just a version number

Returns:
version of the libpcap library being used

lookupDev

public static java.lang.String lookupDev(java.lang.StringBuilder errbuf)
Returns a network device suitable for use with openLive and lookupNet.

Parameters:
errbuf - if there is an error, errbuf is filled with appropriate message
Returns:
name of the device or null on error

lookupNet

public static int lookupNet(java.lang.String device,
                            PcapInteger netp,
                            PcapInteger maskp,
                            java.lang.StringBuilder errbuf)
Determines the network number and mask associated with the network device. Both netp and maskp are integer object references whos value is set from within the call. This is the way that pcap natively passes back these two values.

Note: this method is deprecated in pcap as it can not be used to pass back information about IP v6 addresses.

Parameters:
device - device to do the lookup on
netp - object which will contain the value of network address
maskp - object which will contain the value of network netmask
errbuf - any error messages if return value is -1
Returns:
0 on success otherwise -1 on error

openDead

public static Pcap openDead(int linktype,
                            int snaplen)
Create a pcap_t structure without starting a capture. pcap_open_dead() is 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 code.

Parameters:
linktype - pcap DLT link type integer value
snaplen - filters generated using the pcap structure will truncate captured packets to this length
Returns:
Pcap structure that can only be used to generate filter code and none of its other capture methods should be called or null if error occured

openLive

public static Pcap openLive(java.lang.String device,
                            int snaplen,
                            int promisc,
                            int timeout,
                            java.lang.StringBuilder errbuf)

Open a live capture associated with the specified network interface device. pcap_open_live() is used to obtain a packet capture descriptor 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. snaplen specifies the maximum number of bytes to capture. If this value is less than the size of a packet that is captured, only the first snaplen bytes of that packet will be captured and provided as packet data. A value of 65535 should be sufficient, on most if not all networks, to capture all the data available from the packet. promisc specifies if the interface is to be put into promiscuous mode. (Note that even if this parameter is false, the interface could well be in promiscuous mode for some other reason.)

For now, this doesn't work on the "any" device; if an argument of "any" or NULL is supplied, the promisc flag is ignored. to_ms specifies the read timeout in milliseconds. The read timeout is used to arrange that the read not necessarily return immediately when a packet is seen, but that it wait for some amount of time to allow more packets to arrive and to read multiple packets from the OS kernel in one operation. Not all platforms support a read timeout; on platforms that don't, the read timeout is ignored. A zero value for to_ms, on platforms that support a read timeout, will cause a read to wait forever to allow enough packets to arrive, with no timeout. errbuf is used to return error or warning text. It will be set to error text when pcap_open_live() fails and returns NULL. errbuf may also be set to warning text when pcap_open_live() succeds; to detect this case the caller should store a zero-length string in errbuf before calling pcap_open_live() and display the warning to the user if errbuf is no longer a zero-length string.

Special note about snaplen argument. The behaviour of this argument may be suprizing to some. The argument is only applied when there is a filter set using setFilter method after the openLive call. Otherwise snaplen, even non zero is ignored. This is the behavior of all BSD systems utilizing BPF and WinPcap. This may change in the future, but that is the current behavior. (For more detailed explanation and discussion please see jNetPcap website and its FAQs.)

Parameters:
device - buffer containing a C, '\0' terminated string with the the name of the device
snaplen - amount of data to capture per packet; (see special note in doc comments about when this argument is ignored even when non-zero)
promisc - 1 means open in promiscious mode, a 0 means non-propmiscous
timeout - timeout in ms
errbuf - a buffer that will contain any error messages if the call to open failed
Returns:
a raw structure the data of pcap_t C structure as returned by native libpcap call to open

openOffline

public static Pcap openOffline(java.lang.String fname,
                               java.lang.StringBuilder errbuf)
Open a savefile in the tcpdump/libpcap format to read packets. pcap_open_offline() is called to open a "savefile" for reading. fname specifies the name of the file to open. The file has the same format as those used by tcpdump(1) and tcpslice(1). The name "-" in a synonym for stdin. Alternatively, you may call pcap_fopen_offline() to read dumped data from an existing open stream fp. Note that on Windows, that stream should be opened in binary mode. errbuf is used to return error text and is only set when pcap_open_offline() or pcap_fopen_offline() fails and returns NULL.

Parameters:
fname - filename of the pcap file
errbuf - any error messages in UTC8 encoding
Returns:
Pcap structure or null if error occured

breakloop

public void breakloop()

set a flag that will force pcap_dispatch() or pcap_loop() to return rather than looping. They will return the number of packets that have been processed so far, or -2 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 pcap_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 pcap_breakloop(), the call will be restarted, and the loop will not terminate until more packets arrive and the call completes.

Note: pcap_next() will, on some platforms, loop reading packets from the OS; that loop will not necessarily be terminated by a signal, so pcap_breakloop() should be used to terminate packet processing even if pcap_next() is being used. pcap_breakloop() does not guarantee that no further packets will be processed by pcap_dispatch() or pcap_loop() after it is called; at most one more packet might be processed. If -2 is returned from pcap_dispatch() or pcap_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 -2 and clear the flag.


checkIsActive

protected void checkIsActive()
                      throws PcapClosedException
Checks if the current Pcap structure is active and open. It automatically throws an exception when its closed, but will not crash the VM. All dynamic non-native method in Pcap and any subclassed extensions should always make this call before attempting to do anything with pcap. The call makes sure that the pcap_t structure is still allocated and assigned to this object. If Pcap has been closed, no dynamic methods should be allowed to do anything. Native methods already perform this check. Static methods do not rely on pcap_t structure, since they are static, so they can not do this check.

Throws:
PcapClosedException - if pcap_t structure has been deallocated, another words if Pcap.close has already been called.

close

public void close()
pcap_close() closes the files associated with p and deallocates resources.


compile

public int compile(PcapBpfProgram program,
                   java.lang.String str,
                   int optimize,
                   int netmask)
Compile a packet filter, converting a high level filtering expression in to a progra that can be interpreted by the kernel-level filtering engine.

Parameters:
program - initially empty, but after the method call will contain the compiled BPF program
str - a string containing the textual expression to be compiled
optimize - 1 means to do optimizations, any other value means no
netmask - netmask needed to determine the broadcast address
Returns:
A return of -1 indicates an error in which case getErr() may be used to display the error text.

datalink

public int datalink()
Returns the link layer of an adapter.

Returns:
PCAP link layer number

dispatch

public <T> int dispatch(int cnt,
                        PcapHandler<T> handler,
                        T user)

Collect a group of packets. pcap_dispatch() is used to collect and process packets. cnt specifies the maximum number of packets to process before returning. This 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 cnt of -1 processes all the packets received in one buffer when reading a live capture, or all the packets in the file when reading a ``savefile''. callback specifies a routine to be called with three arguments: a u_char pointer which is passed in from pcap_dispatch(), a const struct pcap_pkthdr pointer, 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 (which won't necessarily be the entire packet; to capture the entire packet, you will have to provide a value for snaplen in your call to pcap_open_live() that is sufficiently large to get all of the packet's data - a value of 65535 should be sufficient on most if not all networks).

The number of packets read is returned. 0 is returned 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 read 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.'' A return of -1 indicates an error in which case pcap_perror() or pcap_geterr() may be used to display the error text. A return of -2 indicates that the loop terminated due to a call to pcap_breakloop() before any packets were processed. If your application uses pcap_breakloop(), make sure that you explicitly check for -1 and -2, rather than just checking for a return value < 0.

Note: when reading a live capture, pcap_dispatch() will not necessarily return when the read times out; on some platforms, the read timeout isn't supported, and, on other platforms, the timer doesn't start until at least one packet arrives. This means that the read timeout should NOT be used in, for example, an interactive application, to allow the packet capture loop to ``poll'' for user input periodically, as there's no guarantee that pcap_dispatch() will return after the timeout expires.

Type Parameters:
T - handler's user object type
Parameters:
cnt - number of packets to read
handler - called when packet arrives for each packet
user - opaque user object
Returns:
0 on success, -1 on error and -2 if breakloop was used interrupt the captue

dumpOpen

public PcapDumper dumpOpen(java.lang.String fname)
Open a file to write packets. The dumpOpen method is called to open a "savefile" for writing. The name '-' is a synonym for stdout.

Parameters:
fname - specifies the name of the file to open; currently the libpcap option to open stdout by using "-" as a string, is not supported by jNetPcap
Returns:
a dumper object or null on error; use getErr method to retrieve the error message

finalize

protected void finalize()
Cleanup before we're GCed. Will close connection to any open interface. Does nothing if connection already closed.

Overrides:
finalize in class java.lang.Object

getErr

public java.lang.String getErr()
return the error text pertaining to the last pcap library error.

Note: the pointer Return will no longer point to a valid error message string after the pcap_t passed to it is closed; you must use or copy the string before closing the pcap_t.

Returns:
the error text pertaining to the last pcap library error

getNonBlock

public int getNonBlock(java.lang.StringBuilder errbuf)
pcap_getnonblock() returns the current ``non-blocking'' state of the capture descriptor; it always returns 0 on ``savefiles''. If there is an error, -1 is returned and errbuf is filled in with an appropriate error message.

Returns:
if there is an error, -1 is returned and errbuf is filled in with an appropriate error message
See Also:
setNonBlock(int, StringBuilder)

inject

public int inject(byte[] buf)
This method allows to send a raw packet to the network. The MAC CRC doesn't need to be included, because it is transparently calculated and added by the network interface driver. The data will be taken from the supplied buffer where the start of the packet is buffer's current position() property and end its limit() properties.

Parameters:
buf - contains the data of the packet to send (including the various protocol headers)
Returns:
0 number of bytes written otherwise -1 on failure

inject

public int inject(byte[] buf,
                  int offset,
                  int length)
This method allows to send a raw packet to the network. The MAC CRC doesn't need to be included, because it is transparently calculated and added by the network interface driver. The data will be taken from the supplied buffer where the start of the packet is buffer's current position() property and end its limit() properties.

Parameters:
buf - contains the data of the packet to send (including the various protocol headers)
offset - offset of the first index into the byte array
length - amount of data to write from the offset
Returns:
0 number of bytes written otherwise -1 on failure

inject

public int inject(java.nio.ByteBuffer buf)
This method allows to send a raw packet to the network. The MAC CRC doesn't need to be included, because it is transparently calculated and added by the network interface driver. The data will be taken from the supplied buffer where the start of the packet is buffer's current position() property and end its limit() properties.

Parameters:
buf - contains the data of the packet to send (including the various protocol headers); the buffer should be a direct buffer; array based buffers will be copied into a direct buffer
Returns:
0 number of bytes written otherwise -1 on failure

isSwapped

public int isSwapped()
returns true if the current savefile uses a different byte order than the current system

Returns:
0 is false, non-zero is true

loop

public <T> int loop(int cnt,
                    PcapHandler<T> handler,
                    T user)
Collect a group of packets. pcap_loop() is similar to pcap_dispatch() except it keeps reading packets until cnt packets are processed or an error occurs. It does not return when live read timeouts occur. Rather, specifying a non-zero read timeout to pcap_open_live() and then calling pcap_dispatch() allows the reception and processing of any packets that arrive when the timeout occurs. A negative cnt causes pcap_loop() to loop forever (or at least until an error occurs). -1 is returned on an error; 0 is returned if cnt is exhausted; -2 is returned if the loop terminated due to a call to pcap_breakloop() before any packets were processed. If your application uses pcap_breakloop(), make sure that you explicitly check for -1 and -2, rather than just checking for a return value < 0.

Type Parameters:
T - handler's user object type
Parameters:
cnt - number of packets to read
handler - called when packet arrives for each packet
user - opaque user object
Returns:
0 on success, -1 on error and -2 if breakloop was used interrupt the captue

majorVersion

public int majorVersion()
Return the major version number of the pcap library used to write the savefile.

Returns:
return the major version number of the pcap library used to write the savefile

minorVersion

public int minorVersion()
Return the minor version number of the pcap library used to write the savefile.

Returns:
return the minor version number of the pcap library used to write the savefile

next

public java.nio.ByteBuffer next(PcapPktHdr pkt_header)
Return the next available packet. pcap_next() reads the next packet (by calling pcap_dispatch() with a cnt of 1) and returns a u_char pointer to the data in that packet. (The pcap_pkthdr struct for that packet is not supplied.) NULL is returned if an error occured, or 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 read 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 occured or not.

Parameters:
pkt_header - a packet header that will be initialized to corresponding C structure captured values
Returns:
buffer containing packet data or null if error occured

nextEx

public int nextEx(PcapPktHdr pkt_header,
                  PcapPktBuffer buffer)
Read a packet from an interface or from an offline capture. This function is used to retrieve the next available packet, bypassing the callback method traditionally provided by libpcap. pcap_next_ex fills the pkt_header and pkt_data parameters (see pcap_handler()) with the pointers to the header and to the data of the next captured packet.

Parameters:
pkt_header - a packet header that will be initialized to corresponding C structure captured values
buffer - buffer containing packet data or null if error occured
Returns:
the status code
  • 1 if the packet has been read without problems
  • 0 if the timeout set with pcap_open_live() has elapsed. In this case pkt_header and pkt_data don't point to a valid packet
  • -1 if an error occurred
  • -2 if EOF was reached reading from an offline capture

sendPacket

public int sendPacket(byte[] buf)
This method allows to send a raw packet to the network. The MAC CRC doesn't need to be included, because it is transparently calculated and added by the network interface driver. The data will be taken from the supplied buffer where the start of the packet is buffer's current position() property and end its limit() properties.

Parameters:
buf - contains the data of the packet to send (including the various protocol headers)
Returns:
0 on success and -1 on failure

sendPacket

public int sendPacket(byte[] buf,
                      int offset,
                      int length)
This method allows to send a raw packet to the network. The MAC CRC doesn't need to be included, because it is transparently calculated and added by the network interface driver. The data will be taken from the supplied buffer where the start of the packet is buffer's current position() property and end its limit() properties.

Parameters:
buf - contains the data of the packet to send (including the various protocol headers)
offset - offset of the first index into the byte array
length - amount of data to write from the offset
Returns:
0 on success and -1 on failure

sendPacket

public int sendPacket(java.nio.ByteBuffer buf)
This method allows to send a raw packet to the network. The MAC CRC doesn't need to be included, because it is transparently calculated and added by the network interface driver. The data will be taken from the supplied buffer where the start of the packet is buffer's current position() property and end its limit() properties.

Parameters:
buf - contains the data of the packet to send (including the various protocol headers); the buffer should be a direct buffer; array based buffers will be copied into a direct buffer
Returns:
0 on success and -1 on failure

setDatalink

public int setDatalink(int dlt)
Set the current data link type of the pcap descriptor to the type specified by dlt.

Parameters:
dlt - new dlt
Returns:
-1 is returned on failure

setFilter

public int setFilter(PcapBpfProgram program)
Associate a filter to a capture. pcap_setfilter() is used to specify a filter program. fp is a pointer to a bpf_program struct, usually the result of a call to pcap_compile(). -1 is returned on failure, in which case pcap_geterr() may be used to display the error text; 0 is returned on success.

Parameters:
program -
Returns:
-1 is returned on failure, in which case pcap_geterr() may be used to display the error text; 0 is returned on success

setNonBlock

public int setNonBlock(int nonBlock,
                       java.lang.StringBuilder errbuf)
pcap_setnonblock() puts a capture descriptor, opened with pcap_open_live(), 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, -1 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() will, if no packets are currently available to be read, return 0 immediately rather than blocking waiting for packets to arrive. pcap_loop() and pcap_next() will not work in ``non-blocking'' mode.

Parameters:
nonBlock - a non negative value means to set in non blocking mode
Returns:
if there is an error, -1 is returned and errbuf is filled in with an appropriate error message
See Also:
getNonBlock(StringBuilder)

snapshot

public int snapshot()
Return the dimension of the packet portion (in bytes) that is delivered to the application. pcap_snapshot() returns the snapshot length specified when pcap_open_live was called.

Returns:
the snapshot length specified when pcap_open_live was called
See Also:
openLive(String, int, int, int, StringBuilder)

stats

public int stats(PcapStat stats)
Returns statistics on the current capture. The method fills in the PcapStat structure. The values represent packet statistics from the start of the run to the time of the call.

Parameters:
stats - PcapStat object to fill in
Returns:
-1 if underlying packet capture doesn't support packet statistics or if there is an error; use getErr to retrieve the error message

toString

public java.lang.String toString()
Prints libVersion that Pcap is based on.

Overrides:
toString in class java.lang.Object