Chris Adams / Sep 16 2019
Remix of Python by Nextjournal
Network IP range checking
IP range conversion
We need to be able to check for IP ranges
import ipaddress
network = ipaddress.ip_network("185.203.112.0/22")
network.num_addresses
1024
all_the_ips = list(network.hosts())
all_the_ips[0], all_the_ips[-1]
(IPv4Address('185.203.112.1'), IPv4Address('185.203.115.254'))
def get_first_and_last_ips(iprange_with_mask): network = ipaddress.ip_network(iprange_with_mask) list_of_addresses = list(network.hosts()) return [ list_of_addresses[0], list_of_addresses[-1] ]
get_first_and_last_ips("185.203.112.0/22")
[IPv4Address('185.203.112.1'), IPv4Address('185.203.115.254')]
get_first_and_last_ips("147.78.192.0/22")
[IPv4Address('147.78.192.1'), IPv4Address('147.78.195.254')]
# don't do this. Making a list from the generator takes aaaaages, and times out. # get_first_and_last_ips("2a0a:e5c0::/29")
Checking for IPv6
Some providers will increasingly work in IPv6, so we'll need to check for that too.
import ipaddress ipv6_network = ipaddress.ip_network("2a0a:e5c0::/29")
ipv6_network
IPv6Network('2a0a:e5c0::/29')
ipv6_network.hosts()
<generator ob...x7fdcd1a0afc0>
ipv6_network[0].exploded
'2a0a:e5c0:0000:0000:0000:0000:0000:0000'
ipv6_network[-1].exploded
'2a0a:e5c7:ffff:ffff:ffff:ffff:ffff:ffff'
second_ipv6_network = ipaddress.ip_network("2a09:2940::/29")
second_ipv6_network[0].exploded, second_ipv6_network[-1].exploded
('2a09:2940:0000:0000:0000:0000:0000:0000', '2a09:2947:ffff:ffff:ffff:ffff:ffff:ffff')