net_params.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. import ipaddress
  2. import socket
  3. import subprocess
  4. import typing
  5. import getmac
  6. __all__ = (
  7. 'LocalNetwork',
  8. 'is_valid_ipv4',
  9. 'enforce_mac',
  10. 'enforce_mac',
  11. 'parse_ip',
  12. )
  13. OUR_MAC = None
  14. OUR_IP = None
  15. OUR_INTERFACE = None
  16. class LocalNetwork:
  17. # def get_mac(self, interface: typing.Optional[str]) -> str:
  18. # if interface is None:
  19. # interface = self.
  20. def get_mac(self, interface: typing.Optional[str] = None) -> str:
  21. if interface is None:
  22. interface = self.get_default_interface()
  23. global OUR_MAC
  24. if OUR_MAC:
  25. return OUR_MAC
  26. OUR_MAC = getmac.get_mac_address(interface)
  27. return typing.cast(str, OUR_MAC)
  28. def get_ip(self) -> str:
  29. global OUR_IP
  30. if OUR_IP:
  31. return OUR_IP
  32. with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
  33. s.connect(("1.1.1.1", 80))
  34. ip = typing.cast(str, s.getsockname()[0])
  35. OUR_IP = ip
  36. return OUR_IP
  37. def get_default_interface(self) -> str:
  38. global OUR_INTERFACE
  39. if OUR_INTERFACE:
  40. return OUR_INTERFACE
  41. output = subprocess.check_output(['ip', 'route', 'list']).decode().split()
  42. for ind, word in enumerate(output):
  43. if word == 'dev':
  44. OUR_INTERFACE = output[ind + 1]
  45. return OUR_INTERFACE
  46. raise RuntimeError('Could not find default interface')
  47. def is_valid_ipv4(ip: str) -> bool:
  48. try:
  49. ipaddress.IPv4Address(ip)
  50. return True
  51. except ipaddress.AddressValueError:
  52. return False
  53. def enforce_mac(mac: str) -> bytes:
  54. mac_bytes = []
  55. for b in mac.split(':'):
  56. mac_bytes.append(int(b, 16))
  57. return bytes(mac_bytes)
  58. def enforce_ip(ip: str) -> bytes:
  59. ip_bytes = []
  60. for b in ip.split('.'):
  61. ip_bytes.append(int(b))
  62. return bytes(ip_bytes)
  63. def parse_mac(mac: bytes) -> str:
  64. mac_parts = []
  65. for b in mac:
  66. hex = f'{b:x}'
  67. if len(hex) == 1:
  68. hex = '0' + hex
  69. mac_parts.append(hex)
  70. return ':'.join(mac_parts)
  71. def parse_ip(ip: bytes) -> str:
  72. ip_parts = []
  73. for b in ip:
  74. ip_parts.append(str(b))
  75. return '.'.join(ip_parts)
  76. if __name__ == '__main__':
  77. foo = LocalNetwork()
  78. print(foo.get_default_interface())
  79. print(foo.get_mac())
  80. print(foo.get_ip())
  81. # print(is_valid_ipv4('1.1.1.1'))