IPGenerator.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import random
  2. from . import IPv4 as ip
  3. class IPGenerator:
  4. def __init__(self, include_private_ips = False, include_localhost = False,
  5. include_multicast = False, include_reserved = False,
  6. include_link_local = False, blacklist = None):
  7. self.blacklist = []
  8. self.generated_ips = set()
  9. if not include_private_ips:
  10. for segment in ip.ReservedIPBlocks.PRIVATE_IP_SEGMENTS:
  11. self.add_to_blacklist(segment)
  12. if not include_localhost:
  13. self.add_to_blacklist(ip.ReservedIPBlocks.LOCALHOST_SEGMENT)
  14. if not include_multicast:
  15. self.add_to_blacklist(ip.ReservedIPBlocks.MULTICAST_SEGMENT)
  16. if not include_reserved:
  17. self.add_to_blacklist(ip.ReservedIPBlocks.RESERVED_SEGMENT)
  18. if not include_link_local:
  19. self.add_to_blacklist(ip.ReservedIPBlocks.ZERO_CONF_SEGMENT)
  20. if blacklist:
  21. for segment in blacklist:
  22. self.add_to_blacklist(segment)
  23. def add_to_blacklist(self, ip_segment):
  24. if isinstance(ip_segment, ip.IPAddressBlock):
  25. self.blacklist.append(ip_segment)
  26. else:
  27. self.blacklist.append(ip.IPAddressBlock.parse(ip_segment))
  28. def random_ip(self):
  29. while True:
  30. random_ip = ip.IPAddress.from_int(random.randrange(0, 1 << 32))
  31. if not self._is_in_blacklist(random_ip) and random_ip not in self.generated_ips:
  32. self.generated_ips.add(random_ip)
  33. return str(random_ip)
  34. def clear(self, clear_blacklist = True, clear_generated_ips = True):
  35. if clear_blacklist: self.blacklist.clear()
  36. if clear_generated_ips: self.generated_ips.clear()
  37. def _is_in_blacklist(self, ip: ip.IPAddress):
  38. return any(ip in block for block in self.blacklist)
  39. class MappingIPGenerator(IPGenerator):
  40. def __init__(self, *args, **kwargs):
  41. super().__init__(self, *args, **kwargs)
  42. self.mapping = {}
  43. def clear(self, clear_generated_ips = True, *args, **kwargs):
  44. super().clear(self, clear_generated_ips = clear_generated_ips, *args, **kwargs)
  45. if clear_generated_ips:
  46. self.mapping = {}
  47. def get_mapped_ip(self, key):
  48. if key not in self.mapping:
  49. self.mapping[key] = self.random_ip()
  50. return self.mapping[key]
  51. def __getitem__(self, item):
  52. return self.get_mapped_ip(item)