1Easy(3) User Contributed Perl Documentation Easy(3)
2
3
4
5Net::Pcap::Easy - Net::Pcap is awesome, but it's difficult to bootstrap
6
8 use strict;
9 use warnings;
10 use Net::Pcap::Easy;
11
12 # all arguments to new are optoinal
13 my $npe = Net::Pcap::Easy->new(
14 dev => "lo",
15 filter => "host 127.0.0.1 and (tcp or icmp)",
16 packets_per_loop => 10,
17 bytes_to_capture => 1024,
18 promiscuous => 0, # true or false
19
20 tcp_callback => sub {
21 my ($npe, $ether, $ip, $tcp, $header ) = @_;
22 my $xmit = localtime( $header->{tv_sec} );
23
24 print "$xmit TCP: $ip->{src_ip}:$tcp->{src_port}"
25 . " -> $ip->{dest_ip}:$tcp->{dest_port}\n";
26
27 print "\t$ether->{src_mac} -> $ether->{dest_mac}\n" if $SHOW_MAC;
28 },
29
30 icmp_callback => sub {
31 my ($npe, $ether, $ip, $icmp, $header ) = @_;
32 my $xmit = localtime( $header->{tv_sec} );
33
34 print "$xmit ICMP: $ether->{src_mac}:$ip->{src_ip}"
35 . " -> $ether->{dest_mac}:$ip->{dest_ip}\n";
36 },
37 );
38
39 1 while $npe->loop;
40
42 This module is little more than a collection of macros and convenience
43 functions. Net::Pcap does all the real work (of lifting libpcap into
44 perl anyway).
45
46 Every time I began to write a Net::Pcap application, I had to go figure
47 out all these little things all over again. Most of the functions
48 return C-style truth values (0 is ok, non-zero is a problem),
49 installing a filter is un-obvious, how to disassemble the packet is a
50 process of reading four or five pods (e.g. NetPacket::UDP), etc...
51
52 What I wanted was one POD that covered everything you need to know, and
53 a wrapper that makes everything perl-esque.
54
56 There are a couple convenience functions available, two control
57 functions, and various blessed-hash keys at your disposal.
58
60 "dev()"
61 Returns the name of the device you're sniffing.
62
63 "pcap()"
64 This returns the actual Net::Pcap reference. If you need to call a
65 function from Net::Pcap that requires a pcap object argument, this
66 would be the object to pass.
67
68 "network()"
69 Returns the network the device is on (as a text ip number, e.g.,
70 192.168.1.0).
71
72 "netmask()"
73 Returns the netmask of the device (as a text ip number, e.g.,
74 255.255.255.0).
75
76 "cidr()"
77 Returns the network of the device as a Net::Netmask object, which
78 string-interpolates to CIDR notation.
79
80 "raw_network()"
81 This is the long (see pack's "l") value of the network.
82
83 "raw_netmask()"
84 This is the long (see pack's "l") value of the netmask.
85
86 "is_local($ip_or_network)"
87 Returns true when the first argument is an IP (as text) or network
88 (as text or as a Net::Netmask object) is "in" the listening
89 network. See Net::Netmask for details on this.
90
91 "loop()"
92 Call this over and over until your program is done listening. It
93 collects a number of packets equal to "packets_per_loop" (see
94 below) and passes each packet one at a time to any callbacks you've
95 specified (see below).
96
97 The function returns the number of packets processed (normally the
98 same as "packets_per_loop"), and therefore less than
99 "packets_per_loop" or 0 at the end of a packet file.
100
101 It returns the empty list or the undef value in the case of an
102 error.
103
104 "stats()"
105 Returns a hash (or hashref) containing collection statistics.
106
107 {
108 drop => 0, # packets missed by libpcap
109 ifdrop => 0, # packets missed by interface
110 recv => 1, # packets captured
111 }
112
113 "new()"
114 The details are in the OPTIONS section below.
115
116 "close()"
117 Close the pcap. Intended to be useful from SIG/while loops like
118 this.
119
120 $SIG{INT} = sub { $npe->close };
121 while( $npe->loop ) {
122 # ... blah
123 }
124
126 Net::Pcap::Easy takes a small number of options, each of which is
127 purely optional, although it's recommended to specify as many as
128 possible, particularly the device.
129
130 The options can only be specified as arguments to the "new()" method.
131
132 "dev"
133 The device you wish to listen on, eth0, "Local Area Connection,"
134 etc. It's a good idea to specify this device, but if you don't,
135 Net::Pcap::Easy will attempt to locate it with Net::Pcap's
136 "lookupdev()" method. Odds are good that it won't find the device
137 you want, your mileage may vary.
138
139 my $npe = Net::Pcap::Easy->new(
140 dev => "eth0",
141 filter => "icmp",
142 packets_per_loop => 10,
143
144 icmp_callback => sub { warn "ping or something!\n" },
145 );
146
147 1 while $npe->loop; # loop() returns 10, 10, 10, until you hit ^C
148 exit 0;
149
150 If passed a special filename, "file:/path/name", Net::Pcap::Easy
151 will try to open that file and read it as the device. This will
152 break functions like "network", "netmask" and the raw versions --
153 their results are undefined.
154
155 bash$ tcpdump -c 6 -i lo -w lo.data
156
157 my $npe = Net::Pcap::Easy->new(
158 dev => "file:./lo.data",
159 packets_per_loop => 3,
160 icmp_callback => sub { warn "ping or something!\n" },
161 );
162
163 1 while $npe->loop; # loop() returns 3 twice, then a 0
164 exit 0;
165
166 "packets_per_loop"
167 The number of packets to capture on each loop. Most likely, it's
168 more efficient to capture more than one packet per loop. But if
169 you capture too many your program will seem to stutter. Likely
170 there's a nice balance somewhere.
171
172 Net::Pcap::Easy defaults to a value of 32 packets per loop. The
173 minimum is 1 and Net::Pcap::Easy will silently discard values lower
174 than 1, using the default PPL instead.
175
176 "bytes_to_capture"
177 The number of bytes to capture from each packet. Defaults to 1024.
178 The minimum is 256 and Net::Pcap::Easy will silently discard values
179 lower than this, simply using the minimum instead. If you really
180 really want to capture less, you can change the minimum by setting
181 $Net::Pcap::Easy::MIN_SNAPLEN to whatever value you like.
182
183 "timeout_in_ms"
184 Use this to set a timeout for the "loop()" method (see below). The
185 default is 0, meaning: wait until I get my packets. If you set
186 this to some number greater than 0, the "loop()" function may
187 return before capturing the requested PPL.
188
189 Note that this probably doesn't ever do anything useful. The
190 libpcap timeout doesn't have any useful relationship to actually
191 timing out on most platforms.
192
193 <https://github.com/the-tcpdump-group/libpcap/issues/86> (et al).
194
195 The simplest solution for this is to use forks. There is an
196 example of this included in the distribution.
197
198 <https://github.com/jettero/net--pcap--easy/blob/master/examples/forks.pl>
199
200 "promiscuous"
201 This is a boolean value (in the perl sense) indicating whether you
202 wish to capture packets not intended for the listening interface.
203 The default is false.
204
205 "pcap"
206 You can optionally build the Net::Pcap object yourself. Presumably
207 you have something custom in mind if you choose to do this.
208 Choosing to do this will disable various features (like populating
209 the network and netmask fields);
210
211 *_callback
212 The captured packets are passed to code refs. There are a variety
213 of callback types to choose from. Each callback must be a code
214 ref.
215
216 This is covered in more detail below.
217
219 Only one callback will get called for each packet.
220
221 If a packet would match multiple callbacks it will try to call the most
222 specific match first (whatever that might mean). The callbacks are
223 listed in order of preference.
224
225 "tcp_callback"
226 The callback will receive as arguments:
227
228 my ($npe, $ether, $ip, $tcp, $header ) = @_;
229
230 $npe is the Net::Pcap::Easy object, $ether is a NetPacket::Ethernet
231 object, $ip is a NetPacket::IP object, $tcp is a NetPacket::TCP
232 object and $header is a Net::Pcap header object.
233
234 Each "Net::Pcap" object contains the length of the entire packet
235 "{len}", the length captured by the libpcap "{caplen}", and the
236 timestamp from the packet header "{tv_sec}"/"{tv_usec}" —
237 "{tv_sec}" is seconds since the epoch (see: "localtime" in
238 perlfunc) and "{tv_usec}" is microseconds since that second [I
239 think].
240
241 Each "NetPacket" object contains a "{data}" field that holds the
242 data below the packet headers. Unsurprisingly, the "{dest_mac}"
243 and "{src_mac}" are available in the $ether object, the "{src_ip}"
244 and "{dest_ip}" are in the $ip object and the "{dest_port}" and
245 "{src_port}" are in the $tcp object.
246
247 Example:
248
249 tcp_callback => sub {
250 my ($npe, $ether, $ip, $tcp, $header ) = @_;
251
252 print "TCP: $ip->{src_ip}:$tcp->{src_port} -> $ip->{dest_ip}:$tcp->{dest_port}\n";
253 print "\t$ether->{src_mac} -> $ether->{dest_mac}\n" if $SHOW_MAC;
254 }
255
256 "udp_callback"
257 The callback will receive as arguments:
258
259 my ($npe, $ether, $ip, $udp, $header ) = @_;
260
261 This works exactly like the "tcp_callback" except that instead of
262 $tcp, the callback is passed a $udp argument that is a
263 NetPacket::UDP object. The $udp object has a "{src_port}" and
264 "{dest_port}", just like you'd expect.
265
266 "icmp_callback"
267 The callback will receive as arguments:
268
269 my ($npe, $ether, $ip, $icmp, $header ) = @_;
270
271 This callback is quite similar to the
272 "tcp_callback"/"udp_callback"s, but the NetPacket::ICMP object
273 doesn't have ports. See that page for details on parsing ICMP
274 packets and/or use the more specific callbacks below, instead of
275 parsing the "{type}" by hand.
276
277 Technically these ICMP are out of preference order (they should be
278 above, not below the "icmp_callback"). However, they all receive
279 identical arguments to the generic "icmp_callback" ...
280
281 Specific ICMP Callbacks: "icmpechoreply_callback",
282 "icmpunreach_callback", "icmpsourcequench_callback",
283 "icmpredirect_callback", "icmpecho_callback",
284 "icmprouteradvert_callback", "icmproutersolicit_callback",
285 "icmptimxceed_callback", "icmpparamprob_callback",
286 "icmptstamp_callback", "icmptstampreply_callback",
287 "icmpireq_callback", "icmpireqreply_callback"
288
289 "igmp_callback"
290 The callback will receive as arguments:
291
292 my ($npe, $ether, $ip, $igmp, $header ) = @_;
293
294 Please see the NetPacket::IGMP page for details on the $igmp
295 argument.
296
297 "ipv4_callback"
298 The callback will receive as arguments:
299
300 my ($npe, $ether, $ip, $spo, $header ) = @_;
301
302 $spo is any of NetPacket::TCP, NetPacket::UDP, NetPacket::ICMP,
303 NetPacket::IGMP, or "undef" (see the default callback, below, for
304 an example on parsing the $spo).
305
306 The biggest difference between the "ipv4_callback" and the
307 "default_callback" is that you can say for sure the third argument
308 is a NetPacket::IP object.
309
310 "arp_callback"
311 The callback will receive as arguments:
312
313 my ($npe, $ether, $arp, $header ) = @_;
314
315 This callback is also quite similar to the
316 "tcp_callback"/"udp_callback"/"icmp_callback"s. See the
317 NetPacket::ARP page for details on parsing ARP packets and/or use
318 the more specific callbacks below, instead of parsing the "{type}"
319 by hand.
320
321 Technically these ARP are out of preference order (they should be
322 above, not below the "arp_callback"). However, they all receive
323 identical arguments to the generic "arp_callback" ...
324
325 Specific ARP Callbacks: "arpreply_callback", "arpreq_callback",
326 "rarpreply_callback", "rarpreq_callback"
327
329 "ipv6_callback"
330 The callback will receive as arguments:
331
332 my ($npe, $ether, $header ) = @_;
333
334 There doesn't seem to be a "NetPacket" decoder for this type of
335 packet, so, this callback gets only the "NetPacket::Ethernet"
336 object.
337
338 "snmp_callback"
339 The callback will receive as arguments:
340
341 my ($npe, $ether, $header ) = @_;
342
343 There doesn't seem to be a "NetPacket" decoder for this type of
344 packet, so, this callback gets only the "NetPacket::Ethernet"
345 object.
346
347 "ppp_callback"
348 The callback will receive as arguments:
349
350 my ($npe, $ether, $header ) = @_;
351
352 There doesn't seem to be a "NetPacket" decoder for this type of
353 packet, so, this callback gets only the "NetPacket::Ethernet"
354 object.
355
356 "appletalk_callback"
357 The callback will receive as arguments:
358
359 my ($npe, $ether, $header ) = @_;
360
361 There doesn't seem to be a "NetPacket" decoder for this type of
362 packet, so, this callback gets only the "NetPacket::Ethernet"
363 object.
364
366 "default_callback"
367 Anything not captured above will go to this callback if specified.
368 It receives a variety of arguments, differing based on the packet
369 types. There are seven types of calls it might receive:
370
371 my ($npe, $ether, $ip, $tcp, $header ) = @_; # TCP packets
372 my ($npe, $ether, $ip, $udp, $header ) = @_; # UDP packets
373 my ($npe, $ether, $ip, $icmp, $header ) = @_; # ICMP packets
374 my ($npe, $ether, $ip, $igmp, $header ) = @_; # IGMP packets
375 my ($npe, $ether, $ip, $header ) = @_; # other IP packets
376 my ($npe, $ether, $arp, $header ) = @_; # ARP packets
377 my ($npe, $ether, $header ) = @_; # everything else
378
379 Example:
380
381 default_callback => sub {
382 my ($npe, $ether, $po, $spo, $header ) = @_;
383
384 if( $po ) {
385 if( $po->isa("NetPacket::IP") ) {
386 if( $spo ) {
387 if( $spo->isa("NetPacket::TCP") ) {
388 print "TCP packet: $po->{src_ip}:$spo->{src_port} -> ",
389 "$po->{dest_ip}:$spo->{dest_port}\n";
390
391 } elsif( $spo->isa("NetPacket::UDP") ) {
392 print "UDP packet: $po->{src_ip}:$spo->{src_port} -> ",
393 "$po->{dest_ip}:$spo->{dest_port}\n";
394
395 } else {
396 print "", ref($spo), ": $po->{src_ip} -> ",
397 "$po->{dest_ip} ($po->{type})\n";
398 }
399
400 } else {
401 print "IP packet: $po->{src_ip} -> $po->{dest_ip}\n";
402 }
403
404 } elsif( $po->isa("NetPacket::ARP") ) {
405 print "ARP packet: $po->{sha} -> $po->{tha}\n";
406 }
407
408 } else {
409 print "IPv6 or appletalk or something... huh\n";
410 }
411 }
412
414 The NetPacket stuff is a little slow because it's object oriented and
415 therefore involves many function calls. If you have a need for
416 something really fast, you can supply something to the "loop()"
417 function. This will avoid all internal processing of the packet and
418 you will be completely on your own regarding the packet processing.
419 Also, the "loop()" will fail to return the number of processed packets
420 since it didn't process any.
421
422 Warning: The following is not "Easy" like the rest of this package and
423 assumes knowledge of the network layers (2-Ethernet, 3-IPv4, 4-TCP/UDP)
424
425 1 while defined
426 # NOTE: defined, since loop returns 0 and undef on error
427
428 $npe->loop( sub {
429 my ($user_data, $header, $raw_bytes) = @_;
430
431 # $user_data is literally "user data"
432
433 # $header is like this:
434 # { caplen => 96, len => 98, tv_sec => 1245963414, tv_usec => 508250 },
435
436 print unpack("H*", $raw_bytes), "\n";
437
438 my $packet = $_[-1]; # this is the same as $raw_bytes, but I prefer
439 # the word packet and rarely examin the other
440 # elements of @_
441
442 # Calculating precisely what you need is quite a bit faster than
443 # decoding the whole packet -- although it's not exactly "Easy." Say
444 # we're interested in IPv4 TCP and UDP packets only... The following
445 # assumes *Ethernet* and we don't check it!
446
447 my $l3protlen = ord substr $packet, 14, 1; # the protocol and length
448 my $l3prot = $l3protlen & 0xf0 >> 2; # the protocol part
449
450 return unless $l3prot == 4; # return unless IPv4
451
452 my $l4prot = ord substr $packet, 23, 1; # the L4protocol
453
454 # return unless it's udp(17) or tcp(6)
455 return unless $l4prot == 6 or $l4prot == 17;
456
457 my $l3hlen= ($l3protlen & 0x0f) * 4; # number of 32bit words
458 my $l4 = 14 + $l3hlen; # the layer 4 data starts here
459
460 # my $src_ip = substr $packet, 26, 4; # these are netowrk order packed
461 # my $dst_ip = substr $packet, 30, 4; # but they're pretty easy to convert
462
463 # The ord of the individual bytes of an IP are what we usually
464 # see... join(".", map { ord $_} split "", "\xc0\xa8\x01\x01")
465 # gives 192.168.1.1
466
467 # Here, I'm only interestd in local network downloads
468 my $upload = 0;
469
470 if( substr($packet, 30, 2) eq "\xc0\xa8" ) { # 192.168.0.0/16x.x
471 # download direction
472
473 my $cust = ord(substr($packet, 32,1)) .'.'. ord(substr($packet, 33,1));
474 my $port = unpack 'n', substr $packet, $l4+0, 2; # src port
475
476 # On my network, in this sense, the last two bytes idenfity a "customer"
477 # the source port (on a download) is the port the protocol operates on.
478 # 80 for http, 110 for pop3, etc. Unpack('n', blarg) gives the
479 # network order 2-byte port number as a Perl number.
480
481 _do_things($cust, $port);
482
483 } elsif( $upload ) {
484 # upload direction
485
486 my $cust = ord(substr($packet, 28,1)) .'.'. ord(substr($packet, 29,1));
487 my $port = unpack 'n', substr $packet, $l4+2, 2; # dst port
488
489 # In the upload direction, the protocol port is the dst port.
490
491 _do_things($cust, $port);
492 }
493
494 });
495
497 Note, silly though this may seem, if the packets are received by a non-
498 Ethernet device, they will be encapsulated in a fake Ethernet frame
499 before being passed to the callbacks. This design decision (or kludge)
500 was chosen to help keep the module simple.
501
503 Paul Miller "<jettero@cpan.org>"
504
505 I am using this software in my own projects... If you find bugs,
506 please please please let me know. Actually, let me know if you find it
507 handy at all. Half the fun of releasing this stuff is knowing that
508 people use it.
509
510 If you see anything wrong with the callbacks, the docs, or anything:
511 Definitely let me know! rt.cpan, irc, email, whatever. Just let me
512 know.
513
514 Patches welcome!
515 Please note that your patches should avoid changing the API for
516 downstream users. Sometimes this means making bad design decisions
517 (e.g., sticking fake Ethernet headers on non-Ethernet frames).
518
519 ANDK
520 Fixed various things in the init functions. See RT #47324.
521
522 Daniel Roethlisberger
523 Helped Net::Pcap::Easy load non Ethernet frames.
524
525 Jerry Litteer
526 Needed Ethernet $header information for his project, so he sent
527 patches.
528
530 Copyright (c) 2009-2010 Paul Miller
531
533 This module is free software. You can redistribute it and/or modify it
534 under the terms of the Artistic License 2.0.
535
536 This program is distributed in the hope that it will be useful, but
537 without any warranty; without even the implied warranty of
538 merchantability or fitness for a particular purpose.
539
541 perl(1), Net::Pcap, Net::Pcap, Net::Netmask, NetPacket::Ethernet,
542 NetPacket::IP, NetPacket::ARP, NetPacket::TCP, NetPacket::UDP,
543 NetPacket::IGMP, NetPacket::ICMP
544
545
546
547perl v5.34.0 2022-01-21 Easy(3)