¿Cómo calcular la cantidad de direcciones IP que hay entre dos direcciones IP?

Tengo dos direcciones IP y quiero contar cuántas direcciones IP hay en el rango entre las dos.

Ejemplo:

IP_START = "127.0.0.0" IP_END = "127.0.1.1" SUM_OF_IP_ADDRESS = 257 

¿Alguien sabe si Python tiene algo que me ayude a lograr esto?

Solución corta utilizando el paquete ipaddress .

 import ipaddress ip1 = int(ipaddress.IPv4Address(unicode('127.0.0.0'))) ip2 = int(ipaddress.IPv4Address(unicode('127.0.1.1'))) print ip2 - ip1 
 IP_START = "127.0.0.0" IP_END = "127.0.1.1" diffs = [int(b)-int(a) for a,b in zip(IP_START.split('.'), IP_END.split('.'))] SUM_OF_IP_ADDRESS = 0 for d in diffs: SUM_OF_IP_ADDRESS *= 256 SUM_OF_IP_ADDRESS += d SUM_OF_IP_ADDRESS += 1 >>> IP_START = "127.0.0.0" >>> IP_END = "127.0.1.1" >>> diffs = [int(b)-int(a) for a,b in zip(IP_START.split('.'), IP_END.split('.'))] >>> SUM_OF_IP_ADDRESS = 0 >>> for d in diffs: ... SUM_OF_IP_ADDRESS *= 256 ... SUM_OF_IP_ADDRESS += d ... SUM_OF_IP_ADDRESS += 1 ... >>> SUM_OF_IP_ADDRESS 257 

esto sonaba divertido así que aquí tienes

 class IPV4ADDR: def __init__(self, *parts): if len(parts) > 4: raise Exception("Unknown IP Address:%s" % parts) if len(parts) == 1 and isinstance(parts[0], basestring): parts = map(int, parts[0].split(".")) if len(parts) != 4: raise Exception("Unknown IP Address:%s" % parts) self.parts = parts def __int__(self): parts = self.parts return parts[0] << 24 | parts[1] << 16 | parts[2] << 8 | parts[3] def __sub__(self, other): return int(self) - int(other) def __add__(self, other): #not sure how to "add" ip addresses so ill just OR them numeric_val = int(self) | int(other) return IPV4ADDR(numeric_val & 0xFF000000, numeric_val & 0xFF0000, numeric_val & 0xFF00, numeric_val & 0xFF) def __str__(self): return "%d.%d.%d.%d" % self.parts a1 = IPV4ADDR("127.0.0.0") a2 = IPV4ADDR("127.0.1.1") print a2 - a1 #257