IPv4.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. import re
  2. class IPAddress:
  3. # a number between 0 and 255, no leading zeros
  4. _IP_NUMBER_REGEXP = r"(25[0-5]|2[0-4]\d|1?[1-9]?\d)"
  5. # 4 numbers between 0 and 255, joined together with dots
  6. IP_REGEXP = r"{0}\.{0}\.{0}\.{0}".format(_IP_NUMBER_REGEXP)
  7. def __init__(self, intlist):
  8. if not isinstance(intlist, list) or not all(isinstance(n, int) for n in intlist):
  9. raise TypeError("The first constructor argument must be an list of ints")
  10. if not len(intlist) == 4 or not all(0 <= n <= 255 for n in intlist):
  11. raise ValueError("The integer list must contain 4 ints in range of 0 and 255, like an ip-address")
  12. self.ipnum = int.from_bytes(bytes(intlist), "big")
  13. @staticmethod
  14. def parse(ip: str):
  15. match = re.match("^" + IPAddress.IP_REGEXP + "$", ip)
  16. if not match:
  17. raise ValueError("%s is no ipv4-address" % ip)
  18. numbers = [int(match.group(i)) for i in range(1, 5)]
  19. return IPAddress(numbers)
  20. @staticmethod
  21. def from_int(numeric: int):
  22. if numeric not in range(1 << 32):
  23. raise ValueError("numeric value must be in uint-range")
  24. return IPAddress(list(numeric.to_bytes(4, "big")))
  25. @staticmethod
  26. def is_ipv4(ip: str):
  27. match = re.match("^" + IPAddress.IP_REGEXP + "$", ip)
  28. return True if match else False
  29. def to_int(self):
  30. return self.ipnum
  31. def is_private(self):
  32. return ReservedIPBlocks.is_private(self)
  33. def get_private_segment(self):
  34. return ReservedIPBlocks.get_private_segment(self)
  35. def is_localhost(self):
  36. return ReservedIPBlocks.is_localhost(self)
  37. def is_multicast(self):
  38. return ReservedIPBlocks.is_multicast(self)
  39. def is_reserved(self):
  40. return ReservedIPBlocks.is_reserved(self)
  41. def is_zero_conf(self):
  42. return ReservedIPBlocks.is_zero_conf(self)
  43. def _tuple(self):
  44. return tuple(self.ipnum.to_bytes(4, "big"))
  45. def __repr__(self):
  46. return "IPAddress([%i, %i, %i, %i])" % self._tuple()
  47. def __str__(self):
  48. return "%i.%i.%i.%i" % self._tuple()
  49. def __hash__(self):
  50. return self.ipnum
  51. def __eq__(self, other):
  52. if other is None:
  53. return False
  54. return isinstance(other, IPAddress) and self.ipnum == other.ipnum
  55. def __lt__(self, other):
  56. if other is None:
  57. raise TypeError("Cannot compare to None")
  58. if not isinstance(other, IPAddress):
  59. raise NotImplemented # maybe other can compare to self
  60. return self.ipnum < other.ipnum
  61. def __gt__(self, other):
  62. if other is None:
  63. raise TypeError("Cannot compare to None")
  64. if not isinstance(other, IPAddress):
  65. raise NotImplemented # maybe other can compare to self
  66. return self.ipnum > other.ipnum
  67. class IPAddressBlock:
  68. CIDR_REGEXP = IPAddress.IP_REGEXP + r"(\/(3[0-2]|[12]?\d)|)?"
  69. def __init__(self, ip, netmask = 32):
  70. if isinstance(ip, str):
  71. ip = IPAddress.parse(ip)
  72. elif isinstance(ip, list):
  73. ip = IPAddress(ip)
  74. if not 1 <= netmask <= 32:
  75. raise ValueError("netmask must lie between 1 and 32")
  76. self.ipnum = ip.to_int() & self._bitmask(netmask)
  77. self.netmask = netmask
  78. @staticmethod
  79. def parse(cidr: str):
  80. match = re.match("^" + IPAddressBlock.CIDR_REGEXP + "$", cidr)
  81. if not match:
  82. raise ValueError("%s is no valid cidr-notation" % cidr)
  83. ip = [int(match.group(i)) for i in range(1, 5)]
  84. suffix = 32 if not match.group(6) else int(match.group(6))
  85. return IPAddressBlock(ip, suffix)
  86. def _bitmask(self, netmask):
  87. ones = lambda x: (1 << x) - 1
  88. return ones(32) ^ ones(32 - netmask)
  89. def __repr__(self):
  90. return "IPAddressBlock(%s, %i)" % (repr(IPAddress.from_int(self.ipnum)), self.netmask)
  91. def __self__(self):
  92. return IPAddress.from_int(self.ipnum) + "/" + str(self.netmask)
  93. def __contains__(self, ip):
  94. return (ip.to_int() & self._bitmask(self.netmask)) == self.ipnum
  95. class ReservedIPBlocks:
  96. PRIVATE_IP_SEGMENTS = [
  97. IPAddressBlock.parse(block)
  98. for block in
  99. ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16")
  100. ]
  101. LOCALHOST_SEGMENT = IPAddressBlock.parse("127.0.0.0/8")
  102. MULTICAST_SEGMENT = IPAddressBlock.parse("224.0.0.0/4")
  103. RESERVED_SEGMENT = IPAddressBlock.parse("240.0.0.0/4")
  104. ZERO_CONF_SEGMENT = IPAddressBlock.parse("169.254.0.0/16")
  105. @staticmethod
  106. def is_private(ip):
  107. return any(ip in block for block in ReservedIPBlocks.PRIVATE_IP_SEGMENTS)
  108. @staticmethod
  109. def get_private_segment(ip):
  110. if not ReservedIPBlocks.is_private(ip):
  111. raise ValueError("%s is not part of a private IP segment" % ip)
  112. for block in ReservedIPBlocks.PRIVATE_IP_SEGMENTS:
  113. if ip in block:
  114. return block
  115. @staticmethod
  116. def is_localhost(ip):
  117. return ip in ReservedIPBlocks.LOCALHOST_SEGMENT
  118. @staticmethod
  119. def is_multicast(ip):
  120. return ip in ReservedIPBlocks.MULTICAST_SEGMENT
  121. @staticmethod
  122. def is_reserved(ip):
  123. return ip in ReservedIPBlocks.RESERVED_SEGMENT
  124. @staticmethod
  125. def is_zero_conf(ip):
  126. return ip in ReservedIPBlocks.ZERO_CONF_SEGMENT