GeoIP CSV to Bind ACL

Simple perl script for converting a GeoIP CSV file (latest version) to Bind ACL definitions.

#!/usr/bin/perl
 
use strict;
use warnings;
 
use Net::CIDR::Lite;
 
# Get files
my $infile  = $ARGV[0];
my $outfile = $ARGV[1];
 
# Open infile for reading
open(FILE, '<', $infile);
 
# Define iplist array
my %iplist;
 
# Loop infile
while(<FILE>) {
        # Set start, end and country variables
        my @line = split(/\"/, $_);
        my $start_ip = $line[1];
        my $end_ip   = $line[3];
        my $country  = $line[9];
 
        # Use the CIDR class to get networks in the range
        my $cidr = Net::CIDR::Lite->new;
        $cidr->add_range("$start_ip-$end_ip");
        my @networks = $cidr->list;
 
        # Put networks in the iplist array
        foreach(@networks) {
                $iplist{$country} .= "\t" . $_ . ';' . "\n";
        }
}
 
# Close the infile file handle
close FILE;
 
# Open outfile for writing
open(FILE, '>', $outfile);
 
# Loop iplist array
foreach my $country (sort keys %iplist) {
        # Write to outfile
        print FILE 'acl "' . $country . '" {' . "\n";
        print FILE $iplist{$country};
        print FILE '};' . "\n";
}
 
# Close the outfile file handle
close FILE;
 
# We're done

Simple usage:

$ ./geoip.pl GeoIPCountryWhois.csv countries.acl

You’ll need the Net::CIDR::Lite extension for Perl, in Debian/Ubuntu the package is called libnet-cidr-lite-perl.