python ipaddress, get first usable host only?
<p>I am using pythons ipaddress module and im trying to get the first usable host only, not all usable hosts</p>

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

<p>is is possible any other way to just get the first usable host?</p>

<p>Thanks</p>

<pre><code>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
...
&gt;&gt;&gt; for ip in n.hosts():
...  print ip[1]
...
Traceback (most recent call last):
  File "&lt;console&gt;", line 2, in &lt;module&gt;
TypeError: 'IPv4Address' object does not support indexing
&gt;&gt;&gt;
</code></pre>

<p>the below is also failing</p>

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

<p><code>hosts()</code> returns a generator object, which does not support indexing. You must iterate through it.</p>

<p>If you only want the first element, just use <code>next()</code>:</p>

<pre><code>n = ipaddress.ip_network(u'10.10.20.0/24')
first_host = next(n.hosts())
</code></pre>

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

<pre><code>all_hosts = list(n.hosts())
first_host = all_hosts[0]
</code></pre>

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

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

python