1#!perl -T 2use strict; 3use Test::More; 4use Net::Pcap; 5use lib 't'; 6use Utils; 7 8my $total = 3; # number of packets to process 9 10plan skip_all => "pcap_next_ex() is not available" unless is_available('pcap_next_ex'); 11plan skip_all => "slowness and random failures... testing pcap_next_ex() is a PITA"; 12plan skip_all => "must be run as root" unless is_allowed_to_use_pcap(); 13plan skip_all => "no network device available" unless find_network_device(); 14plan tests => $total * 17 + 4; 15 16my $has_test_exception = eval "use Test::Exception; 1"; 17 18my($dev,$pcap,$net,$mask,$filter,$data,$r,$err) = ('','','','','','',''); 19my %header = (); 20 21# Find a device and open it 22$dev = find_network_device(); 23Net::Pcap::lookupnet($dev, \$net, \$mask, \$err); 24$pcap = Net::Pcap::open_live($dev, 1024, 1, 100, \$err); 25 26# Testing error messages 27SKIP: { 28 skip "Test::Exception not available", 4 unless $has_test_exception; 29 30 # next_ex() errors 31 throws_ok(sub { 32 Net::Pcap::next_ex() 33 }, '/^Usage: Net::Pcap::next_ex\(p, pkt_header, pkt_data\)/', 34 "calling next_ex() with no argument"); 35 36 throws_ok(sub { 37 Net::Pcap::next_ex(0, 0, 0) 38 }, '/^p is not of type pcap_tPtr/', 39 "calling next_ex() with incorrect argument type for arg1"); 40 41 throws_ok(sub { 42 Net::Pcap::next_ex($pcap, 0, 0) 43 }, '/^arg2 not a hash ref/', 44 "calling next_ex() with incorrect argument type for arg2"); 45 46 throws_ok(sub { 47 Net::Pcap::next_ex($pcap, \%header, 0) 48 }, '/^arg3 not a scalar ref/', 49 "calling next_ex() with incorrect argument type for arg3"); 50 51} 52 53# Compile and set a filter 54Net::Pcap::compile($pcap, \$filter, "ip", 0, $mask); 55Net::Pcap::setfilter($pcap, $filter); 56 57# Test next_ex() 58my $count = 0; 59for (1..$total) { 60 my($packet, %header); 61 eval { $r = Net::Pcap::next_ex($pcap, \%header, \$packet) }; 62 is( $@, '', "next_ex()" ); 63 is( $r, 1, " - should return 1 ($r)" ); 64 65 for my $field (qw(len caplen tv_sec tv_usec)) { 66 ok( exists $header{$field}, " - field '$field' is present" ); 67 ok( defined $header{$field}, " - field '$field' is defined" ); 68 like( $header{$field}, '/^\d+$/', " - field '$field' is a number" ); 69 } 70 71 ok( $header{caplen} <= $header{len}, " - coherency check: packet length (caplen <= len)" ); 72 73 ok( defined $packet, " - packet is defined" ); 74 is( length $packet, $header{caplen}, " - packet has the advertised size" ); 75 76 $count++; 77} 78 79is( $count, $total, "all packets processed" ); 80 81Net::Pcap::close($pcap); 82