How to calculate how much Ip Addresses have betwee

2019-02-21 06:12发布

问题:

I have two Ip Addresses, and I want to count how many Ip Addresses there are in the range between the two.

Example:

IP_START = "127.0.0.0"

IP_END = "127.0.1.1"

SUM_OF_IP_ADDRESS = 257

Does anyone know if python has anything to help me accomplish this?

回答1:

Short solution using the ipaddress package.

import ipaddress
ip1 = int(ipaddress.IPv4Address(unicode('127.0.0.0')))
ip2 = int(ipaddress.IPv4Address(unicode('127.0.1.1')))
print ip2 - ip1


回答2:

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


回答3:

this sounded fun so here you go

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