1
2 """
3 Misc. utility functions. It is part of the pygeoip package.
4
5 @author: Jennifer Ennis <zaylea at gmail dot com>
6
7 @license:
8 Copyright(C) 2004 MaxMind LLC
9
10 This program is free software: you can redistribute it and/or modify
11 it under the terms of the GNU Lesser General Public License as published by
12 the Free Software Foundation, either version 3 of the License, or
13 (at your option) any later version.
14
15 This program is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
19
20 You should have received a copy of the GNU Lesser General Public License
21 along with this program. If not, see <http://www.gnu.org/licenses/lgpl.txt>.
22 """
23
24 import struct
25 import socket
26 from array import array
27
28 from pygeoip.const import PY3
29
30
32 """
33 Wrapper function for IPv4 and IPv6 converters
34 @param ip: IPv4 or IPv6 address
35 @type ip: str
36 """
37 if ip.find(':') >= 0:
38 return ip2long_v6(ip)
39 else:
40 return ip2long_v4(ip)
41
42
44 """
45 Convert a IPv4 address into a 32-bit integer.
46
47 @param ip: quad-dotted IPv4 address
48 @type ip: str
49 @return: network byte order 32-bit integer
50 @rtype: int
51 """
52 ip_array = ip.split('.')
53 if PY3:
54
55 return int(ip_array[0]) * 16777216 + int(ip_array[1]) * 65536 + \
56 int(ip_array[2]) * 256 + int(ip_array[3])
57 else:
58 return long(ip_array[0]) * 16777216 + long(ip_array[1]) * 65536 + \
59 long(ip_array[2]) * 256 + long(ip_array[3])
60
61
63 """
64 Convert a IPv6 address into long.
65
66 @param ip: IPv6 address
67 @type ip: str
68 @return: network byte order long
69 @rtype: long
70 """
71 ipbyte = socket.inet_pton(socket.AF_INET6, ip)
72 ipnum = array('L', struct.unpack('!4L', ipbyte))
73 max_index = len(ipnum) - 1
74 return sum(ipnum[max_index - i] << (i * 32) for i in range(len(ipnum)))
75