How to calculate how much Ip Addresses have between two Ip Addresses?

你离开我真会死。 提交于 2019-12-09 03:29:20

问题


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


来源:https://stackoverflow.com/questions/17731510/how-to-calculate-how-much-ip-addresses-have-between-two-ip-addresses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!