Converting IPv4 or IPv6 address to a long for comparisons
Posted
by Justin Akehurst
on Stack Overflow
See other posts from Stack Overflow
or by Justin Akehurst
Published on 2010-04-13T17:07:49Z
Indexed on
2010/04/13
18:03 UTC
Read the original article
Hit count: 298
In order to check if an IPv4 or IPv6 address is within a certain range, I've got code that takes an IPv4 address, turns that into a long, then does that same conversion on the upper/lower bound of the subnet, then checks to see if the long is between those values.
I'd like to be able to do the same thing for IPv6, but saw nothing in the Python 2.6 standard libraries to allow me to do this, so I wrote this up:
import socket, struct
from array import array
def ip_address_to_long(address):
ip_as_long = None
try:
ip_as_long = socket.ntohl(struct.unpack('L',
socket.inet_pton(socket.AF_INET, address))[0])
except socket.error:
# try IPv6
try:
addr = array('L', struct.unpack('!4L',
socket.inet_pton(socket.AF_INET6, address)))
addr.reverse()
ip_as_long = sum(addr[i] << (i * 32) for i in range(len(addr)))
except socket.error as se:
raise ValueError('Invalid address')
except Exception as e:
print str(e)
return ip_as_long
My question is: Is there a simpler way to do this that I am missing? Is there a standard library call that can do this for me?
© Stack Overflow or respective owner