如何计算Ip地址在两个Ip地址之间有多少?

时间:2013-07-18 18:44:44

标签: python ip ip-address

我有两个Ip地址,我想计算两者之间的Ip地址数。

示例:

IP_START = "127.0.0.0"

IP_END = "127.0.1.1"

SUM_OF_IP_ADDRESS = 257

有人知道python是否有任何东西可以帮助我实现这个目标?

4 个答案:

答案 0 :(得分:9)

使用ipaddress包的简短解决方案。

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

答案 1 :(得分:3)

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

答案 2 :(得分:2)

这听起来很有趣,所以你去吧

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

答案 3 :(得分:0)

一些短期解决方案

from ipaddress import ip_address

def ips_between(IP_START, IP_END):
    return int(ip_address(IP_END)) - int(ip_address(IP_START))