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