Skip to content

Instantly share code, notes, and snippets.

@CLCL
Created July 25, 2013 06:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CLCL/6077358 to your computer and use it in GitHub Desktop.
Save CLCL/6077358 to your computer and use it in GitHub Desktop.
Apacheログとかで国特定したいときに使う/root/bin/ip2geo.pl。 GeoIPを調べるgeoiplookupコマンド(CentOS 6だったらEPELから入る)があることが前提。 パイプして使おう。
#!/usr/bin/perl
# CentOS 6: yum --enablerepo=epel install geoip
# GeoIPのデータベース更新は自分で設置すること!
use strict;
use warnings;
my $dic = {
};
while(<>) {
s/(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})/getcountrybyaddress($1)/eg;
print;
}
exit;
sub getcountrybyaddress {
my $ip = shift;
if ( exists $dic->{$ip} ) {
return $dic->{$ip};
}
my $res = _getcountrybyaddress( $ip );
$dic->{$ip} = $res;
return $res;
}
sub _getcountrybyaddress {
my $ip = shift;
my $country = `geoiplookup $ip`;
if ( $country =~ m/GeoIP.+: (..),.+$/sgo ) {
$country = $1;
} else {
$country = "??";
}
my $ip2 = sprintf "%3d.%3d.%3d.%3d", split('\.', $ip);
my $res = "[$country:$ip2]";
return $res;
}
__END__
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment