在示例代码中,我将启动IP和结束IP作为输入。从中我将创建一个IP池列表。我想添加一个验证,启动IP应始终小于结束IP。
start_ip = '100.71.9.98'
end_ip = '100.71.9.100'
start_ip < end_ip
False
如何验证start_ip应该小于end_ip?
答案 0 :(得分:3)
将字符串转换为整数列表。
>>> start_ip = '100.71.9.98'
>>> end_ip = '100.71.9.100'
>>> map(int, start_ip.split('.')) # list(map(int, ...)) in Python 3.x
[100, 71, 9, 98]
>>> map(int, end_ip.split('.'))
[100, 71, 9, 100]
然后,可以根据需要对它们进行比较:
>>> '100.71.9.98' < '100.71.9.100'
False
>>> [100, 71, 9, 98] < [100, 71, 9, 100]
True
>>> map(int, start_ip.split('.')) < map(int, end_ip.split('.'))
True
答案 1 :(得分:2)
如果您使用Python 3.x,那么您可以使用具有为ip地址设计的对象的ipaddress
stdlib包。这些对象以这种方式支持比较。
import ipaddress
start = ipaddress.IPv4Address('100.71.9.98')
end = ipaddress.IPv4Address('100.71.9.100')
print(start < end)
# True
如果您使用的是Python 2.7,则可以使用py2-ipaddress(具有一些缩减的功能)。