IPv4.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  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. class IPAddressBlock:
  62. CIDR_REGEXP = IPAddress.IP_REGEXP + r"(\/(3[0-2]|[12]?\d)|)?"
  63. def __init__(self, ip, netmask = 32):
  64. if isinstance(ip, str):
  65. ip = IPAddress.parse(ip)
  66. elif isinstance(ip, list):
  67. ip = IPAddress(ip)
  68. if not 1 <= netmask <= 32:
  69. raise ValueError("netmask must lie between 1 and 32")
  70. self.ipnum = ip.to_int() & self._bitmask(netmask)
  71. self.netmask = netmask
  72. self.last_ipnum = self.ipnum + self.block_size() - 1
  73. @staticmethod
  74. def parse(cidr: str):
  75. match = re.match("^" + IPAddressBlock.CIDR_REGEXP + "$", cidr)
  76. if not match:
  77. raise ValueError("%s is no valid cidr-notation" % cidr)
  78. ip = [int(match.group(i)) for i in range(1, 5)]
  79. suffix = 32 if not match.group(6) else int(match.group(6))
  80. return IPAddressBlock(ip, suffix)
  81. def block_size(self):
  82. return 2 ** (32 - self.netmask)
  83. def first_address(self):
  84. return IPAddress.from_int(self.ipnum)
  85. def last_address(self):
  86. return IPAddress.from_int(self.last_ipnum)
  87. def _bitmask(self, netmask):
  88. ones = lambda x: (1 << x) - 1
  89. return ones(32) ^ ones(32 - netmask)
  90. def __repr__(self):
  91. return "IPAddressBlock(%s, %i)" % (repr(IPAddress.from_int(self.ipnum)), self.netmask)
  92. def __self__(self):
  93. return IPAddress.from_int(self.ipnum) + "/" + str(self.netmask)
  94. def __contains__(self, ip):
  95. return (ip.to_int() & self._bitmask(self.netmask)) == self.ipnum
  96. class ReservedIPBlocks:
  97. PRIVATE_IP_SEGMENTS = [
  98. IPAddressBlock.parse(block)
  99. for block in
  100. ("10.0.0.0/8", "172.16.0.0/12", "192.168.0.0/16")
  101. ]
  102. LOCALHOST_SEGMENT = IPAddressBlock.parse("127.0.0.0/8")
  103. MULTICAST_SEGMENT = IPAddressBlock.parse("224.0.0.0/4")
  104. RESERVED_SEGMENT = IPAddressBlock.parse("240.0.0.0/4")
  105. ZERO_CONF_SEGMENT = IPAddressBlock.parse("169.254.0.0/16")
  106. @staticmethod
  107. def is_private(ip):
  108. return any(ip in block for block in ReservedIPBlocks.PRIVATE_IP_SEGMENTS)
  109. @staticmethod
  110. def get_private_segment(ip):
  111. if not ReservedIPBlocks.is_private(ip):
  112. raise ValueError("%s is not part of a private IP segment" % ip)
  113. for block in ReservedIPBlocks.PRIVATE_IP_SEGMENTS:
  114. if ip in block:
  115. return block
  116. @staticmethod
  117. def is_localhost(ip):
  118. return ip in ReservedIPBlocks.LOCALHOST_SEGMENT
  119. @staticmethod
  120. def is_multicast(ip):
  121. return ip in ReservedIPBlocks.MULTICAST_SEGMENT
  122. @staticmethod
  123. def is_reserved(ip):
  124. return ip in ReservedIPBlocks.RESERVED_SEGMENT
  125. @staticmethod
  126. def is_zero_conf(ip):
  127. return ip in ReservedIPBlocks.ZERO_CONF_SEGMENT