Skip to main content
 首页 » 编程设计

python ipaddress,只获得第一个可用的主机

2025年05月04日29落叶无声

我正在使用 pythons ipaddress 模块,我试图只获取第一个可用主机,而不是所有可用主机

下面给了我所有的主机,当我试图索引它时,我得到了下面的错误。

有没有其他方法可以只获得第一个可用的主机?

谢谢

n = ipaddress.ip_network(u'10.10.20.0/24') 
for ip in n.hosts(): 
...  print ip 
10.10.20.1 
10.10.20.2 
10.10.20.3 
10.10.20.4 
... 
>>> for ip in n.hosts(): 
...  print ip[1] 
... 
Traceback (most recent call last): 
  File "<console>", line 2, in <module> 
TypeError: 'IPv4Address' object does not support indexing 
>>> 

下面的也失败了

>>> print n.hosts()[0] 
Traceback (most recent call last): 
  File "<console>", line 1, in <module> 
TypeError: 'generator' object has no attribute '__getitem__' 

请您参考如下方法:

hosts() 返回一个不支持索引的生成器对象。您必须遍历它。

如果你只想要第一个元素,只需使用next():

n = ipaddress.ip_network(u'10.10.20.0/24') 
first_host = next(n.hosts()) 

如果要将生成器对象转换为支持索引的列表,必须调用list()函数:

all_hosts = list(n.hosts()) 
first_host = all_hosts[0] 

您还可以像在列表中一样循环遍历生成器对象,就像您在第一个代码片段中所做的那样:

for ip in n.hosts(): 
    # do something with ip: this is the IP address, so don't try to index into it! 
    pass