IPv4.py 4.8 KB

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