Below is the file 'ip2country.py' from this revision. You can also download the file.
#!/usr/bin/env python import pysqlite2.dbapi2 as sqlite import sys import csv create_table = """\ CREATE TABLE ip_to_country ( ip_start integer NOT NULL, ip_end integer NOT NULL, country2 char(2) NOT NULL, country3 char(3) NOT NULL, country varchar(128) NOT NULL ); """ def init_db(dbfile): conn = sqlite.connect(dbfile, isolation_level=None) cursor = conn.cursor() cursor.execute("BEGIN") cursor.execute(create_table) cursor.execute("CREATE INDEX ip_to_country_idx ON ip_to_country (ip_start, ip_end);") for row in csv.reader(open('ip-to-country.csv')): cursor.execute("INSERT INTO ip_to_country (ip_start,ip_end,country2,country3,country) VALUES (?,?,?,?,?)", row) cursor.execute("COMMIT") def ip_to_integer(ip_address): rv = 0l s = ip_address.split('.') if len(s) != 4: return 0 for i, p in enumerate(s): p = int(p) rv += p if i != 3: rv = rv << 8 return rv def lookup(dbfile, ip_address): conn = sqlite.connect(dbfile, isolation_level=None) i = ip_to_integer(ip_address) cursor = conn.cursor() cursor.execute("SELECT * FROM ip_to_country WHERE ip_start <= %d AND ip_end >= %d" % (i,i)) print cursor.fetchall() def countrystats(dbfile): conn = sqlite.connect(dbfile, isolation_level=None) cursor = conn.cursor() for ip in sys.stdin.xreadlines(): i = ip_to_integer(ip) cursor.execute("SELECT country FROM ip_to_country WHERE ip_start <= %d AND ip_end >= %d" % (i,i)) res = cursor.fetchall() if res and len(res) != 0: print res[0][0] def error(mesg): sys.stderr.write(mesg+'\n') sys.exit(1) if __name__ == '__main__': if len(sys.argv) < 2: error("usage: ip2country.py <command> [args..]\n") handlers = { 'init' : init_db, 'lookup' : lookup, 'countrystats' : countrystats } command = sys.argv[1] if not handlers.has_key(command): error("unknown command") apply(handlers[command], sys.argv[2:])