我有两个 IP 地址,我想计算两者之间有多少个 IP 地址。
例子:
IP_START = "127.0.0.0"
IP_END = "127.0.1.1"
SUM_OF_IP_ADDRESS = 257
有谁知道python是否有什么可以帮助我完成这个?
我有两个 IP 地址,我想计算两者之间有多少个 IP 地址。
例子:
IP_START = "127.0.0.0"
IP_END = "127.0.1.1"
SUM_OF_IP_ADDRESS = 257
有谁知道python是否有什么可以帮助我完成这个?
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
这听起来很有趣所以给你
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
Max的答案的Python3版本
import ipaddress
ip1 = int(ipaddress.IPv4Address(str('127.0.0.0')))
ip2 = int(ipaddress.IPv4Address(str('127.0.1.1')))
print(ip2 - ip1)
一些简短的解决方案
from ipaddress import ip_address
def ips_between(IP_START, IP_END):
return int(ip_address(IP_END)) - int(ip_address(IP_START))