Skip to content

Instantly share code, notes, and snippets.

@georgexsh
Created September 16, 2015 10:10
Show Gist options
  • Save georgexsh/54f5650e0807a003db69 to your computer and use it in GitHub Desktop.
Save georgexsh/54f5650e0807a003db69 to your computer and use it in GitHub Desktop.
ipip.net lib
# coding: utf-8
import struct
# opti
from socket import inet_aton
from bisect import bisect_left
_unpack_ul_little = lambda b: struct.unpack("<L", b)[0]
_unpack_ul_big = lambda b: struct.unpack(">L", b)[0]
_unpack_us_big = lambda b: struct.unpack(">H", b)[0]
class IPIPDatabase(object):
def __init__(self, filename):
self._load(filename)
def _load(self, filename):
self._ranges = []
self._locs = []
with open(filename, 'rb') as f:
buff = f.read()
self._load_datx(buff)
def _load_datx(self, buff):
text_start = _unpack_ul_big(buff[:4]) - 256*256*4
offset = 4 + 256*256*4
while offset < text_start:
ip_range = buff[offset:offset+4]
text_offset = _unpack_ul_little(buff[offset+4:offset+7] + b'\0') + text_start
text_length = _unpack_us_big(buff[offset+7:offset+9])
loc_text = buff[text_offset:text_offset+text_length].strip()
self._ranges.append(ip_range)
self._locs.append(loc_text)
offset += 9
def find(self, ip):
i = bisect_left(self._ranges, inet_aton(ip))
return self._locs[i]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment