<p>我想使用IP地址字符串,即:192.168.1.23,但只保留IP地址的前三个字节,然后追加0-255。我想把这个IP地址转换成一个IP地址的范围,我可以传递给NMAP来进行扫描。在</p>
<p>当然,最简单的解决方案是简单地去掉字符串的最后两个字符,但是如果IP是192.168.1.1或192.168.1.123,这当然行不通</p>
<p>下面是我想出的解决方案:</p>
<pre><code>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 + "."
# <a href="https://www.cnpython.com/list/append" class="inner-link">append</a> "0-255" at the end, we now have target range trange = "XX.XX.XX.0-255"
trange += "0-255"
</code></pre>
<p>它工作得很好,但我觉得很难看,效率不高。有什么更好的方法?在</p>