#!/usr/bin/perl

use strict;
use Net::Pcap;
use NetPacket::Ethernet;
use NetPacket::IP;
use NetPacket::TCP;
use Socket;
use IO::Socket;

use Geo::IP;
my $gi = Geo::IP->open("GeoLiteCity.dat", GEOIP_STANDARD);

my $err;

my $dev = "eth0";
unless (defined $dev) {
    $dev = Net::Pcap::lookupdev(\$err);
    if (defined $err) {
        die 'Unable to determine network device for monitoring - ', $err;
    }
}

my $server = IO::Socket::INET->new(
        Proto     => 'tcp',
        PeerPort => 10000,
        PeerAddr    => 'localhost' )
    or die "can't setup server";


#while (1) {
  #print $client "connection";
  my ($address, $netmask);
  print "Starting to send data\n";
  #$client->autoflush(1);
  my $object = Net::Pcap::open_live($dev, 1500, 0, 0, \$err);

  my $filter;
  Net::Pcap::compile(
      $object, 
      \$filter, 
      '(tcp[13] & 2!=0) && (not src net 192.168.0.0/16)',
      0, 
      $netmask
  ) && die 'Unable to compile packet capture filter';
  Net::Pcap::setfilter($object, $filter) &&
    die 'Unable to set packet capture filter';


  unless (defined $object) {
    die 'Unable to create packet capture on device ', $dev, ' - ', $err;
  }

  #print $server "ticklex";

  Net::Pcap::loop($object, -1, \&syn_packets, $server) ||
    die 'Unable to perform packet capture';
#}

sub syn_packets {
    my ($user_data, $header, $packet) = @_;
    my $ether_data = NetPacket::Ethernet::strip($packet);
    my $ip = NetPacket::IP->decode($ether_data);
    my $tcp = NetPacket::TCP->decode($ip->{'data'});

    #print "Debating" . $ip->{'src_ip'}. " \n";

    #if ($tcp->{'flags'} eq FIN) {
      my $record = $gi->record_by_addr($ip->{'src_ip'});
      if ($record) {
        print $ip->{'src_ip'}. " - " ."Sending ".$record->latitude.":".$record->longitude."\n";
        print $user_data $record->latitude.":".$record->longitude."-red:darkred\n";;
      }
    #}
}

