Net::Pcap - Interface to pcap LBL packet capture library

NAME

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

[ Caution: this is a patched version of Net::Pcap for Win32. It's a beta version for this platform. Don't use it in a production script. In agreement with Tim Potter, it will be incorporated in a future release of Net::Pcap.

In order to use Net::Pcap in your Perl scripts, it is necessary to install WinPcap 3.1 beta 3 or WinPcap 3.0 on your machine; see http://winpcap.polito.it/install/default.htm.

Home page for this version: http://www.bribes.org/perl/wnetpcap.html

Report bug to Jean-Louis Morel: jl_morel@bribes.org . Thanks. ]


SYNOPSIS

  use Net::Pcap;


DESCRIPTION

Net::Pcap is a Perl binding to the LBL pcap(3) library, version 0.4. The README for libpcap describes itself as:

  "a system-independent interface for user-level packet capture.
  libpcap provides a portable framework for low-level network
  monitoring.  Applications include network statistics collection,
  security monitoring, network debugging, etc."


FUNCTIONS

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 Net::Pcap::lookupdev(), are passed that parameter as a reference. This is to retain compatibility with previous versions of Net::Pcap.

Lookup functions

Net::Pcap::lookupdev(\$err);
Returns the name of a network device that can be used with Net::Pcap::open_live() function. On error, the $err parameter is filled with an appropriate error message else it is undefined.

Net::Pcap::findalldevs(\$err [,\%description]);
Returns a list of all network device names that can be used with Net::Pcap::open_live() function. If the optional parameter is provided, the hash %description is filled with the description string of each network device. On error, the $err parameter is filled with an appropriate error message else it is undefined.
  my ($error, %description);
  foreach(Net::Pcap::findalldevs(\$error, \%description)) {
    print "$_\n   $description{$_}\n\n";
  }
  print $error if defined $error;

Net::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.

Packet capture functions

Net::Pcap::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 ms. The packet descriptor will be undefined if an error occurs, and the $err parameter will be set with an appropriate error message.

Net::Pcap::loop($pcap_t, $cnt, \&callback_fn, $user_data);
Read $cnt packets from the packet capture descriptor $pcap_t and call the perl function &callback_fn with an argument of $user_data. If $cnt is negative, then the function loops forever or until an error occurs.

The callback function is also passed packet header information and packet data like so:

  sub process_pkt {
      my($user_data, $hdr, $pkt) = @_;
      ...
  }

The header information is a reference to a hash containing the following fields.

Net::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 Net::Pcap::dump_* commands.

Net::Pcap::close($pcap_t);
Close the packet capture device associated with descriptor $pcap_t.

Net::Pcap::dispatch($pcap_t, $cnt, \&callback_fn, $user_data);
Collect $cnt packets and process them with callback function &callback_fn. if $cnt is -1, all packets currently buffered are processed. If $cnt is 0, process all packets until an error occurs.

Net::Pcap::next($pcap_t, \%hdr);
Return the next available packet on the interface associated with packet descriptor $pcap_t. Into the %hdr hash is stored the received packet header. If not packet is available, the return value and header is undefined.

Net::Pcap::compile($pcap_t, \$filter_t, $filter_str, $optimize, $netmask);
Compile the filter string contained in $filter_str and store it in $filter_t. 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 the filter 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.

Net::Pcap::setfilter($pcap_t, $filter_t);
Associate the compiled filter stored in $filter_t with the packet capture descriptor $pcap_t.

Savefile commands

