Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find next available IP address in python

Tags:

python

Using python I need to find the next IP address given a range of IP addresses I've already used. So if I have a list of IP address like...

IPs = ['10.220.1.1','10.220.1.2','10.220.1.3','10.220.1.5']

When I ask for the next IP address I need it to return '10.220.1.4'. The next request would return '10.220.1.6' and so on.

like image 302
corradomatt Avatar asked May 30 '26 22:05

corradomatt


1 Answers

If you're using Python 3.3 (or newer), you can use the ipaddress module. Example for all hosts in the subnet 10.220.1.0/24 except for those in reserved:

from ipaddress import IPv4Network

network = IPv4Network('10.220.1.0/24')
reserved = {'10.220.1.1', '10.220.1.2', '10.220.1.3', '10.220.1.5'}

hosts_iterator = (host for host in network.hosts() if str(host) not in reserved)

# Using hosts_iterator:
print(next(hosts_iterator))  # prints 10.220.1.4
print(next(hosts_iterator))  # prints 10.220.1.6
print(next(hosts_iterator))  # prints 10.220.1.7

# Or you can iterate over hosts_iterator:
for host in hosts_iterator:
    print(host)

So basically this can be done in a single line (+ imports and definition of network and reserved addresses).

like image 119
Manuel Jacob Avatar answered Jun 02 '26 11:06

Manuel Jacob