IP to Geo

IP to Geo Git Source Tree

Root/tests/iptogeo.py

1#!/usr/bin/env python
2# -*- coding: utf-8 -*-
3
4#
5# Copyright 2016 Grégory Soutadé
6#
7# This file is part of iptogeo.
8#
9# iptogeo is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# iptogeo is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with iptogeo. If not, see <http://www.gnu.org/licenses/>.
21#
22
23import socket
24import struct
25
26class IPToGeoException(Exception):
27 pass
28
29class IPToGeo(object):
30
31 MAGIC = 0x179E08EF
32 VERSION = 1
33 REQ = 1
34 RESP = 0
35 IPV4 = 4
36 IPV6 = 16
37
38 IP_NOT_FOUND = 6
39
40 PACKET_SIZE = 32
41
42 ERRORS = {1 : 'Bad magic',
43 2 : 'Bad version',
44 3 : 'Bad request field' ,
45 4 : 'Bad IP version',
46 5 : 'Unsupported IP version',
47 6 : 'IP not found'}
48
49 def __init__(self, remote_addr='127.0.0.1', remote_port=53333, timeout=None, family=socket.AF_INET):
50 self._remote_addr = remote_addr
51 self._remote_port = remote_port
52 self._timeout = timeout
53 self._family = family
54
55 self._create_socket()
56
57 def _create_socket(self):
58 self._socket = socket.socket(self._family, socket.SOCK_STREAM)
59 if not self._timeout is None:
60 self._socket.settimeout(self._timeout)
61 self._socket.connect((self._remote_addr, self._remote_port))
62
63 def _extend_ipv6(self, ipv6):
64 tmp = ''
65 for s in ipv6.split(':'):
66 if not s: break
67 while len(s) != 4:
68 s = '0' + s
69 tmp += s
70 while len(tmp) < 16*2:
71 tmp += '0'
72 res = ''
73 for i in range(0, 15*2, 2):
74 res += tmp[i] + tmp[i+1] + ':'
75 res += tmp[30] + tmp[31]
76
77 return res
78
79 def _create_request(self, ip, ip_type):
80 packet = ''
81 packet += struct.pack('<IBBBBI', IPToGeo.MAGIC, IPToGeo.VERSION, IPToGeo.REQ,
82 0, #err
83 ip_type, # ip type
84 0) # flags
85 for i in ip:
86 packet += struct.pack('<B', i) # ipv4
87 packet += struct.pack('<III', 0, 0, 0) # ipv6
88 packet += struct.pack('<I', 0) # country code
89
90 return packet
91
92 def _check_request(self, packet):
93 (magic, version, req, err, ip_type, flags, ipv4, ipv6b, ipv6c, ipv6d) = struct.unpack_from('<IBBBBIIIII', packet, 0)
94
95 if magic != IPToGeo.MAGIC:
96 raise IPToGeoException('Invalid magic %08x' % (magic))
97
98 ip_res = '%08x' % (ipv4)
99 if ip_type == IPToGeo.IPV6:
100 ip_res += '%08x' % (ipv6b)
101 ip_res += '%08x' % (ipv6c)
102 ip_res += '%08x' % (ipv6d)
103
104 if err == IPToGeo.IP_NOT_FOUND: return (ip_res, None) # IP not found
105 if err != 0:
106 raise IPToGeoException(IPToGeo.ERRORS[err])
107
108 (cc0, cc1, cc2, cc3) = struct.unpack_from('BBBB', packet, 7*4)
109
110 return (ip_res, '%c%c%c%c' % (cc0, cc1, cc2, cc3))
111
112 def ip_to_geo(self, ip):
113 ip_type = IPToGeo.IPV4
114 if ip.find('.') >= 0:
115 splitted_ip = [int(a) for a in ip.split('.')]
116 if len(splitted_ip) != 4:
117 raise Exception('Bad IP %s' % (ip))
118 elif ip.find(':') >= 0:
119 splitted_ip = [int(a, 16) for a in self._extend_ipv6(ip).split(':')]
120 if len(splitted_ip) != 16:
121 raise Exception('Bad IP %s' % (ip))
122 ip_type = IPToGeo.IPV6
123 else:
124 raise Exception('Bad IP %s' % (ip))
125
126 packet = self._create_request(splitted_ip, ip_type)
127 try:
128 self._socket.send(packet)
129 except IOError, e:
130 # Give another chance (we may have been disconnected due to timeout)
131 self._create_socket()
132 self._socket.send(packet)
133 packet = self._socket.recv(IPToGeo.PACKET_SIZE)
134 if not packet:
135 raise IPToGeoException('Error, empty packet')
136 (ip, country_code) = self._check_request(packet)
137 if country_code:
138 # convert to string
139 country_code = '%c%c' % (country_code[0], country_code[1])
140 return (ip, country_code)
141
142 def close(self):
143 self._socket.close()

Archive Download this file

Branches

Tags