Quick Navigator

Search Site

Unix VPS
A - Starter
B - Basic
C - Preferred
D - Commercial
MPS - Dedicated
Previous VPSs
* Sign Up! *

Contact Us
Online Help
Domain Status
Man Pages

Virtual Servers

Topology Map

Server Agreement
Year 2038

USA Flag



Man Pages

Manual Reference Pages  -  NET::PCAP (3)

.ds Aq ’


Net::Pcap - Interface to pcap(3) LBL packet capture library



Version 0.17


    use Net::Pcap;

    my $err = ;
    my $dev = pcap_lookupdev(\$err);  # find a device

    # open the device for live listening
    my $pcap = pcap_open_live($dev, 1024, 1, 0, \$err);

    # loop over next 10 packets
    pcap_loop($pcap, 10, \&process_packet, "just for the demo");

    # close the device

    sub process_packet {
        my ($user_data, $header, $packet) = @_;
        # do something ...


Net::Pcap is a Perl binding to the LBL pcap(3) library and its Win32 counterpart, the WinPcap library. Pcap (packet capture) is a portable API to capture network packet: it allows applications to capture packets at link-layer, bypassing the normal protocol stack. It also provides features like kernel-level packet filtering and access to internal statistics.

Common applications include network statistics collection, security monitoring, network debugging, etc.


    Signals handling

Since version 5.7.3, Perl uses a mechanism called deferred signals to delay signals delivery until safe points in the interpreter. See Deferred Signals (Safe Signals) in perlipc for a detailled explanation.

Since Net::Pcap version 0.08, released in October 2005, the module modified the internal variable PL_signals to re-enable immediate signals delivery in Perl 5.8 and later within some XS functions (CPAN-RT #6320). However, it can create situations where the Perl interpreter is less stable and can crash (CPAN-RT #43308). Therefore, as of version 0.17, Net::Pcap no longer modifies PL_signals by itself, but provides facilities so the user has full control of how signals are delivered.

First, there pcap_perl_settings() function allows to select how signals are handled:

    pcap_loop($pcap, 10, \&process_packet, "");

Then, to easily make code interruptable, Net::Pcap provides the UNSAFE_SIGNALS pseudo-bloc:

        pcap_loop($pcap, 10, \&process_packet, "");

(Stolen from Rafael Garcia-Suarez’s Perl::Unsafe::Signals)


Net::Pcap supports the following Exporter tags:
o :bpf exports a few BPF related constants:


o :datalink exports the data link types macros:


o :pcap exports the following pcap constants:


o :mode exports the following constants:


o :openflag exports the following constants:


o :source exports the following constants:


o :sample exports the following constants:


o :rpcap exports the following constants:


o :functions short names of the functions (without the "pcap_" prefix) for those which would not cause a clash with an already defined name. Namely, the following functions are not available in short form: open(), close(), next(), dump(), file(), fileno(). Using these short names is now discouraged, and may be removed in the future.
By default, this module exports the symbols from the :datalink and :pcap tags, and all the functions, with the same names as the C library.


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.

    Lookup functions

<B>pcap_lookupdev(\$err)B> 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.


    $dev = pcap_lookupdev();

<B>pcap_findalldevs(\%devinfo, \$err)B> 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.


    @devs = pcap_findalldevs(\%devinfo, \$err);
    for my $dev (@devs) {
        print "$dev : $devinfo{$dev}\n"

<B>NoteB> 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.

<B>pcap_lookupnet($dev, \$net, \$mask, \$err)B> 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.

    Packet capture functions

<B>pcap_open_live($dev, B>$snaplen<B>, B>$promisc<B>, B>$to_ms<B>, \$err)B> 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.


    $dev = pcap_lookupdev();
    $pcap = pcap_open_live($dev, 1024, 1, 0, \$err)
        or die "Cant open device $dev: $err\n";

<B>pcap_open_dead($linktype, B>$snaplen<B>)B> 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.


    $pcap = pcap_open_dead(0, 1024);

<B>pcap_open_offline($filename, \$err)B> 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.


    $pcap = pcap_open_offline($dump, \$err)
        or die "Cant read $dump: $err\n";

<B>pcap_loop($pcap, B>$count<B>, \&callback, B>$user_data<B>)B> 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.
o len - the total length of the packet.
o caplen - the actual captured length of the packet data. This corresponds to the snapshot length parameter passed to open_live().
o tv_sec - seconds value of the packet timestamp.
o tv_usec - microseconds value of the packet timestamp.


    pcap_loop($pcap, 10, \&process_packet, "user data");

    sub process_packet {
        my ($user_data, $header, $packet) = @_;
        # ...

<B>pcap_breakloop($pcap)B> 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.

<B>pcap_close($pcap)B> Close the packet capture device associated with the descriptor $pcap.
<B>pcap_dispatch($pcap, B>$count<B>, \&callback, B>$user_data<B>)B> 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.
<B>pcap_next($pcap, \%header)B> 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.
<B>pcap_next_ex($pcap, \%header, \$packet)B> 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:
o 1 means that the packet was read without problems;
o 0 means that packets are being read from a live capture, and the timeout expired;
o -1 means that an error occurred while reading the packet;
o -2 packets are being read from a dump file, and there are no more packets to read from the savefile.
<B>pcap_compile($pcap, \$filter, B>$filter_str<B>, B>$optimize<B>, B>$netmask<B>)B> 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.
<B>pcap_compile_nopcap($snaplen, B>$linktype<B>, \$filter, B>$filter_str<B>, B>$optimize<B>, B>$netmask<B>)B> 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.
<B>pcap_setfilter($pcap, B>$filter<B>)B> Associate the compiled filter stored in $filter with the packet capture descriptor $pcap.
<B>pcap_freecode($filter)B> Used to free the allocated memory used by a compiled filter, as created by pcap_compile().
<B>pcap_setnonblock($pcap, B>$mode<B>, \$err)B> 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.

<B>pcap_getnonblock($pcap, \$err)B> 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.

    Savefile commands

<B>pcap_dump_open($pcap, B>$filename<B>)B> 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.
<B>pcap_dump($dumper, \%header, B>$packet<B>)B> 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.


    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, );

    sub process_packet {
        my ($user_data, $header, $packet) = @_;
        pcap_dump($dumper, $header, $packet);

<B>pcap_dump_file($dumper)B> Returns the filehandle associated with a savefile opened with pcap_dump_open().
<B>pcap_dump_flush($dumper)B> 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.
<B>pcap_dump_close($dumper)B> Close the savefile associated with the descriptor $dumper.

    Status functions

<B>pcap_datalink($pcap)B> Returns the link layer type associated with the given pcap descriptor.


    $linktype = pcap_datalink($pcap);

<B>pcap_set_datalink($pcap, B>$linktype<B>)B> Sets the data link type of the given pcap descriptor to the type specified by $linktype. Returns -1 on failure.
<B>pcap_datalink_name_to_val($name)B> 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.


    $linktype = pcap_datalink_name_to_val(LTalk);  # returns DLT_LTALK

<B>pcap_datalink_val_to_name($linktype)B> Translates a data link type value to the corresponding data link type name.


    $name = pcap_datalink_val_to_name(DLT_LTALK);  # returns LTALK

<B>pcap_datalink_val_to_description($linktype)B> Translates a data link type value to a short description of that data link type.


    $descr = pcap_datalink_val_to_description(DLT_LTALK);  # returns Localtalk

<B>pcap_snapshot($pcap)B> Returns the snapshot length (snaplen) specified in the call to pcap_open_live().
<B>pcap_is_swapped($pcap)B> This function returns true if the endianness of the currently open savefile is different from the endianness of the machine.
<B>pcap_major_version($pcap)B> Return the major version number of the pcap library used to write the currently open savefile.
<B>pcap_minor_version($pcap)B> Return the minor version of the pcap library used to write the currently open savefile.
<B>pcap_stats($pcap, \%stats)B> 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.
o ps_recv - the number of packets received by the packet capture software.
o ps_drop - the number of packets dropped by the packet capture software.
o ps_ifdrop - the number of packets dropped by the network interface.

<B>pcap_file($pcap)B> Returns the filehandle associated with a savefile opened with pcap_open_offline() or undef if the device was opened with pcap_open_live().
<B>pcap_fileno($pcap)B> Returns the file number of the network device opened with pcap_open_live().
<B>pcap_get_selectable_fd($pcap)B> 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.

    Error handling

<B>pcap_geterr($pcap)B> Returns an error message for the last error associated with the packet capture device $pcap.
<B>pcap_strerror($errno)B> Returns a string describing error number $errno.
<B>pcap_perror($pcap, B>$prefix<B>)B> Prints the text of the last error associated with descriptor $pcap on standard error, prefixed by $prefix.


<B>B>pcap_lib_version()<B>B> Returns the name and version of the pcap library the module was linked against.

    Perl specific functions

The following functions are specific to the Perl binding of libpcap.
<B>pcap_perl_settings($setting)B> Modify internal behaviour of the Perl interpreter.
o PERL_SIGNALS_SAFE, PERL_SIGNALS_UNSAFE respectively enable safe or unsafe signals delivery. Returns the previous value of PL_signals. See Signals handling.


    local $SIG{ALRM} = sub { pcap_breakloop() };
    alarm 60;

    pcap_loop($pcap, 10, \&process_packet, "");

    WinPcap specific functions

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().
<B>pcap_createsrcstr(\$source, B>$type<B>, B>$host<B>, B>$port<B>, B>$name<B>, \$err)B> Accepts a set of strings (host name, port, ...), and stores the complete source string according to the new format (e.g. "rpcap://") 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 <B>B>tcpdump<B>(1)B>, 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.

<B>pcap_parsesrcstr($source, \$type, \$host, \$port, \$name, \$err)B> 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:
o 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);
o the host on which the capture has to be started (only for remote captures);
o 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.

<B>pcap_open($source, B>$snaplen<B>, B>$flags<B>, B>$read_timeout<B>, \$auth, \$err)B> 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.

<B>pcap_setbuff($pcap, B>$dim<B>)B> 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.

<B>pcap_setmode($pcap, B>$mode<B>)B> 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).
<B>pcap_setmintocopy($pcap_t, B>$size<B>)B> Changes the minimum amount of data in the kernel buffer that causes a read from the application to return (unless the timeout expires).
<B>pcap_getevent($pcap)B> 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.
<B>pcap_sendpacket($pcap, B>$packet<B>)B> 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.
<B>pcap_sendqueue_alloc($memsize)B> 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.

<B>pcap_sendqueue_queue($queue, \%header, B>$packet<B>)B> 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 as is. The CRC of the packets needs not to be calculated, because it will be transparently added by the network interface.

<B>pcap_sendqueue_transmit($pcap, B>$queue<B>, B>$sync<B>)B> 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.


Net::Pcap exports by default the names of several constants in order to ease the development of programs. See EXPORTS for details about which constants are exported.

Here are the descriptions of a few data link types. See pcap(3) for a more complete description and semantics associated with each data link.
o DLT_NULL - BSD loopback encapsulation
o DLT_EN10MB - Ethernet (10Mb, 100Mb, 1000Mb, and up)
o DLT_RAW - raw IP
o DLT_IEEE802 - IEEE 802.5 Token Ring
o DLT_IEEE802_11 - IEEE 802.11 wireless LAN
o DLT_FRELAY - Frame Relay
o DLT_SLIP - Serial Line IP
o DLT_PPP - PPP (Point-to-point Protocol)
o DLT_PPP_SERIAL - PPP over serial with HDLC encapsulation
o DLT_PPP_ETHER - PPP over Ethernet
o DLT_IP_OVER_FC - RFC 2625 IP-over-Fibre Channel
o DLT_AX25 - Amateur Radio AX.25
o DLT_LTALK - Apple LocalTalk
o DLT_APPLE_IP_OVER_IEEE1394 - Apple IP-over-IEEE 1394 (a.k.a. Firewire)


arg%d not a scalar ref
arg%d not a hash ref
arg%d not a reference <B>(F)B> These errors occur if you forgot to give a reference to a function which expect one or more of its arguments to be references.


The following limitations apply to this version of Net::Pcap.
o At present, only one callback function and user data scalar can be current at any time as they are both stored in global variables.


Please report any bugs or feature requests to, or through the web interface at <>. I will be notified, and then you’ll automatically be notified of progress on your bug as I make changes.

Currently known bugs:
o the ps_recv field is not correctly set; see t/07-stats.t
o pcap_file() seems to always returns undef for live connection and causes segmentation fault for dump files; see t/10-fileno.t
o pcap_fileno() is documented to return -1 when called on save file, but seems to always return an actual file number. See t/10-fileno.t
o pcap_dump_file() seems to corrupt something somewhere, and makes scripts dump core. See t/05-dump.t


See the eg/ and t/ directories of the Net::Pcap distribution for examples on using this module.


    Perl Modules

Net::Pcap::Reassemble for reassembly of TCP/IP fragments.

POE::Component::Pcap for using Net::Pcap within POE-based programs.

Net::Packet or NetPacket for decoding and creating network packets.

Net::Pcap::Easy is a module which provides an easier, more Perl-ish API than Net::Pcap and integrates some facilities from Net::Netmask and NetPacket.

    Base Libraries

pcap(3), tcpdump(8)

The source code for the pcap(3) library is available from <>

The source code and binary for the Win32 version of the pcap library, WinPcap, is available from <>


Hacking Linux Exposed: Sniffing with Net::Pcap to stealthily managing iptables rules remotely, <>

PerlMonks node about Net::Pcap, <>


Current maintainer is Se\k:'Aperghis-Tramoni (SAPER) <> with the help of Jean-Louis Morel (JLMOREL) <> for WinPcap support.

Previous authors & maintainers:
o Marco Carnut (KCARNUT) <>
o Tim Potter (TIMPOTTER) <>
o Bo Adler (BOADLER) <>
o Peter Lister (PLISTER) <>


To Paul Johnson for his module Devel::Cover and his patience for helping me using it with XS code, which revealed very useful for writing more tests.

To the beta-testers: Jean-Louis Morel, Max Maischen, Philippe Bruhat, David Morel, Scott Lanning, Rafael Garcia-Suarez, Karl Y. Pradene.


Copyright (C) 2005, 2006, 2007, 2008, 2009 Se\k:'Aperghis-Tramoni. All rights reserved.

Copyright (C) 2003 Marco Carnut. All rights reserved.

Copyright (C) 1999, 2000 Tim Potter. All rights reserved.

Copyright (C) 1998 Bo Adler. All rights reserved.

Copyright (C) 1997 Peter Lister. All rights reserved.

This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.

Search for    or go to Top of page |  Section 3 |  Main Index

perl v5.20.3 PCAP (3) 2011-06-13

Powered by GSP Visit the GSP FreeBSD Man Page Interface.
Output converted with manServer 1.07.