All functions defined by "Net::Pcap" are direct mappings to the libpcap functions. Consult the pcap(3)
documentation and source code for more information.
Arguments that change a parameter, for example pcap_lookupdev(), are passed that parameter as a
reference. This is to retain compatibility with previous versions of "Net::Pcap".
Lookupfunctionspcap_lookupdev(\$err)
Returns the name of a network device that can be used with pcap_open_live() function. On error, the
$err parameter is filled with an appropriate error message else it is undefined.
Example
$dev = pcap_lookupdev();
pcap_findalldevs(\%devinfo,\$err)
Returns a list of all network device names that can be used with pcap_open_live() function. On
error, the $err parameter is filled with an appropriate error message else it is undefined.
Example
@devs = pcap_findalldevs(\%devinfo, \$err);
for my $dev (@devs) {
print "$dev : $devinfo{$dev}\n"
}
Note
For backward compatibility reasons, this function can also be called using the following
signatures:
@devs = pcap_findalldevs(\$err);
@devs = pcap_findalldevs(\$err, \%devinfo);
The first form was introduced by Marco Carnut in "Net::Pcap" version 0.05 and kept intact in
versions 0.06 and 0.07. The second form was introduced by Jean-Louis Morel for the Windows only,
ActivePerl port of "Net::Pcap", in versions 0.04.01 and 0.04.02.
The new syntax has been introduced for consistency with the rest of the Perl API and the C API of
libpcap(3), where $err is always the last argument.
pcap_lookupnet($dev,\$net,\$mask,\$err)
Determine the network number and netmask for the device specified in $dev. The function returns 0 on
success and sets the $net and $mask parameters with values. On failure it returns -1 and the $err
parameter is filled with an appropriate error message.
Packetcapturefunctionspcap_open_live($dev,$snaplen,$promisc,$to_ms,\$err)
Returns a packet capture descriptor for looking at packets on the network. The $dev parameter
specifies which network interface to capture packets from. The $snaplen and $promisc parameters
specify the maximum number of bytes to capture from each packet, and whether to put the interface
into promiscuous mode, respectively. The $to_ms parameter specifies a read timeout in milliseconds.
The packet descriptor will be undefined if an error occurs, and the $err parameter will be set with
an appropriate error message.
Example
$dev = pcap_lookupdev();
$pcap = pcap_open_live($dev, 1024, 1, 0, \$err)
or die "Can't open device $dev: $err\n";
pcap_open_dead($linktype,$snaplen)
Creates and returns a new packet descriptor to use when calling the other functions in "libpcap". It
is typically used when just using "libpcap" for compiling BPF code.
Example
$pcap = pcap_open_dead(0, 1024);
pcap_open_offline($filename,\$err)
Return a packet capture descriptor to read from a previously created "savefile". The returned
descriptor is undefined if there was an error and in this case the $err parameter will be filled.
Savefiles are created using the "pcap_dump_*" commands.
Example
$pcap = pcap_open_offline($dump, \$err)
or die "Can't read '$dump': $err\n";
pcap_loop($pcap,$count,\&callback,$user_data)
Read $count packets from the packet capture descriptor $pcap and call the perl function &callback
with an argument of $user_data. If $count is negative, then the function loops forever or until an
error occurs. Returns 0 if $count is exhausted, -1 on error, and -2 if the loop terminated due to a
call to pcap_breakloop() before any packets were processed.
The callback function is also passed packet header information and packet data like so:
sub process_packet {
my ($user_data, $header, $packet) = @_;
...
}
The header information is a reference to a hash containing the following fields.
• "len" - the total length of the packet.
• "caplen" - the actual captured length of the packet data. This corresponds to the snapshot
length parameter passed to open_live().
• "tv_sec" - seconds value of the packet timestamp.
• "tv_usec" - microseconds value of the packet timestamp.
Example
pcap_loop($pcap, 10, \&process_packet, "user data");
sub process_packet {
my ($user_data, $header, $packet) = @_;
# ...
}
pcap_breakloop($pcap)
Sets 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.
Please see the section on pcap_breakloop() in pcap(3) for more information.
pcap_close($pcap)
Close the packet capture device associated with the descriptor $pcap.
pcap_dispatch($pcap,$count,\&callback,$user_data)
Collect $count packets and process them with callback function &callback. if $count is -1, all
packets currently buffered are processed. If $count is 0, process all packets until an error occurs.
pcap_next($pcap,\%header)
Return the next available packet on the interface associated with packet descriptor $pcap. Into the
%header hash is stored the received packet header. If not packet is available, the return value and
header is undefined.
pcap_next_ex($pcap,\%header,\$packet)
Reads the next available packet on the interface associated with packet descriptor $pcap, stores its
header in "\%header" and its data in "\$packet" and returns a success/failure indication:
• 1 means that the packet was read without problems;
• 0 means that packets are being read from a live capture, and the timeout expired;
• -1 means that an error occurred while reading the packet;
• -2 packets are being read from a dump file, and there are no more packets to read from the
savefile.
pcap_compile($pcap,\$filter,$filter_str,$optimize,$netmask)
Compile the filter string contained in $filter_str and store it in $filter. A description of the
filter language can be found in the libpcap source code, or the manual page for tcpdump(8) . The
filter is optimized if the $optimize variable is true. The netmask of the network device must be
specified in the $netmask parameter. The function returns 0 if the compilation was successful, or -1
if there was a problem.
pcap_compile_nopcap($snaplen,$linktype,\$filter,$filter_str,$optimize,$netmask)
Similar to compile() except that instead of passing a $pcap descriptor, one passes $snaplen and
$linktype directly. Returns -1 if there was an error, but the error message is not available.
pcap_setfilter($pcap,$filter)
Associate the compiled filter stored in $filter with the packet capture descriptor $pcap.
pcap_freecode($filter)
Used to free the allocated memory used by a compiled filter, as created by pcap_compile().
pcap_offline_filter($filter,\%header,$packet)
Check whether $filter matches the packet described by header %header and packet data $packet. Returns
true if the packet matches.
pcap_setnonblock($pcap,$mode,\$err)
Set the non-blocking mode of a live capture descriptor, depending on the value of $mode (zero to
activate and non-zero to deactivate). It has no effect on offline descriptors. If there is an error,
it returns -1 and sets $err.
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.
pcap_getnonblock($pcap,\$err)
Returns the non-blocking state of the capture descriptor $pcap. Always returns 0 on savefiles. If
there is an error, it returns -1 and sets $err.
Savefilecommandspcap_dump_open($pcap,$filename)
Open a savefile for writing and return a descriptor for doing so. If $filename is "-" data is
written to standard output. On error, the return value is undefined and pcap_geterr() can be used to
retrieve the error text.
pcap_dump($dumper,\%header,$packet)
Dump the packet described by header %header and packet data $packet to the savefile associated with
$dumper. The packet header has the same format as that passed to the pcap_loop() callback.
Example
my $dump_file = 'network.dmp';
my $dev = pcap_lookupdev();
my $pcap = pcap_open_live($dev, 1024, 1, 0, \$err);
my $dumper = pcap_dump_open($pcap, $dump_file);
pcap_loop($pcap, 10, \&process_packet, '');
pcap_dump_close($dumper);
sub process_packet {
my ($user_data, $header, $packet) = @_;
pcap_dump($dumper, $header, $packet);
}
pcap_dump_file($dumper)
Returns the filehandle associated with a savefile opened with pcap_dump_open().
pcap_dump_flush($dumper)
Flushes the output buffer to the corresponding save file, so that any packets written with
pcap_dump() but not yet written to the save file will be written. Returns -1 on error, 0 on success.
pcap_dump_close($dumper)
Close the savefile associated with the descriptor $dumper.
Statusfunctionspcap_datalink($pcap)
Returns the link layer type associated with the given pcap descriptor.
Example
$linktype = pcap_datalink($pcap);
pcap_set_datalink($pcap,$linktype)
Sets the data link type of the given pcap descriptor to the type specified by $linktype. Returns -1
on failure.
pcap_datalink_name_to_val($name)
Translates a data link type name, which is a "DLT_" name with the "DLT_" part removed, to the
corresponding data link type value. The translation is case-insensitive. Returns -1 on failure.
Example
$linktype = pcap_datalink_name_to_val('LTalk'); # returns DLT_LTALK
pcap_datalink_val_to_name($linktype)
Translates a data link type value to the corresponding data link type name.
Example
$name = pcap_datalink_val_to_name(DLT_LTALK); # returns 'LTALK'
pcap_datalink_val_to_description($linktype)
Translates a data link type value to a short description of that data link type.
Example
$descr = pcap_datalink_val_to_description(DLT_LTALK); # returns 'Localtalk'
pcap_snapshot($pcap)
Returns the snapshot length (snaplen) specified in the call to pcap_open_live().
pcap_is_swapped($pcap)
This function returns true if the endianness of the currently open savefile is different from the
endianness of the machine.
pcap_major_version($pcap)
Return the major version number of the pcap library used to write the currently open savefile.
pcap_minor_version($pcap)
Return the minor version of the pcap library used to write the currently open savefile.
pcap_stats($pcap,\%stats)
Returns a hash containing information about the status of packet capture device $pcap. The hash
contains the following fields.
This function 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.
• "ps_recv" - the number of packets received by the packet capture software.
• "ps_drop" - the number of packets dropped by the packet capture software.
• "ps_ifdrop" - the number of packets dropped by the network interface.
pcap_file($pcap)
Returns the filehandle associated with a savefile opened with pcap_open_offline() or "undef" if the
device was opened with pcap_open_live().
pcap_fileno($pcap)
Returns the file number of the network device opened with pcap_open_live().
pcap_get_selectable_fd($pcap)
Returns, on Unix, a file descriptor number for a file descriptor on which one can do a select() or
poll() to wait for it to be possible to read packets without blocking, if such a descriptor exists,
or -1, if no such descriptor exists. Some network devices opened with pcap_open_live() do not support
select() or poll(), so -1 is returned for those devices. See pcap(3) for more details.
Errorhandlingpcap_geterr($pcap)
Returns an error message for the last error associated with the packet capture device $pcap.
pcap_strerror($errno)
Returns a string describing error number $errno.
pcap_perror($pcap,$prefix)
Prints the text of the last error associated with descriptor $pcap on standard error, prefixed by
$prefix.
Informationpcap_lib_version()
Returns the name and version of the "pcap" library the module was linked against.
Perlspecificfunctions
The following functions are specific to the Perl binding of libpcap.
pcap_perl_settings($setting)
Modify internal behaviour of the Perl interpreter.
• "PERL_SIGNALS_SAFE", "PERL_SIGNALS_UNSAFE" respectively enable safe or unsafe signals delivery.
Returns the previous value of "PL_signals". See "Signals handling".
Example:
local $SIG{ALRM} = sub { pcap_breakloop() };
alarm 60;
pcap_perl_settings(PERL_SIGNALS_UNSAFE);
pcap_loop($pcap, 10, \&process_packet, "");
pcap_perl_settings(PERL_SIGNALS_SAFE);
WinPcapspecificfunctions
The following functions are only available with WinPcap, the Win32 port of the Pcap library. If a called
function is not available, it will cleanly croak().
pcap_createsrcstr(\$source,$type,$host,$port,$name,\$err)
Accepts a set of strings (host name, port, ...), and stores the complete source string according to
the new format (e.g. "rpcap://1.2.3.4/eth0") in $source.
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(1), 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.
Returns 0 if everything is fine, -1 if some errors occurred. The string containing the complete
source is returned in the $source variable.
pcap_parsesrcstr($source,\$type,\$host,\$port,\$name,\$err)
Parse the source string and stores the pieces in which the source can be split in the corresponding
variables.
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).
The user can omit some parameters in case it is not interested in them.
Returns 0 if everything is fine, -1 if some errors occurred. The requested values (host name, network
port, type of the source) are returned into the proper variables passed by reference.
pcap_open($source,$snaplen,$flags,$read_timeout,\$auth,\$err)
Open a generic source in order to capture / send (WinPcap only) traffic.
The pcap_open() replaces all the pcap_open_xxx() functions with a single call.
This function hides the differences between the different pcap_open_xxx() functions so that the
programmer does not have to manage different opening function. In this way, the true open() function
is decided according to the source type, which is included into the source string (in the form of
source prefix).
Returns a pointer to a pcap descriptor which can be used as a parameter to the following calls
(compile() and so on) and that specifies an opened WinPcap session. In case of problems, it returns
"undef" and the $err variable keeps the error message.
pcap_setbuff($pcap,$dim)
Sets 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 setbuff(), it is deleted and its content
is discarded. open_live() creates a 1 MB buffer by default.
pcap_setmode($pcap,$mode)
Sets the working mode of the interface $pcap to $mode. Valid values for $mode are "MODE_CAPT"
(default capture mode) and "MODE_STAT" (statistical mode).
pcap_setmintocopy($pcap_t,$size)
Changes the minimum amount of data in the kernel buffer that causes a read from the application to
return (unless the timeout expires).
pcap_getevent($pcap)
Returns the "Win32::Event" object associated with the interface $pcap. Can be used to wait until the
driver's buffer contains some data without performing a read. See Win32::Event.
pcap_sendpacket($pcap,$packet)
Send a raw packet to the network. $pcap is the interface that will be used to send the packet,
$packet contains the data of the packet to send (including the various protocol headers). The MAC CRC
doesn't need to be included, because it is transparently calculated and added by the network
interface driver. The return value is 0 if the packet is successfully sent, -1 otherwise.
pcap_sendqueue_alloc($memsize)
This function allocates and returns a send queue, i.e. a buffer containing a set of raw packets that
will be transmitted on the network with sendqueue_transmit().
$memsize is the size, in bytes, of the queue, therefore it determines the maximum amount of data that
the queue will contain. This memory is automatically deallocated when the queue ceases to exist.
pcap_sendqueue_queue($queue,\%header,$packet)
Adds a packet at the end of the send queue pointed by $queue. The packet header %header has the same
format as that passed to the loop() callback. $ackekt is a buffer with the data of the packet.
The %headerr header structure is the same used by WinPcap and libpcap to store the packets in a file,
therefore sending a capture file is straightforward. "Raw packet" means that the sending application
will have to include the protocol headers, since every packet is sent to the network asis. The CRC
of the packets needs not to be calculated, because it will be transparently added by the network
interface.
pcap_sendqueue_transmit($pcap,$queue,$sync)
This function transmits the content of a queue to the wire. $pcapt is the interface on which the
packets will be sent, $queue is to a "send_queue" containing the packets to send, $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.