Skip to main content
 首页 » 编程设计

python之获取IP地址的前三个字节

2025年05月04日16jiqing9006

我想使用 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" 

它工作正常,但对我来说感觉丑陋且效率低下。执行此操作的更好方法是什么?

请您参考如下方法:

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

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

rfind 函数与 find() 类似,但从末尾开始搜索。

rfind(...) S.rfind(sub [,start [,end]]) -> int Return the highest index in S where substring sub is found, such that sub is contained within S[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 on failure.

更复杂的解决方案可以使用正则表达式:

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

希望对您有所帮助!