获取IP地址的前三个字节

时间:2014-04-24 01:19:25

标签: python

我想使用IP地址字符串,即:192.168.1.23,但只保留IP地址的前三个字节,然后追加0-255。我想将该IP地址转换为一系列IP地址'我可以传递给NMAP进行扫描扫描。

最简单的解决方案当然是简单地修剪字符串的最后两个字符,但当然,如果IP为192.168.1.1或192.168.1.123

,这将不起作用

以下是我提出的解决方案:

lhost = "192.168.1.23"

# Split the lhost on each '.' then re-assemble the first three parts
lip = self.lhost.split('.')
trange = ""
for i, val in enumerate(lip):
    if (i < len(lip) - 1):
        trange += val + "."

# Append "0-255" at the end, we now have target range trange = "XX.XX.XX.0-255"
trange += "0-255"

它工作正常,但感觉很丑,对我来说效率不高。有什么更好的方法呢?

4 个答案:

答案 0 :(得分:4)

您可以使用字符串对象的rfind函数。

>>> lhost = "192.168.1.23"
>>> lhost[:lhost.rfind(".")] + ".0-255"
'192.168.1.0-255'

rfind函数与find()类似,但从最后搜索。

  

RFIND(...)       S.rfind(sub [,start [,end]]) - &gt; INT       返回S中找到substring sub的最高索引,       这样sub包含在S [start:end]中。可选的       参数start和end被解释为切片表示法。       失败时返回-1。

更复杂的解决方案可以使用常规表达:

>>> import re
>>> re.sub("\d{1,3}$","0-255",lhost)
'192.168.1.0-255'

希望它有所帮助!

答案 1 :(得分:1)

您可以拆分并获取前三个值,按'.'加入,然后添加".0-255"

>>> lhost = "192.168.1.23"
>>> '.'.join(lhost.split('.')[0:-1]) + ".0-255"
'192.168.1.0-255'
>>> 

答案 2 :(得分:1)

并非所有IP都属于C类。我认为代码必须灵活,以适应各种IP范围及其掩码, 我以前写过一个很小的python模块来计算网络ID&lt;具有任何网络掩码的给定IP地址的广播ID。 代码可以在这里找到:https://github.com/brownbytes/tamepython/blob/master/subnet_calculator.py

我认为networkSubnet()和hostRange()是可以为您提供帮助的功能。

答案 3 :(得分:0)

我喜欢这个:

#!/usr/bin/python3

ip_address = '128.200.34.1'

list_ = ip_address.split('.')
assert len(list_) == 4
list_[3] = '0-255'

print('.'.join(list_))
相关问题