Created
June 28, 2013 06:33
-
-
Save sysr-q/5882877 to your computer and use it in GitHub Desktop.
Horrible, I know. Don't judge me.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import struct, socket, csv | |
def ip_to_decimal(ip): | |
return struct.unpack("!I", socket.inet_aton(ip))[0] | |
def read_list(ip_csv="/tmp/IpToCountry.csv"): | |
""" Read the entire IpToCountry CSV file into life. | |
:param ip_csv: the file we're reading from | |
""" | |
lookup = [] | |
with open(ip_csv, 'rb') as f: | |
reader = csv.reader(f) | |
for line in reader: | |
# The devil reincarnate catching us up | |
if len(line) != 7 or line[0].startswith('#'): | |
continue | |
lookup.append({ | |
"from": int(line[0]), | |
"to": int(line[1]), | |
"code": line[4], | |
"country": line[6] | |
}) | |
return lookup | |
def lookup_ip(ip): | |
if lookup_ip.lookup is None: | |
lookup_ip.lookup = read_list() | |
dec = ip_to_decimal(ip) | |
for l in lookup_ip.lookup: | |
over = l['from'] <= dec | |
under = l['to'] >= dec | |
if not over or not under: | |
continue | |
return l['country'] | |
# Fuck globals, let's put our list *on* | |
# the function that's using it. | |
lookup_ip.lookup = None |
danneu
commented
Jun 28, 2013
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment