获取IP地址的前三个字节

2024-04-29 08:12:15 发布

您现在位置: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"

它工作得很好,但我觉得很难看,效率不高。有什么更好的方法?在


Tags: the字符串ip字节onval解决方案字符
3条回答

您可以拆分并获得前三个值,通过'.'连接,然后添加".0-255"

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

可以使用string对象的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.

更复杂的解决方案可以使用regular express:

^{pr2}$

希望对你有帮助!在

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

我认为networkSubnet()和hostRange()是对您有帮助的函数。在

相关问题 更多 >