Net::Pcap::dump_open($pcap_t, $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 Net::Pcap::geterr() can be used to retrieve the error text.

Net::Pcap::dump($pcap_dumper_t, \%hdr, $pkt);
Dump the packet described by header %hdr and packet data $pkt to the savefile associated with $pcap_dumper_t. The packet header has the same format as that passed to the Net::Pcap::loop() callback.

Net::Pcap::dump_close($pcap_dumper_t);
Close the savefile associated with descriptor $pcap_dumper_t.

Status functions

$error = Net::Pcap::setnonblock($pcap_t, $nonblock, \$err);
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 $err 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.

$nonblock = Net::Pcap::getnonblock($pcap_t, \$err);
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 $err is filled in with an appropriate error message.

Net::Pcap::datalink($pcap_t);
Returns the link layer type associated with the currently open device.

Net::Pcap::snapshot($pcap_t);
Returns the snapshot length (snaplen) specified in the call to Net::Pcap::open_live().

Net::Pcap::is_swapped($pcap_t);
This function returns true if the endianess of the currently open savefile is different from the endianess of the machine.

Net::Pcap::major_version($pcap_t);
Return the major version number of the pcap library used to write the currently open savefile.

Net::Pcap::minor_version($pcap_t);
Return the minor version of the pcap library used to write the currently open savefile.

Net::Pcap::stats($pcap_t, \%stats);
Returns a hash containing information about the status of packet capture device $pcap_t. The hash contains the following fields.
Net::Pcap::file($pcap_t);
Return the filehandle associated with a savefile opened with Net::Pcap::open_offline().

Net::Pcap::fileno($pcap_t);
Return the file number of the network device opened with Net::Pcap::open_live().

Error handling

Net::Pcap::geterr($pcap_t);
Return an error message for the last error associated with the packet capture device $pcap_t.

Net::Pcap::strerror($errno);
Return a string describing error number $errno.

Net::Pcap::perror($pcap_t, $prefix);
Print the text of the last error associated with descriptor $pcap_t on standard error, prefixed by $prefix.

New WinPcap functions

$error = Net::Pcap::createsrcstr(\$source, $type, $host, $port, $name, \$err);
Accepts a set of strings ($host $name, $port), the $type of the source we want to create, and it returns the complete $source string according to the new format (e.g. 'rpcap://1.2.3.4/eth0'). Returns 0 if everything is fine, -1 if some errors occurred.

$error = Net::Pcap::parsesrcstr($source, \$type, \$host, \$port, \$name, \$err);
Parses the $source string and returns the pieces $type, $host, $port, $name in which the source can be split. Returns 0 if everything is fine, -1 if some errors occurred.

Net::Pcap::open($source, $snaplen, $flags, $read_timeout, \%auth, \$err);
Open a generic source in order to capture / send (WinPcap only) traffic. The Net::Pcap::open() replaces all the Net::Pcap::open_xxx() functions with a single call.

Parameters:

$source
The source name with the format prefix according to the new Source Specification Syntax (See WinPcap doc).

On Linux systems with 2.2 or later kernels, a device argument of ``any'' (i.e. rpcap://any) can be used to capture packets from all interfaces.

In order to makes the source syntax easier, please remember that:

  • the adapters returned by the Net::Pcap::findalldevs_ex() can be used immediately by the Net::Pcap::open()

  • in case the user wants to pass its own source string to the Net::Pcap::open(), the Net::Pcap::createsrcstr() helps in creating the correct source identifier.

$snaplen
length of the packet that has to be retained. For each packet received by the filter, only the first 'snaplen' bytes are stored in the buffer and passed to the user application.

$flags
keeps several flags that can be needed for capturing packets. The allowed flags are:
OPENFLAG_PROMISCUOUS
It defines if the adapter has to go in promiscuous mode.

OPENFLAG_DATATX_UDP
It defines if the data transfer (in case of a remote capture) has to be done with UDP protocol.

OPENFLAG_NOCAPTURE_RPCAP
It defines if the remote probe has to capture its own generated traffic.

$read_timeout
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 waits 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.

%auth
a hash that keeps the information required to authenticate the user on a remote machine. In case this is not a remote capture, this parameter can be set to undef.

The keys of the hash are type, username, password.

Example:

  my %auth = ( type => RMTAUTH_PWD,
               username => 'TheUserName',
               password => 'ThePassWord'
             );

$err
if an error occurs the $err parameter will be set with an appropriate error message. undef otherwise.

The function returns a packet capture descriptor for looking at packets on the network. In case of problems, it returns undef and the $err variable keeps the error message.

Win32 specific functions

Net::Pcap::setbuff($pcap_t, $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 Net::Pcap::setbuff(), it is deleted and its content is discarded. Net::Pcap::open_live() creates a 1 MByte buffer by default.

Net::Pcap::setmode($pcap_t, $mode)
Sets the working mode of the interface $pcap_t to $mode. Valid values for $mode are MODE_CAPT (default capture mode) and MODE_STAT (statistical mode).

Net::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).

Net::Pcap::getevent($pcap_t)
Returns the Win32::Event object associated with the interface $pcap_t. Can be used to wait until the driver's buffer contains some data without performing a read. See the Win32::Event manpage.

Net::Pcap::sendpacket($pcap_t, $packet)
Send a raw packet to the network. $pcap_t 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 succesfully sent, -1 otherwise.

$queue = Net::Pcap::sendqueue_alloc($memsize)
This function allocates a send queue, i.e. a buffer containing a set of raw packets that will be transmitted on the network with Net::Pcap::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 deallocated automatically when the queue ceases to exist.

Net::Pcap::sendqueue_queue($queue, \%hdr, $pkt)
Adds a packet at the end of the send queue pointed by $queue. The packet header %hdr has the same format as that passed to the Net::Pcap::loop() callback. $pkt is a buffer with the data of the packet.

The %hdr 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.

$nbytes = Net::Pcap::sendqueue_transmit($pcap_t, $queue, $sync)
This function transmits the content of a queue to the wire. $pcap_t 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.

Export

By default, Net::Pcap exports no symbols into the callers namespace. The following tags can be used to selectively import symbols into the main namespace.

:mode
  MODE_CAPT  MODE_STAT  MODE_MON
:src
  SRC_FILE  SRC_IFLOCAL  SRC_IFREMOTE
:openflag
  OPENFLAG_PROMISCUOUS  OPENFLAG_DATATX_UDP  OPENFLAG_NOCAPTURE_RPCAP
:samp
  SAMP_NOSAMP  SAMP_1_EVERY_N  SAMP_FIRST_AFTER_N_MS
:rpcap
  RMTAUTH_NULL  RMTAUTH_PWD


LIMITATIONS

The following limitations apply to this version of Net::Pcap.


EXAMPLES

See the 't' directory of the Net::Pcap distribution for examples on using this module.


COPYRIGHT

Copyright (c) 1999-2000 Tim Potter. All rights reserved. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.


SEE ALSO

pcap(3), tcpdump(8)

The source code for libpcap is available from ftp://ftp.ee.lbl.gov/libpcap.tar.Z


AUTHOR

Tim Potter <tpot@frungy.org>

 Net::Pcap - Interface to pcap LBL packet capture library