1
2 """
3 Utility functions. Part of the pygeoip package.
4
5 @author: Jennifer Ennis <zaylea@gmail.com>
6
7 @license: Copyright(C) 2004 MaxMind LLC
8
9 This program is free software: you can redistribute it and/or modify
10 it under the terms of the GNU Lesser 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 This program 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 Lesser General Public License
20 along with this program. If not, see <http://www.gnu.org/licenses/lgpl.txt>.
21 """
22
23 import struct
24 import socket
25 from array import array
26
27 from pygeoip.const import PY3
28
29
31 """
32 Wrapper function for IPv4 and IPv6 converters
33 @param ip: IPv4 or IPv6 address
34 @type ip: str
35 """
36 if ip.find(':') >= 0:
37 return ip2long_v6(ip)
38 else:
39 return ip2long_v4(ip)
40
41
43 """
44 Convert a IPv4 address into a 32-bit integer.
45
46 @param ip: quad-dotted IPv4 address
47 @type ip: str
48 @return: network byte order 32-bit integer
49 @rtype: int
50 """
51 ip_array = ip.split('.')
52 if PY3:
53
54 return int(ip_array[0]) * 16777216 + int(ip_array[1]) * 65536 + \
55 int(ip_array[2]) * 256 + int(ip_array[3])
56 else:
57 return long(ip_array[0]) * 16777216 + long(ip_array[1]) * 65536 + \
58 long(ip_array[2]) * 256 + long(ip_array[3])
59
60
62 """
63 Convert a IPv6 address into long.
64
65 @param ip: IPv6 address
66 @type ip: str
67 @return: network byte order long
68 @rtype: long
69 """
70 ipbyte = socket.inet_pton(socket.AF_INET6, ip)
71 ipnum = array('L', struct.unpack('!4L', ipbyte))
72 max_index = len(ipnum) - 1
73 return sum(ipnum[max_index - i] << (i * 32) for i in range(len(ipnum)))
74