AlexW AlexW - 23 days ago 5x
Python Question

python ipaddress, get first usable host only?

I am using pythons ipaddress module and im trying to get the first usable host only, not all usable hosts

the below gives me all hosts, and when i try to index it i get the below error.

is is possible any other way to just get the first usable host?


n = ipaddress.ip_network(u'')
for ip in n.hosts():
... print ip
>>> 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

the below is also failing

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


hosts() returns a generator object, which does not support indexing. You must iterate through it.

If you only want the first element, just use next():

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

If you want to convert the generator object into a list which supports indexing, you have to call the list() function:

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

You can also loop through a generator object like you would a list, as you did in your first code snippet:

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