66 lines
1.7 KiB
Perl
Executable File
66 lines
1.7 KiB
Perl
Executable File
package My::geoip;
|
|
use strict;
|
|
use warnings;
|
|
# Remember to install the XS-version of this library.
|
|
use GeoIP2::Database::Reader;
|
|
use Try::Tiny;
|
|
use Scalar::Util qw( blessed );
|
|
|
|
sub new {
|
|
my $class = shift;
|
|
my $self = {};
|
|
bless ($self,$class);
|
|
$self->{'asn'} = GeoIP2::Database::Reader->new( file => '/usr/local/share/GeoIP/GeoLite2-ASN.mmdb' );
|
|
$self->{'country'} = GeoIP2::Database::Reader->new( file => '/usr/local/share/GeoIP/GeoLite2-Country.mmdb' );
|
|
return $self;
|
|
}
|
|
|
|
sub reload {
|
|
my $self = shift;
|
|
undef($self->{'asn'});
|
|
undef($self->{'country'});
|
|
$self->{'asn'} = GeoIP2::Database::Reader->new( file => '/usr/local/share/GeoIP/GeoLite2-ASN.mmdb' );
|
|
$self->{'country'} = GeoIP2::Database::Reader->new( file => '/usr/local/share/GeoIP/GeoLite2-Country.mmdb' );
|
|
return $self;
|
|
}
|
|
|
|
sub parse {
|
|
my $self = shift;
|
|
my $host = shift;
|
|
return { asn => 0, iso => '' } unless($host =~ m/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/);
|
|
my $r = {};
|
|
$r->{'asn'} = $self->geoip_h($host,'asn') || 0;
|
|
$r->{'iso'} = $self->geoip_h($host,'country') || '';
|
|
return $r;
|
|
}
|
|
|
|
sub geoip_h {
|
|
my $self = shift;
|
|
my $host = shift;
|
|
my $cmd = shift;
|
|
my $toret;
|
|
my $err = 0;
|
|
my $work;
|
|
my $func;
|
|
try {
|
|
$work = $self->{'country'}->country( ip => $host ) if($cmd eq 'country');
|
|
$work = $self->{'asn'}->asn( ip => $host ) if($cmd eq 'asn');
|
|
} catch {
|
|
$err = 1 if $_->isa('GeoIP::Error:IPAddressNotFound');
|
|
$err = 1 if $_->isa('GeoIP::Error::Generic');
|
|
$err = 1 unless blessed $_;
|
|
} finally {
|
|
unless($err) {
|
|
if($work) {
|
|
$toret = $work->country->iso_code() if($cmd eq 'country');
|
|
$toret = $work->autonomous_system_number() if($cmd eq 'asn');
|
|
# $toret = $work->$func();
|
|
}
|
|
}
|
|
};
|
|
return if($err);
|
|
return $toret;
|
|
}
|
|
|
|
1;
|