slightly improved network functionality and added tests for network

This commit is contained in:
UpstreamData
2022-05-19 11:55:38 -06:00
parent 40f14876cc
commit ec5563f2f0
3 changed files with 100 additions and 17 deletions

View File

@@ -1,15 +1,16 @@
import ipaddress
from typing import Union
import ipaddress
class MinerNetworkRange:
"""A MinerNetwork that takes a range of IP addresses.
:param ip_range: A range of IP addresses to put in the network, or a list of IPs
Takes a string formatted as
{ip_range_1_start}-{ip_range_1_end}, {ip_range_2_start}-{ip_range_2_end}
Also takes a list of strings formatted as
[{ip1}, {ip2}, {ip3}, ...]
Takes a string formatted as:
{ip_range_1_start}-{ip_range_1_end}, {ip_address_1},
{ip_range_2_start}-{ip_range_2_end}, {ip_address_2}...
Also takes a list of strings formatted as:
[{ip_address_1}, {ip_address_2}, {ip_address_3}, ...]
"""
def __init__(self, ip_range: Union[str, list]):
@@ -17,17 +18,20 @@ class MinerNetworkRange:
if isinstance(ip_range, str):
ip_ranges = ip_range.replace(" ", "").split(",")
for item in ip_ranges:
start, end = item.split("-")
start_ip = ipaddress.ip_address(start)
end_ip = ipaddress.ip_address(end)
networks = ipaddress.summarize_address_range(start_ip, end_ip)
for network in networks:
self.host_ips.append(network.network_address)
for host in network.hosts():
if host not in self.host_ips:
self.host_ips.append(host)
if network.broadcast_address not in self.host_ips:
self.host_ips.append(network.broadcast_address)
if "-" in item:
start, end = item.split("-")
start_ip = ipaddress.ip_address(start)
end_ip = ipaddress.ip_address(end)
networks = ipaddress.summarize_address_range(start_ip, end_ip)
for network in networks:
self.host_ips.append(network.network_address)
for host in network.hosts():
if host not in self.host_ips:
self.host_ips.append(host)
if network.broadcast_address not in self.host_ips:
self.host_ips.append(network.broadcast_address)
else:
self.host_ips.append(ipaddress.ip_address(item))
elif isinstance(ip_range, list):
self.host_ips = [ipaddress.ip_address(ip_str) for ip_str in ip_range]