Home:ALL Converter>Parsing UDP packets from offline pcap file with Perl script

Parsing UDP packets from offline pcap file with Perl script

Ask Time:2013-12-04T10:03:46         Author:ggenova79

Json Formatter

I'm hoping someone can help me with the following issue. I wrote a Perl script to parse all the UDP packets from an offline Pcap file and then write all the UDP data out to a file using Net::Pcap and NetPacket. It works fine on most of the pcap files. I currently have a Pcap file where there are 4 extra bytes (Null/Loopback, Family: IP (2)) before the IP Header. This is causing my script to check the protocol type using the wrong byte. I have looked all over and tried to offset the byte, but can't figure it out. Is there some way to check for a null link type while in the loop(), remove the extra bytes and save it back to a pcap file. I tried a number of ways, but each time it gets me only so far until I hit another problem. I have seen some examples where a filter is set in the loop method, but that is only of live captures. Any suggestions?

Wireshark image

perl script:

use Net::Pcap qw(:functions);
use NetPacket::Ethernet qw(:types);
use NetPacket::IP qw(:protos);
use NetPacket::UDP;
use NetPacket::TCP;

$pcap = Net::Pcap::open_offline($_[0], \$err) or die "Can't read '$_[0]': $err\n";
Net::Pcap::loop($pcap, $maxpkts, \&process_packet, '');
Net::Pcap::close($pcap);

sub process_packet {
($user_data, $header, $packet) = @_;
my $ip = NetPacket::IP -> decode($packet);
# extract UDP packets from pcap file
if ($ip -> {proto} == IP_PROTO_UDP) {
    my $udp = NetPacket::UDP -> decode($ip -> {data});
    if (($udp -> {len} == 62) && ($udp -> {src_port} == 16800 || $udp -> {src_port} == 16700)) {
        $seconds = $header -> {tv_sec};
        $milliseconds = $header -> {tv_usec} / 1000000;
        $newtime = $seconds + $milliseconds;
        $count++;
        if ($count > 1) {
            $delta = $newtime - $oldtime;
        }
        print $pcap_tempfile $udp->{data};
        print "Packet $count: ", "DELTA ",  "\n";
        printf ".%06d", $header -> {tv_usec};
        $oldtime = $newtime;
    }
} else {

}

}

Author:ggenova79,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/20365456/parsing-udp-packets-from-offline-pcap-file-with-perl-script
yy