【问题标题】:Verify IP string is greater or less than another IP string in python验证IP字符串大于或小于python中的另一个IP字符串
【发布时间】:2014-12-13 05:10:42
【问题描述】:

在示例代码中,我将 start IP 和 end 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 ?

【问题讨论】:

  • 一个衬里:打印 [int(n) for n in start_ip.split('.')]
  • 很好理解,但我不知道这其中的复杂性。

标签: python string ip


【解决方案1】:

将字符串转换为整数列表。

>>> 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

【讨论】:

  • 完美!我对字符串比较有不同的印象。
【解决方案2】:

如果您使用 Python 3.x,那么您可以使用 ipaddress stdlib 包,其中包含为 IP 地址设计的对象。这些对象支持以这种方式进行比较。

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(功能有所减少)。

【讨论】:

  • 实际上我正在使用 netaddr 库来处理这些事情。但我正在编写自己的方法来实现它。基本上是想去掉多余的库。 :) 了解 py2-address 有什么好处
猜你喜欢
  • 2011-04-14
  • 2016-12-11
  • 2021-12-06
  • 2013-03-11
  • 2016-05-23
  • 2014-05-08
  • 2013-10-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多