#
# Pcap.pm
#
# An interface to the LBL pcap(3) library. This module simply
# bootstraps the extensions defined in Pcap.xs
#
# Copyright (C) 2005-2009 Sebastien 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.
#
package Net::Pcap;
use strict;
use warnings;
use Exporter ();
use Carp;
# functions names
my @func_short_names = qw(
lookupdev findalldevs lookupnet
open_live open_dead open_offline loop breakloop close dispatch
next next_ex compile compile_nopcap setfilter freecode
offline_filter setnonblock getnonblock
dump_open dump dump_file dump_flush dump_close
datalink set_datalink datalink_name_to_val datalink_val_to_name
datalink_val_to_description
snapshot is_swapped major_version minor_version stats
file fileno get_selectable_fd geterr strerror perror
lib_version createsrcstr parsesrcstr open setbuff setuserbuffer
setmode setmintocopy getevent sendpacket
sendqueue_alloc sendqueue_queue sendqueue_transmit
);
my @func_long_names = map { "pcap_$_" } @func_short_names;
# functions aliases
{
no strict "refs";
for my $func (@func_short_names) {
*{ __PACKAGE__ . "::pcap_$func" } = \&{ __PACKAGE__ . "::" . $func }
}
}
{
no strict "vars";
$VERSION = '0.18';
@ISA = qw(Exporter);
%EXPORT_TAGS = (
'bpf' => [qw(
BPF_ALIGNMENT BPF_MAJOR_VERSION BPF_MAXBUFSIZE BPF_MAXINSNS
BPF_MEMWORDS BPF_MINBUFSIZE BPF_MINOR_VERSION BPF_RELEASE
)],
'datalink' => [qw(
DLT_AIRONET_HEADER DLT_APPLE_IP_OVER_IEEE1394 DLT_ARCNET
DLT_ARCNET_LINUX DLT_ATM_CLIP DLT_ATM_RFC1483 DLT_AURORA
DLT_AX25 DLT_CHAOS DLT_CHDLC DLT_CISCO_IOS DLT_C_HDLC
DLT_DOCSIS DLT_ECONET DLT_EN10MB DLT_EN3MB DLT_ENC DLT_FDDI
DLT_FRELAY DLT_HHDLC DLT_IBM_SN DLT_IBM_SP DLT_IEEE802
DLT_IEEE802_11 DLT_IEEE802_11_RADIO DLT_IEEE802_11_RADIO_AVS
DLT_IPFILTER DLT_IP_OVER_FC DLT_JUNIPER_ATM1 DLT_JUNIPER_ATM2
DLT_JUNIPER_ES DLT_JUNIPER_GGSN DLT_JUNIPER_MFR DLT_JUNIPER_MLFR
DLT_JUNIPER_MLPPP DLT_JUNIPER_MONITOR DLT_JUNIPER_SERVICES
DLT_LINUX_IRDA DLT_LINUX_SLL DLT_LOOP DLT_LTALK DLT_NULL
DLT_OLD_PFLOG DLT_PCI_EXP DLT_PFLOG DLT_PFSYNC DLT_PPP
DLT_PPP_BSDOS DLT_PPP_ETHER DLT_PPP_SERIAL DLT_PRISM_HEADER
DLT_PRONET DLT_RAW DLT_RIO DLT_SLIP DLT_SLIP_BSDOS DLT_SUNATM
DLT_SYMANTEC_FIREWALL DLT_TZSP DLT_USER0 DLT_USER1 DLT_USER2
DLT_USER3 DLT_USER4 DLT_USER5 DLT_USER6 DLT_USER7 DLT_USER8
DLT_USER9 DLT_USER10 DLT_USER11 DLT_USER12 DLT_USER13
DLT_USER14 DLT_USER15
)],
mode => [qw(
MODE_CAPT MODE_MON MODE_STAT
)],
openflag => [qw(
OPENFLAG_PROMISCUOUS OPENFLAG_DATATX_UDP OPENFLAG_NOCAPTURE_RPCAP
)],
pcap => [qw(
PCAP_ERRBUF_SIZE PCAP_IF_LOOPBACK
PCAP_VERSION_MAJOR PCAP_VERSION_MINOR
)],
rpcap => [qw(
RMTAUTH_NULL RMTAUTH_PWD
)],
sample => [qw(
PCAP_SAMP_NOSAMP PCAP_SAMP_1_EVERY_N PCAP_SAMP_FIRST_AFTER_N_MS
)],
source => [qw(
PCAP_SRC_FILE PCAP_SRC_IFLOCAL PCAP_SRC_IFREMOTE
)],
functions => [qw(
lookupdev findalldevs lookupnet
open_live open_dead open_offline
dump_open dump_close dump_file dump_flush
compile compile_nopcap setfilter freecode
offline_filter setnonblock getnonblock
dispatch next_ex loop breakloop
datalink set_datalink datalink_name_to_val
datalink_val_to_name datalink_val_to_description
snapshot get_selectable_fd
stats is_swapped major_version minor_version
geterr strerror perror lib_version
createsrcstr parsesrcstr
setbuff setuserbuffer setmode setmintocopy getevent sendpacket
sendqueue_alloc sendqueue_queue sendqueue_transmit
)],
);
@EXPORT = (
@{$EXPORT_TAGS{pcap}},
@{$EXPORT_TAGS{datalink}},
@func_long_names,
"UNSAFE_SIGNALS",
);
@EXPORT_OK = (
@{$EXPORT_TAGS{functions}},
@{$EXPORT_TAGS{mode}},
@{$EXPORT_TAGS{openflag}},
@{$EXPORT_TAGS{bpf}},
);
eval {
require XSLoader;
XSLoader::load('Net::Pcap', $VERSION);
1
} or do {
require DynaLoader;
push @ISA, 'DynaLoader';
bootstrap Net::Pcap $VERSION;
};
}
sub AUTOLOAD {
# This AUTOLOAD is used to 'autoload' constants from the constant()
# XS function.
no strict "vars";
my $constname;
($constname = $AUTOLOAD) =~ s/.*:://;
return if $constname eq "DESTROY";
croak "Net::Pcap::constant() not defined" if $constname eq 'constant';
my ($error, $val) = constant($constname);
if ($error) { croak $error; }
{
no strict "refs";
# Fixed between 5.005_53 and 5.005_61
#XXX if ($] >= 5.00561) {
#XXX *$AUTOLOAD = sub () { $val };
#XXX } else {
*$AUTOLOAD = sub { $val };
#XXX }
}
goto &$AUTOLOAD;
}
# pseudo-bloc to enable immediate (unsafe) signals delivery
sub UNSAFE_SIGNALS (&) {
$_[0]->();
}
# Perl wrapper for DWIM
sub findalldevs {
croak "Usage: pcap_findalldevs(devinfo, err)"
unless @_ and @_ <= 2 and ref $_[0];
# findalldevs(\$err), legacy from Marco Carnut 0.05
my %devinfo = ();
( ref $_[0] eq 'SCALAR' and return findalldevs_xs(\%devinfo, $_[0]) )
or croak "arg1 not a scalar ref"
if @_ == 1;
# findalldevs(\$err, \%devinfo), legacy from Jean-Louis Morel 0.04.02
ref $_[0] eq 'SCALAR' and (
( ref $_[1] eq 'HASH' and return findalldevs_xs($_[1], $_[0]) )
or croak "arg2 not a hash ref"
);
# findalldevs(\%devinfo, \$err), new, correct syntax, consistent with libpcap(3)
ref $_[0] eq 'HASH' and (
( ref $_[1] eq 'SCALAR' and return findalldevs_xs($_[0], $_[1]) )
or croak "arg2 not a scalar ref"
);
# if here, the function was called with incorrect arguments
ref $_[0] ne 'HASH' and croak "arg1 not a hash ref";
}
1;
__END__
=encoding UTF-8
=head1 NAME
Net::Pcap - Interface to the pcap(3) LBL packet capture library
=head1 VERSION
Version 0.18
=head1 SYNOPSIS
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
pcap_close($pcap);
sub process_packet {
my ($user_data, $header, $packet) = @_;
# do something ...
}
=head1 DESCRIPTION
C 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.
=head1 NOTES
=head2 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 L for a detailled
explanation.
Since C version 0.08, released in October 2005, the module
modified the internal variable C 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, C no longer modifies C by
itself, but provides facilities so the user has full control of how
signals are delivered.
First, the C function allows one to select how
signals are handled:
pcap_perl_settings(PERL_SIGNALS_UNSAFE);
pcap_loop($pcap, 10, \&process_packet, "");
pcap_perl_settings(PERL_SIGNALS_SAFE);
Then, to easily make code interruptable, C provides the
C pseudo-bloc:
UNSAFE_SIGNALS {
pcap_loop($pcap, 10, \&process_packet, "");
};
(Stolen from Rafael Garcia-Suarez's C)
=head1 EXPORTS
C supports the following C tags:
=over
=item *
C<:bpf> exports a few BPF related constants:
BPF_ALIGNMENT BPF_MAJOR_VERSION BPF_MAXBUFSIZE BPF_MAXINSNS
BPF_MEMWORDS BPF_MINBUFSIZE BPF_MINOR_VERSION BPF_RELEASE
=item *
C<:datalink> exports the data link types macros:
DLT_AIRONET_HEADER DLT_APPLE_IP_OVER_IEEE1394 DLT_ARCNET
DLT_ARCNET_LINUX DLT_ATM_CLIP DLT_ATM_RFC1483 DLT_AURORA
DLT_AX25 DLT_CHAOS DLT_CHDLC DLT_CISCO_IOS DLT_C_HDLC
DLT_DOCSIS DLT_ECONET DLT_EN10MB DLT_EN3MB DLT_ENC DLT_FDDI
DLT_FRELAY DLT_HHDLC DLT_IBM_SN DLT_IBM_SP DLT_IEEE802
DLT_IEEE802_11 DLT_IEEE802_11_RADIO DLT_IEEE802_11_RADIO_AVS
DLT_IPFILTER DLT_IP_OVER_FC DLT_JUNIPER_ATM1 DLT_JUNIPER_ATM2
DLT_JUNIPER_ES DLT_JUNIPER_GGSN DLT_JUNIPER_MFR DLT_JUNIPER_MLFR
DLT_JUNIPER_MLPPP DLT_JUNIPER_MONITOR DLT_JUNIPER_SERVICES
DLT_LINUX_IRDA DLT_LINUX_SLL DLT_LOOP DLT_LTALK DLT_NULL
DLT_OLD_PFLOG DLT_PCI_EXP DLT_PFLOG DLT_PFSYNC DLT_PPP
DLT_PPP_BSDOS DLT_PPP_ETHER DLT_PPP_SERIAL DLT_PRISM_HEADER
DLT_PRONET DLT_RAW DLT_RIO DLT_SLIP DLT_SLIP_BSDOS DLT_SUNATM
DLT_SYMANTEC_FIREWALL DLT_TZSP DLT_USER0 DLT_USER1 DLT_USER2
DLT_USER3 DLT_USER4 DLT_USER5 DLT_USER6 DLT_USER7 DLT_USER8
DLT_USER9 DLT_USER10 DLT_USER11 DLT_USER12 DLT_USER13
DLT_USER14 DLT_USER15
=item *
C<:pcap> exports the following C constants:
PCAP_ERRBUF_SIZE PCAP_IF_LOOPBACK
PCAP_VERSION_MAJOR PCAP_VERSION_MINOR
=item *
C<:mode> exports the following constants:
MODE_CAPT MODE_MON MODE_STAT
=item *
C<:openflag> exports the following constants:
OPENFLAG_PROMISCUOUS OPENFLAG_DATATX_UDP OPENFLAG_NOCAPTURE_RPCAP
=item *
C<:source> exports the following constants:
PCAP_SRC_FILE PCAP_SRC_IFLOCAL PCAP_SRC_IFREMOTE
=item *
C<:sample> exports the following constants:
PCAP_SAMP_NOSAMP PCAP_SAMP_1_EVERY_N PCAP_SAMP_FIRST_AFTER_N_MS
=item *
C<:rpcap> exports the following constants:
RMTAUTH_NULL RMTAUTH_PWD
=item *
C<:functions> short names of the functions (without the C<"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:
C, C, C, C, C, C.
Using these short names is now discouraged, and may be removed in the future.
=back
By default, this module exports the symbols from the C<:datalink> and
C<:pcap> tags, and all the functions, with the same names as the C library.
=head1 FUNCTIONS
All functions defined by C 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 C,
are passed that parameter as a reference. This is to retain
compatibility with previous versions of C.
=head2 Lookup functions
=over
=item B
Returns the name of a network device that can be used with
C function. On error, the C<$err> parameter
is filled with an appropriate error message else it is undefined.
B
$dev = pcap_lookupdev();
=item B
Returns a list of all network device names that can be used with
C function. On error, the C<$err> parameter
is filled with an appropriate error message else it is undefined.
B
@devs = pcap_findalldevs(\%devinfo, \$err);
for my $dev (@devs) {
print "$dev : $devinfo{$dev}\n"
}
=over
=item B
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 C 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 C, 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 C, where C<$err> is always the last argument.
=back
=item B
Determine the network number and netmask for the device specified in
C<$dev>. The function returns 0 on success and sets the C<$net> and
C<$mask> parameters with values. On failure it returns -1 and the
C<$err> parameter is filled with an appropriate error message.
=back
=head2 Packet capture functions
=over
=item B
Returns a packet capture descriptor for looking at packets on the
network. The C<$dev> parameter specifies which network interface to
capture packets from. The C<$snaplen> and C<$promisc> parameters specify
the maximum number of bytes to capture from each packet, and whether
to put the interface into promiscuous mode, respectively. The C<$to_ms>
parameter specifies a read timeout in milliseconds. The packet descriptor
will be undefined if an error occurs, and the C<$err> parameter will be
set with an appropriate error message.
B
$dev = pcap_lookupdev();
$pcap = pcap_open_live($dev, 1024, 1, 0, \$err)
or die "Can't open device $dev: $err\n";
=item B
Creates and returns a new packet descriptor to use when calling the other
functions in C. It is typically used when just using C
for compiling BPF code.
B
$pcap = pcap_open_dead(0, 1024);
=item 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 C<$err> parameter will be filled. Savefiles
are created using the C commands.
B
$pcap = pcap_open_offline($dump, \$err)
or die "Can't read '$dump': $err\n";
=item B
Read C<$count> packets from the packet capture descriptor C<$pcap> and call
the perl function C<&callback> with an argument of C<$user_data>.
If C<$count> is negative, then the function loops forever or until an error
occurs. Returns 0 if C<$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.
=over
=item *
C - the total length of the packet.
=item *
C - the actual captured length of the packet data. This corresponds
to the snapshot length parameter passed to C.
=item *
C - seconds value of the packet timestamp.
=item *
C - microseconds value of the packet timestamp.
=back
B
pcap_loop($pcap, 10, \&process_packet, "user data");
sub process_packet {
my ($user_data, $header, $packet) = @_;
# ...
}
=item B
Sets a flag that will force C or C
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 C in L for more
information.
=item B
Close the packet capture device associated with the descriptor C<$pcap>.
=item B
Collect C<$count> packets and process them with callback function
C<&callback>. if C<$count> is -1, all packets currently buffered are
processed. If C<$count> is 0, process all packets until an error occurs.
=item B
Return the next available packet on the interface associated with
packet descriptor C<$pcap>. Into the C<%header> hash is stored the received
packet header. If not packet is available, the return value and
header is undefined.
=item B
Reads the next available packet on the interface associated with packet
descriptor C<$pcap>, stores its header in C<\%header> and its data in
C<\$packet> and returns a success/failure indication:
=over
=item *
C<1> means that the packet was read without problems;
=item *
C<0> means that packets are being read from a live capture, and the
timeout expired;
=item *
C<-1> means that an error occurred while reading the packet;
=item *
C<-2> packets are being read from a dump file, and there are no more
packets to read from the savefile.
=back
=item B
Compile the filter string contained in C<$filter_str> and store it in
C<$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 C<$optimize> variable is true. The netmask of the
network device must be specified in the C<$netmask> parameter. The
function returns 0 if the compilation was successful, or -1 if there
was a problem.
=item B
Similar to C except that instead of passing a C<$pcap> descriptor,
one passes C<$snaplen> and C<$linktype> directly. Returns -1 if there was an
error, but the error message is not available.
=item B
Associate the compiled filter stored in C<$filter> with the packet
capture descriptor C<$pcap>.
=item B
Used to free the allocated memory used by a compiled filter, as created
by C.
=item B
Check whether C<$filter> matches the packet described by header C<%header>
and packet data C<$packet>. Returns true if the packet matches.
=item B
Set the I mode of a live capture descriptor, depending on the
value of C<$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
C<$err>.
In non-blocking mode, an attempt to read from the capture descriptor with
C will, if no packets are currently available to be read,
return 0 immediately rather than blocking waiting for packets to arrive.
C and C will not work in non-blocking mode.
=item B
Returns the I state of the capture descriptor C<$pcap>.
Always returns 0 on savefiles. If there is an error, it returns -1 and
sets C<$err>.
=back
=head2 Savefile commands
=over
=item B
Open a savefile for writing and return a descriptor for doing so. If
C<$filename> is C<"-"> data is written to standard output. On error, the
return value is undefined and C can be used to
retrieve the error text.
=item B
Dump the packet described by header C<%header> and packet data C<$packet>
to the savefile associated with C<$dumper>. The packet header has the
same format as that passed to the C callback.
B
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);
}
=item B
Returns the filehandle associated with a savefile opened with
C.
=item B
Flushes the output buffer to the corresponding save file, so that any
packets written with C but not yet written to the save
file will be written. Returns -1 on error, 0 on success.
=item B
Close the savefile associated with the descriptor C<$dumper>.
=back
=head2 Status functions
=over
=item B
Returns the link layer type associated with the given pcap descriptor.
B
$linktype = pcap_datalink($pcap);
=item B
Sets the data link type of the given pcap descriptor to the type specified
by C<$linktype>. Returns -1 on failure.
=item B
Translates a data link type name, which is a C name with the C
part removed, to the corresponding data link type value. The translation is
case-insensitive. Returns -1 on failure.
B
$linktype = pcap_datalink_name_to_val('LTalk'); # returns DLT_LTALK
=item B
Translates a data link type value to the corresponding data link type name.
B
$name = pcap_datalink_val_to_name(DLT_LTALK); # returns 'LTALK'
=item B
Translates a data link type value to a short description of that data link type.
B
$descr = pcap_datalink_val_to_description(DLT_LTALK); # returns 'Localtalk'
=item B
Returns the snapshot length (snaplen) specified in the call to
C.
=item B
This function returns true if the endianness of the currently open
savefile is different from the endianness of the machine.
=item B
Return the major version number of the pcap library used to write the
currently open savefile.
=item B
Return the minor version of the pcap library used to write the
currently open savefile.
=item B
Returns a hash containing information about the status of packet
capture device C<$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.
=over
=item *
C - the number of packets received by the packet capture software.
=item *
C - the number of packets dropped by the packet capture software.
=item *
C - the number of packets dropped by the network interface.
=back
=item B
Returns the filehandle associated with a savefile opened with
C or C if the device was opened
with C.
=item B
Returns the file number of the network device opened with C.
=item B
Returns, on Unix, a file descriptor number for a file descriptor on which
one can do a C