While using Python I very often enjoy
standing on shoulders of giants. Thanks to giants it turned out to be very easy-peasy task
Using
ipaddress module
IPv4Address class objects can be
converted to int and these integers are consecutive:
In [1]: import ipaddress
In [2]: ipaddress.IPv4Address('10.0.0.0')
Out[2]: IPv4Address('10.0.0.0')
In [3]: int(ipaddress.IPv4Address('10.0.0.0'))
Out[3]: 167772160
In [4]: int(ipaddress.IPv4Address('10.0.0.1'))
Out[4]: 167772161
So getting ip addresses from range is very simple. You get first and last from string representing range and convert the resulting strings to IPv4Address and then to int. Then you just iterate over int range and convert addresses back to string:
import ipaddress
def ip_from_range(ip_range):
first, last = [int(ipaddress.IPv4Address(el)) for el in ip_range.split('-')]
return [str(ipaddress.IPv4Address(i)) for i in range(first, last + 1)]
In [6]: ip_from_range('10.1.1.250-10.1.2.5')
Out[6]:
['10.1.1.250',
'10.1.1.251',
'10.1.1.252',
'10.1.1.253',
'10.1.1.254',
'10.1.1.255',
'10.1.2.0',
'10.1.2.1',
'10.1.2.2',
'10.1.2.3',
'10.1.2.4',
'10.1.2.5']
List can potentially be of significant size and generator could be an option. Generator doesn't create list but yields elements one at the time (example is for printing but can be used to write/append to file):
import ipaddress
def ip_from_range(ip_range):
first, last = [int(ipaddress.IPv4Address(el)) for el in ip_range.split('-')]
yield from (str(ipaddress.IPv4Address(i)) for i in range(first, last + 1))
for ip in ip_from_range('10.1.1.250-10.1.2.5'):
print(ip)
10.1.1.250
10.1.1.251
10.1.1.252
10.1.1.253
10.1.1.254
10.1.1.255
10.1.2.0
10.1.2.1
10.1.2.2
10.1.2.3
10.1.2.4
10.1.2.5
I like Python.