Skip to content

Generating country IP ranges lists #2

  • by

My original article about this topic is more that year old and was using Regional Internet Registries (RIRs) list as source and was in python. This post will describe other simple solution how to generate some country IP ranges list.

We can use Maxmind GeoLite database file GeoIPCountryCSV.zip. This time, script is in php. It will download zipped file into /tmp, and generate $country.cidr files in current directory.

<? 
echo "Downloading...\n";
copy("http://geolite.maxmind.com/download/geoip/database/GeoIPCountryCSV.zip","/tmp/GeoIPCountryCSV.zip");
$f=fopen('zip:///tmp/GeoIPCountryCSV.zip#GeoIPCountryWhois.csv','r');
echo "Generating";
$data=NULL;
$c=0;
while (($line = fgetcsv($f,0,',')) !== FALSE) {
        $country=$line[4];
        if ((($c++) % 1000==0)) echo ".";
        $mask=round(32-log(ip2long($line[1])-ip2long($line[0]),2));
        if (strpos($mask,'INF')!== false) $mask='32';
        $data[$country][]="$line[0]/$mask\n";
}

echo "\n";
foreach ($data as $country => $ranges) {
        echo "Writing $country\n";
        array_unshift($ranges,"# Generated ".date('r')."\n");
        file_put_contents("$country.cidr",$ranges);
}
?>

Which one do you like more?

Leave a Reply

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