Tcpdump unique host filter

Filter for unique host:

#!/usr/bin/perl
#
# Unique line filter
#
# Usage:
#
# tcpdump -i ethX -nn -s 0 [optional tcpdump filter] | grep --line-buffered [optional filter]
   | awk {'print $3'} | awk -F"[ .]" '{print $1"."$2"."$3"."$4}' | ./thisFilter
#

use Socket;
use Net::DNS;

# Collectie aanmaken
my %hosts;
my $answer;
my $namer;

# DNS
my $DnsServer = "172.16.32.1";
my $res = new Net::DNS::Resolver;
$res->nameservers($DnsServer);
my $ip;

# Resolve DNS Name
sub myCheckDNSName
{
   $ipnumber = $_[0];

   $ip = new Net::IP($ipnumber,4);

   if ($ip)
   {
        # resolved host
        $answer = $res->query($ip->reverse_ip(),'PTR');
        $namer = $answer->{'answer'}[0];
        $resolved = $namer->{'ptrdname'};
        return ($resolved);
   }
   else
   {
        return ("Not resolved");
   }
}

while (<>) {
        my $line = $_;
        $line =~ s/\r?\n//g;

        if ($line =~ m/^(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)\.(\d\d?\d?)/ )
        {
         if (exists $hosts{$line})
         {
            # bestaat al, niks doen!
            # print "exists: $line";
         }
         else
         {
            $now = localtime(time);

            # reverse dns
            $resolved_name = myCheckDNSName($line);
            $hosts{$line} = "($resolved_name) $now ";

            print "-----------------------------------<<<< update >>>>----------------------------------\n\n";
            foreach $value (sort {$hosts{$a} cmp $hosts{$b} } keys %hosts)
            {
               print " $value $hosts{$value} \n";
            }
            print "\n";
         }
        }
}

One thought on “Tcpdump unique host filter

  1. The usage comment line in the perl script was truncated.

    This id how it appears:
    tcpdump | cat file | grep –line-buffered [opt:| awk {'print $3'} | awk -F"[ .]” ‘{print $1″.”$2″.”$3″.”$4}’

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>