Add support for IPV6 requests in iptogeo class

This commit is contained in:
Grégory Soutadé 2016-02-24 19:17:40 +01:00
parent 1f789284dd
commit 911f909f96
1 changed files with 41 additions and 7 deletions

View File

@ -60,13 +60,30 @@ class IPToGeo(object):
self._socket.settimeout(self._timeout)
self._socket.connect((self._remote_addr, self._remote_port))
def _create_request(self, ip):
def _extend_ipv6(self, ipv6):
tmp = ''
for s in ipv6.split(':'):
if not s: break
while len(s) != 4:
s = '0' + s
tmp += s
while len(tmp) < 16*2:
tmp += '0'
res = ''
for i in range(0, 15*2, 2):
res += tmp[i] + tmp[i+1] + ':'
res += tmp[30] + tmp[31]
return res
def _create_request(self, ip, ip_type):
packet = ''
packet += struct.pack('<IBBBBI', IPToGeo.MAGIC, IPToGeo.VERSION, IPToGeo.REQ,
0, #err
IPToGeo.IPV4, # ip type
ip_type, # ip type
0) # flags
packet += struct.pack('<BBBB', ip[0], ip[1], ip[2], ip[3]) # ipv4
for i in ip:
packet += struct.pack('<B', i) # ipv4
packet += struct.pack('<III', 0, 0, 0) # ipv6
packet += struct.pack('<I', 0) # country code
@ -78,18 +95,35 @@ class IPToGeo(object):
if magic != IPToGeo.MAGIC:
raise IPToGeoException('Invalid magic %08x' % (magic))
if err == IPToGeo.IP_NOT_FOUND: return (ipv4, None) # IP not found
ip_res = '%08x' % (ipv4)
if ip_type == IPToGeo.IPV6:
ip_res += '%08x' % (ipv6b)
ip_res += '%08x' % (ipv6c)
ip_res += '%08x' % (ipv6d)
if err == IPToGeo.IP_NOT_FOUND: return (ip_res, None) # IP not found
if err != 0:
raise IPToGeoException(IPToGeo.ERRORS[err])
(cc0, cc1, cc2, cc3) = struct.unpack_from('BBBB', packet, 7*4)
return (ipv4, '%c%c%c%c' % (cc0, cc1, cc2, cc3))
return (ip_res, '%c%c%c%c' % (cc0, cc1, cc2, cc3))
def ip_to_geo(self, ip):
splitted_ip = [int(a) for a in ip.split('.')]
ip_type = IPToGeo.IPV4
if ip.find('.') >= 0:
splitted_ip = [int(a) for a in ip.split('.')]
if len(splitted_ip) != 4:
raise Exception('Bad IP %s' % (ip))
elif ip.find(':') >= 0:
splitted_ip = [int(a, 16) for a in self._extend_ipv6(ip).split(':')]
if len(splitted_ip) != 16:
raise Exception('Bad IP %s' % (ip))
ip_type = IPToGeo.IPV6
else:
raise Exception('Bad IP %s' % (ip))
packet = self._create_request(splitted_ip)
packet = self._create_request(splitted_ip, ip_type)
try:
self._socket.send(packet)
except IOError, e: