MacAddressGenerator.py 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. from random import getrandbits
  2. class MacAddressGenerator:
  3. def __init__(self, include_broadcast_macs = False, include_virtual_macs = False):
  4. self.broadcast = include_broadcast_macs
  5. self.virtual = include_virtual_macs
  6. self.generated = set()
  7. def random_mac(self) -> str:
  8. while True:
  9. mac = self._random_mac()
  10. if mac not in self.generated:
  11. self.generated.add(mac)
  12. return mac
  13. def clear(self):
  14. self.generated.clear()
  15. def generates_broadcast_macs(self) -> bool:
  16. return self.broadcast
  17. def generates_virtual_macs(self) -> bool:
  18. return self.virtual
  19. def set_broadcast_generation(self, broadcast: bool):
  20. self.broadcast = broadcast
  21. def set_virtual_generation(self, virtual: bool):
  22. self.virtual = virtual
  23. def _random_mac(self) -> str:
  24. mac_bytes = bytearray(getrandbits(8) for i in range(6))
  25. if not self.broadcast:
  26. mac_bytes[0] &= ~1 # clear the first bytes' first bit
  27. if not self.virtual:
  28. mac_bytes[0] &= ~2 # clear the first bytes' second bit
  29. return ":".join("%02X" % b for b in mac_bytes)