Commit bd359ab1 by William Tisäter

Merge branch 'master' into sudan-fix

parents b6462152 534fa941
recursive-include apidocs *
recursive-include tests *
include README.md
include COPYING
include DEVELOPER
include INSTALL
include epydoc.ini
include tox.ini
......@@ -20,11 +20,8 @@ You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/lgpl.txt>.
"""
import struct
import socket
from array import array
from pygeoip.const import PY3
import binascii
def ip2long(ip):
......@@ -33,41 +30,7 @@ def ip2long(ip):
@param ip: IPv4 or IPv6 address
@type ip: str
"""
if ip.find(':') >= 0:
return ip2long_v6(ip)
else:
return ip2long_v4(ip)
def ip2long_v4(ip):
"""
Convert a IPv4 address into a 32-bit integer.
@param ip: quad-dotted IPv4 address
@type ip: str
@return: network byte order 32-bit integer
@rtype: int
"""
ip_array = ip.split('.')
if PY3:
# int and long are unified in py3
return int(ip_array[0]) * 16777216 + int(ip_array[1]) * 65536 + \
int(ip_array[2]) * 256 + int(ip_array[3])
else:
return long(ip_array[0]) * 16777216 + long(ip_array[1]) * 65536 + \
long(ip_array[2]) * 256 + long(ip_array[3])
def ip2long_v6(ip):
"""
Convert a IPv6 address into long.
@param ip: IPv6 address
@type ip: str
@return: network byte order long
@rtype: long
"""
ipbyte = socket.inet_pton(socket.AF_INET6, ip)
ipnum = array('L', struct.unpack('!4L', ipbyte))
max_index = len(ipnum) - 1
return sum(ipnum[max_index - i] << (i * 32) for i in range(len(ipnum)))
try:
return int(binascii.hexlify(socket.inet_aton(ip)), 16)
except socket.error:
return int(binascii.hexlify(socket.inet_pton(socket.AF_INET6, ip)), 16)
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment