logo

oasis-root

Compiled tree of Oasis Linux based on own branch at <https://hacktivis.me/git/oasis/> git clone https://anongit.hacktivis.me/git/oasis-root.git

ipaddress.py (74786B)


  1. # Copyright 2007 Google Inc.
  2. # Licensed to PSF under a Contributor Agreement.
  3. """A fast, lightweight IPv4/IPv6 manipulation library in Python.
  4. This library is used to create/poke/manipulate IPv4 and IPv6 addresses
  5. and networks.
  6. """
  7. __version__ = '1.0'
  8. import functools
  9. IPV4LENGTH = 32
  10. IPV6LENGTH = 128
  11. class AddressValueError(ValueError):
  12. """A Value Error related to the address."""
  13. class NetmaskValueError(ValueError):
  14. """A Value Error related to the netmask."""
  15. def ip_address(address):
  16. """Take an IP string/int and return an object of the correct type.
  17. Args:
  18. address: A string or integer, the IP address. Either IPv4 or
  19. IPv6 addresses may be supplied; integers less than 2**32 will
  20. be considered to be IPv4 by default.
  21. Returns:
  22. An IPv4Address or IPv6Address object.
  23. Raises:
  24. ValueError: if the *address* passed isn't either a v4 or a v6
  25. address
  26. """
  27. try:
  28. return IPv4Address(address)
  29. except (AddressValueError, NetmaskValueError):
  30. pass
  31. try:
  32. return IPv6Address(address)
  33. except (AddressValueError, NetmaskValueError):
  34. pass
  35. raise ValueError('%r does not appear to be an IPv4 or IPv6 address' %
  36. address)
  37. def ip_network(address, strict=True):
  38. """Take an IP string/int and return an object of the correct type.
  39. Args:
  40. address: A string or integer, the IP network. Either IPv4 or
  41. IPv6 networks may be supplied; integers less than 2**32 will
  42. be considered to be IPv4 by default.
  43. Returns:
  44. An IPv4Network or IPv6Network object.
  45. Raises:
  46. ValueError: if the string passed isn't either a v4 or a v6
  47. address. Or if the network has host bits set.
  48. """
  49. try:
  50. return IPv4Network(address, strict)
  51. except (AddressValueError, NetmaskValueError):
  52. pass
  53. try:
  54. return IPv6Network(address, strict)
  55. except (AddressValueError, NetmaskValueError):
  56. pass
  57. raise ValueError('%r does not appear to be an IPv4 or IPv6 network' %
  58. address)
  59. def ip_interface(address):
  60. """Take an IP string/int and return an object of the correct type.
  61. Args:
  62. address: A string or integer, the IP address. Either IPv4 or
  63. IPv6 addresses may be supplied; integers less than 2**32 will
  64. be considered to be IPv4 by default.
  65. Returns:
  66. An IPv4Interface or IPv6Interface object.
  67. Raises:
  68. ValueError: if the string passed isn't either a v4 or a v6
  69. address.
  70. Notes:
  71. The IPv?Interface classes describe an Address on a particular
  72. Network, so they're basically a combination of both the Address
  73. and Network classes.
  74. """
  75. try:
  76. return IPv4Interface(address)
  77. except (AddressValueError, NetmaskValueError):
  78. pass
  79. try:
  80. return IPv6Interface(address)
  81. except (AddressValueError, NetmaskValueError):
  82. pass
  83. raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' %
  84. address)
  85. def v4_int_to_packed(address):
  86. """Represent an address as 4 packed bytes in network (big-endian) order.
  87. Args:
  88. address: An integer representation of an IPv4 IP address.
  89. Returns:
  90. The integer address packed as 4 bytes in network (big-endian) order.
  91. Raises:
  92. ValueError: If the integer is negative or too large to be an
  93. IPv4 IP address.
  94. """
  95. try:
  96. return address.to_bytes(4, 'big')
  97. except OverflowError:
  98. raise ValueError("Address negative or too large for IPv4")
  99. def v6_int_to_packed(address):
  100. """Represent an address as 16 packed bytes in network (big-endian) order.
  101. Args:
  102. address: An integer representation of an IPv6 IP address.
  103. Returns:
  104. The integer address packed as 16 bytes in network (big-endian) order.
  105. """
  106. try:
  107. return address.to_bytes(16, 'big')
  108. except OverflowError:
  109. raise ValueError("Address negative or too large for IPv6")
  110. def _split_optional_netmask(address):
  111. """Helper to split the netmask and raise AddressValueError if needed"""
  112. addr = str(address).split('/')
  113. if len(addr) > 2:
  114. raise AddressValueError("Only one '/' permitted in %r" % address)
  115. return addr
  116. def _find_address_range(addresses):
  117. """Find a sequence of sorted deduplicated IPv#Address.
  118. Args:
  119. addresses: a list of IPv#Address objects.
  120. Yields:
  121. A tuple containing the first and last IP addresses in the sequence.
  122. """
  123. it = iter(addresses)
  124. first = last = next(it)
  125. for ip in it:
  126. if ip._ip != last._ip + 1:
  127. yield first, last
  128. first = ip
  129. last = ip
  130. yield first, last
  131. def _count_righthand_zero_bits(number, bits):
  132. """Count the number of zero bits on the right hand side.
  133. Args:
  134. number: an integer.
  135. bits: maximum number of bits to count.
  136. Returns:
  137. The number of zero bits on the right hand side of the number.
  138. """
  139. if number == 0:
  140. return bits
  141. return min(bits, (~number & (number-1)).bit_length())
  142. def summarize_address_range(first, last):
  143. """Summarize a network range given the first and last IP addresses.
  144. Example:
  145. >>> list(summarize_address_range(IPv4Address('192.0.2.0'),
  146. ... IPv4Address('192.0.2.130')))
  147. ... #doctest: +NORMALIZE_WHITESPACE
  148. [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'),
  149. IPv4Network('192.0.2.130/32')]
  150. Args:
  151. first: the first IPv4Address or IPv6Address in the range.
  152. last: the last IPv4Address or IPv6Address in the range.
  153. Returns:
  154. An iterator of the summarized IPv(4|6) network objects.
  155. Raise:
  156. TypeError:
  157. If the first and last objects are not IP addresses.
  158. If the first and last objects are not the same version.
  159. ValueError:
  160. If the last object is not greater than the first.
  161. If the version of the first address is not 4 or 6.
  162. """
  163. if (not (isinstance(first, _BaseAddress) and
  164. isinstance(last, _BaseAddress))):
  165. raise TypeError('first and last must be IP addresses, not networks')
  166. if first.version != last.version:
  167. raise TypeError("%s and %s are not of the same version" % (
  168. first, last))
  169. if first > last:
  170. raise ValueError('last IP address must be greater than first')
  171. if first.version == 4:
  172. ip = IPv4Network
  173. elif first.version == 6:
  174. ip = IPv6Network
  175. else:
  176. raise ValueError('unknown IP version')
  177. ip_bits = first._max_prefixlen
  178. first_int = first._ip
  179. last_int = last._ip
  180. while first_int <= last_int:
  181. nbits = min(_count_righthand_zero_bits(first_int, ip_bits),
  182. (last_int - first_int + 1).bit_length() - 1)
  183. net = ip((first_int, ip_bits - nbits))
  184. yield net
  185. first_int += 1 << nbits
  186. if first_int - 1 == ip._ALL_ONES:
  187. break
  188. def _collapse_addresses_internal(addresses):
  189. """Loops through the addresses, collapsing concurrent netblocks.
  190. Example:
  191. ip1 = IPv4Network('192.0.2.0/26')
  192. ip2 = IPv4Network('192.0.2.64/26')
  193. ip3 = IPv4Network('192.0.2.128/26')
  194. ip4 = IPv4Network('192.0.2.192/26')
  195. _collapse_addresses_internal([ip1, ip2, ip3, ip4]) ->
  196. [IPv4Network('192.0.2.0/24')]
  197. This shouldn't be called directly; it is called via
  198. collapse_addresses([]).
  199. Args:
  200. addresses: A list of IPv4Network's or IPv6Network's
  201. Returns:
  202. A list of IPv4Network's or IPv6Network's depending on what we were
  203. passed.
  204. """
  205. # First merge
  206. to_merge = list(addresses)
  207. subnets = {}
  208. while to_merge:
  209. net = to_merge.pop()
  210. supernet = net.supernet()
  211. existing = subnets.get(supernet)
  212. if existing is None:
  213. subnets[supernet] = net
  214. elif existing != net:
  215. # Merge consecutive subnets
  216. del subnets[supernet]
  217. to_merge.append(supernet)
  218. # Then iterate over resulting networks, skipping subsumed subnets
  219. last = None
  220. for net in sorted(subnets.values()):
  221. if last is not None:
  222. # Since they are sorted, last.network_address <= net.network_address
  223. # is a given.
  224. if last.broadcast_address >= net.broadcast_address:
  225. continue
  226. yield net
  227. last = net
  228. def collapse_addresses(addresses):
  229. """Collapse a list of IP objects.
  230. Example:
  231. collapse_addresses([IPv4Network('192.0.2.0/25'),
  232. IPv4Network('192.0.2.128/25')]) ->
  233. [IPv4Network('192.0.2.0/24')]
  234. Args:
  235. addresses: An iterator of IPv4Network or IPv6Network objects.
  236. Returns:
  237. An iterator of the collapsed IPv(4|6)Network objects.
  238. Raises:
  239. TypeError: If passed a list of mixed version objects.
  240. """
  241. addrs = []
  242. ips = []
  243. nets = []
  244. # split IP addresses and networks
  245. for ip in addresses:
  246. if isinstance(ip, _BaseAddress):
  247. if ips and ips[-1]._version != ip._version:
  248. raise TypeError("%s and %s are not of the same version" % (
  249. ip, ips[-1]))
  250. ips.append(ip)
  251. elif ip._prefixlen == ip._max_prefixlen:
  252. if ips and ips[-1]._version != ip._version:
  253. raise TypeError("%s and %s are not of the same version" % (
  254. ip, ips[-1]))
  255. try:
  256. ips.append(ip.ip)
  257. except AttributeError:
  258. ips.append(ip.network_address)
  259. else:
  260. if nets and nets[-1]._version != ip._version:
  261. raise TypeError("%s and %s are not of the same version" % (
  262. ip, nets[-1]))
  263. nets.append(ip)
  264. # sort and dedup
  265. ips = sorted(set(ips))
  266. # find consecutive address ranges in the sorted sequence and summarize them
  267. if ips:
  268. for first, last in _find_address_range(ips):
  269. addrs.extend(summarize_address_range(first, last))
  270. return _collapse_addresses_internal(addrs + nets)
  271. def get_mixed_type_key(obj):
  272. """Return a key suitable for sorting between networks and addresses.
  273. Address and Network objects are not sortable by default; they're
  274. fundamentally different so the expression
  275. IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
  276. doesn't make any sense. There are some times however, where you may wish
  277. to have ipaddress sort these for you anyway. If you need to do this, you
  278. can use this function as the key= argument to sorted().
  279. Args:
  280. obj: either a Network or Address object.
  281. Returns:
  282. appropriate key.
  283. """
  284. if isinstance(obj, _BaseNetwork):
  285. return obj._get_networks_key()
  286. elif isinstance(obj, _BaseAddress):
  287. return obj._get_address_key()
  288. return NotImplemented
  289. class _IPAddressBase:
  290. """The mother class."""
  291. __slots__ = ()
  292. @property
  293. def exploded(self):
  294. """Return the longhand version of the IP address as a string."""
  295. return self._explode_shorthand_ip_string()
  296. @property
  297. def compressed(self):
  298. """Return the shorthand version of the IP address as a string."""
  299. return str(self)
  300. @property
  301. def reverse_pointer(self):
  302. """The name of the reverse DNS pointer for the IP address, e.g.:
  303. >>> ipaddress.ip_address("127.0.0.1").reverse_pointer
  304. '1.0.0.127.in-addr.arpa'
  305. >>> ipaddress.ip_address("2001:db8::1").reverse_pointer
  306. '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa'
  307. """
  308. return self._reverse_pointer()
  309. @property
  310. def version(self):
  311. msg = '%200s has no version specified' % (type(self),)
  312. raise NotImplementedError(msg)
  313. def _check_int_address(self, address):
  314. if address < 0:
  315. msg = "%d (< 0) is not permitted as an IPv%d address"
  316. raise AddressValueError(msg % (address, self._version))
  317. if address > self._ALL_ONES:
  318. msg = "%d (>= 2**%d) is not permitted as an IPv%d address"
  319. raise AddressValueError(msg % (address, self._max_prefixlen,
  320. self._version))
  321. def _check_packed_address(self, address, expected_len):
  322. address_len = len(address)
  323. if address_len != expected_len:
  324. msg = "%r (len %d != %d) is not permitted as an IPv%d address"
  325. raise AddressValueError(msg % (address, address_len,
  326. expected_len, self._version))
  327. @classmethod
  328. def _ip_int_from_prefix(cls, prefixlen):
  329. """Turn the prefix length into a bitwise netmask
  330. Args:
  331. prefixlen: An integer, the prefix length.
  332. Returns:
  333. An integer.
  334. """
  335. return cls._ALL_ONES ^ (cls._ALL_ONES >> prefixlen)
  336. @classmethod
  337. def _prefix_from_ip_int(cls, ip_int):
  338. """Return prefix length from the bitwise netmask.
  339. Args:
  340. ip_int: An integer, the netmask in expanded bitwise format
  341. Returns:
  342. An integer, the prefix length.
  343. Raises:
  344. ValueError: If the input intermingles zeroes & ones
  345. """
  346. trailing_zeroes = _count_righthand_zero_bits(ip_int,
  347. cls._max_prefixlen)
  348. prefixlen = cls._max_prefixlen - trailing_zeroes
  349. leading_ones = ip_int >> trailing_zeroes
  350. all_ones = (1 << prefixlen) - 1
  351. if leading_ones != all_ones:
  352. byteslen = cls._max_prefixlen // 8
  353. details = ip_int.to_bytes(byteslen, 'big')
  354. msg = 'Netmask pattern %r mixes zeroes & ones'
  355. raise ValueError(msg % details)
  356. return prefixlen
  357. @classmethod
  358. def _report_invalid_netmask(cls, netmask_str):
  359. msg = '%r is not a valid netmask' % netmask_str
  360. raise NetmaskValueError(msg) from None
  361. @classmethod
  362. def _prefix_from_prefix_string(cls, prefixlen_str):
  363. """Return prefix length from a numeric string
  364. Args:
  365. prefixlen_str: The string to be converted
  366. Returns:
  367. An integer, the prefix length.
  368. Raises:
  369. NetmaskValueError: If the input is not a valid netmask
  370. """
  371. # int allows a leading +/- as well as surrounding whitespace,
  372. # so we ensure that isn't the case
  373. if not (prefixlen_str.isascii() and prefixlen_str.isdigit()):
  374. cls._report_invalid_netmask(prefixlen_str)
  375. try:
  376. prefixlen = int(prefixlen_str)
  377. except ValueError:
  378. cls._report_invalid_netmask(prefixlen_str)
  379. if not (0 <= prefixlen <= cls._max_prefixlen):
  380. cls._report_invalid_netmask(prefixlen_str)
  381. return prefixlen
  382. @classmethod
  383. def _prefix_from_ip_string(cls, ip_str):
  384. """Turn a netmask/hostmask string into a prefix length
  385. Args:
  386. ip_str: The netmask/hostmask to be converted
  387. Returns:
  388. An integer, the prefix length.
  389. Raises:
  390. NetmaskValueError: If the input is not a valid netmask/hostmask
  391. """
  392. # Parse the netmask/hostmask like an IP address.
  393. try:
  394. ip_int = cls._ip_int_from_string(ip_str)
  395. except AddressValueError:
  396. cls._report_invalid_netmask(ip_str)
  397. # Try matching a netmask (this would be /1*0*/ as a bitwise regexp).
  398. # Note that the two ambiguous cases (all-ones and all-zeroes) are
  399. # treated as netmasks.
  400. try:
  401. return cls._prefix_from_ip_int(ip_int)
  402. except ValueError:
  403. pass
  404. # Invert the bits, and try matching a /0+1+/ hostmask instead.
  405. ip_int ^= cls._ALL_ONES
  406. try:
  407. return cls._prefix_from_ip_int(ip_int)
  408. except ValueError:
  409. cls._report_invalid_netmask(ip_str)
  410. @classmethod
  411. def _split_addr_prefix(cls, address):
  412. """Helper function to parse address of Network/Interface.
  413. Arg:
  414. address: Argument of Network/Interface.
  415. Returns:
  416. (addr, prefix) tuple.
  417. """
  418. # a packed address or integer
  419. if isinstance(address, (bytes, int)):
  420. return address, cls._max_prefixlen
  421. if not isinstance(address, tuple):
  422. # Assume input argument to be string or any object representation
  423. # which converts into a formatted IP prefix string.
  424. address = _split_optional_netmask(address)
  425. # Constructing from a tuple (addr, [mask])
  426. if len(address) > 1:
  427. return address
  428. return address[0], cls._max_prefixlen
  429. def __reduce__(self):
  430. return self.__class__, (str(self),)
  431. _address_fmt_re = None
  432. @functools.total_ordering
  433. class _BaseAddress(_IPAddressBase):
  434. """A generic IP object.
  435. This IP class contains the version independent methods which are
  436. used by single IP addresses.
  437. """
  438. __slots__ = ()
  439. def __int__(self):
  440. return self._ip
  441. def __eq__(self, other):
  442. try:
  443. return (self._ip == other._ip
  444. and self._version == other._version)
  445. except AttributeError:
  446. return NotImplemented
  447. def __lt__(self, other):
  448. if not isinstance(other, _BaseAddress):
  449. return NotImplemented
  450. if self._version != other._version:
  451. raise TypeError('%s and %s are not of the same version' % (
  452. self, other))
  453. if self._ip != other._ip:
  454. return self._ip < other._ip
  455. return False
  456. # Shorthand for Integer addition and subtraction. This is not
  457. # meant to ever support addition/subtraction of addresses.
  458. def __add__(self, other):
  459. if not isinstance(other, int):
  460. return NotImplemented
  461. return self.__class__(int(self) + other)
  462. def __sub__(self, other):
  463. if not isinstance(other, int):
  464. return NotImplemented
  465. return self.__class__(int(self) - other)
  466. def __repr__(self):
  467. return '%s(%r)' % (self.__class__.__name__, str(self))
  468. def __str__(self):
  469. return str(self._string_from_ip_int(self._ip))
  470. def __hash__(self):
  471. return hash(hex(int(self._ip)))
  472. def _get_address_key(self):
  473. return (self._version, self)
  474. def __reduce__(self):
  475. return self.__class__, (self._ip,)
  476. def __format__(self, fmt):
  477. """Returns an IP address as a formatted string.
  478. Supported presentation types are:
  479. 's': returns the IP address as a string (default)
  480. 'b': converts to binary and returns a zero-padded string
  481. 'X' or 'x': converts to upper- or lower-case hex and returns a zero-padded string
  482. 'n': the same as 'b' for IPv4 and 'x' for IPv6
  483. For binary and hex presentation types, the alternate form specifier
  484. '#' and the grouping option '_' are supported.
  485. """
  486. # Support string formatting
  487. if not fmt or fmt[-1] == 's':
  488. return format(str(self), fmt)
  489. # From here on down, support for 'bnXx'
  490. global _address_fmt_re
  491. if _address_fmt_re is None:
  492. import re
  493. _address_fmt_re = re.compile('(#?)(_?)([xbnX])')
  494. m = _address_fmt_re.fullmatch(fmt)
  495. if not m:
  496. return super().__format__(fmt)
  497. alternate, grouping, fmt_base = m.groups()
  498. # Set some defaults
  499. if fmt_base == 'n':
  500. if self._version == 4:
  501. fmt_base = 'b' # Binary is default for ipv4
  502. else:
  503. fmt_base = 'x' # Hex is default for ipv6
  504. if fmt_base == 'b':
  505. padlen = self._max_prefixlen
  506. else:
  507. padlen = self._max_prefixlen // 4
  508. if grouping:
  509. padlen += padlen // 4 - 1
  510. if alternate:
  511. padlen += 2 # 0b or 0x
  512. return format(int(self), f'{alternate}0{padlen}{grouping}{fmt_base}')
  513. @functools.total_ordering
  514. class _BaseNetwork(_IPAddressBase):
  515. """A generic IP network object.
  516. This IP class contains the version independent methods which are
  517. used by networks.
  518. """
  519. def __repr__(self):
  520. return '%s(%r)' % (self.__class__.__name__, str(self))
  521. def __str__(self):
  522. return '%s/%d' % (self.network_address, self.prefixlen)
  523. def hosts(self):
  524. """Generate Iterator over usable hosts in a network.
  525. This is like __iter__ except it doesn't return the network
  526. or broadcast addresses.
  527. """
  528. network = int(self.network_address)
  529. broadcast = int(self.broadcast_address)
  530. for x in range(network + 1, broadcast):
  531. yield self._address_class(x)
  532. def __iter__(self):
  533. network = int(self.network_address)
  534. broadcast = int(self.broadcast_address)
  535. for x in range(network, broadcast + 1):
  536. yield self._address_class(x)
  537. def __getitem__(self, n):
  538. network = int(self.network_address)
  539. broadcast = int(self.broadcast_address)
  540. if n >= 0:
  541. if network + n > broadcast:
  542. raise IndexError('address out of range')
  543. return self._address_class(network + n)
  544. else:
  545. n += 1
  546. if broadcast + n < network:
  547. raise IndexError('address out of range')
  548. return self._address_class(broadcast + n)
  549. def __lt__(self, other):
  550. if not isinstance(other, _BaseNetwork):
  551. return NotImplemented
  552. if self._version != other._version:
  553. raise TypeError('%s and %s are not of the same version' % (
  554. self, other))
  555. if self.network_address != other.network_address:
  556. return self.network_address < other.network_address
  557. if self.netmask != other.netmask:
  558. return self.netmask < other.netmask
  559. return False
  560. def __eq__(self, other):
  561. try:
  562. return (self._version == other._version and
  563. self.network_address == other.network_address and
  564. int(self.netmask) == int(other.netmask))
  565. except AttributeError:
  566. return NotImplemented
  567. def __hash__(self):
  568. return hash(int(self.network_address) ^ int(self.netmask))
  569. def __contains__(self, other):
  570. # always false if one is v4 and the other is v6.
  571. if self._version != other._version:
  572. return False
  573. # dealing with another network.
  574. if isinstance(other, _BaseNetwork):
  575. return False
  576. # dealing with another address
  577. else:
  578. # address
  579. return other._ip & self.netmask._ip == self.network_address._ip
  580. def overlaps(self, other):
  581. """Tell if self is partly contained in other."""
  582. return self.network_address in other or (
  583. self.broadcast_address in other or (
  584. other.network_address in self or (
  585. other.broadcast_address in self)))
  586. @functools.cached_property
  587. def broadcast_address(self):
  588. return self._address_class(int(self.network_address) |
  589. int(self.hostmask))
  590. @functools.cached_property
  591. def hostmask(self):
  592. return self._address_class(int(self.netmask) ^ self._ALL_ONES)
  593. @property
  594. def with_prefixlen(self):
  595. return '%s/%d' % (self.network_address, self._prefixlen)
  596. @property
  597. def with_netmask(self):
  598. return '%s/%s' % (self.network_address, self.netmask)
  599. @property
  600. def with_hostmask(self):
  601. return '%s/%s' % (self.network_address, self.hostmask)
  602. @property
  603. def num_addresses(self):
  604. """Number of hosts in the current subnet."""
  605. return int(self.broadcast_address) - int(self.network_address) + 1
  606. @property
  607. def _address_class(self):
  608. # Returning bare address objects (rather than interfaces) allows for
  609. # more consistent behaviour across the network address, broadcast
  610. # address and individual host addresses.
  611. msg = '%200s has no associated address class' % (type(self),)
  612. raise NotImplementedError(msg)
  613. @property
  614. def prefixlen(self):
  615. return self._prefixlen
  616. def address_exclude(self, other):
  617. """Remove an address from a larger block.
  618. For example:
  619. addr1 = ip_network('192.0.2.0/28')
  620. addr2 = ip_network('192.0.2.1/32')
  621. list(addr1.address_exclude(addr2)) =
  622. [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
  623. IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
  624. or IPv6:
  625. addr1 = ip_network('2001:db8::1/32')
  626. addr2 = ip_network('2001:db8::1/128')
  627. list(addr1.address_exclude(addr2)) =
  628. [ip_network('2001:db8::1/128'),
  629. ip_network('2001:db8::2/127'),
  630. ip_network('2001:db8::4/126'),
  631. ip_network('2001:db8::8/125'),
  632. ...
  633. ip_network('2001:db8:8000::/33')]
  634. Args:
  635. other: An IPv4Network or IPv6Network object of the same type.
  636. Returns:
  637. An iterator of the IPv(4|6)Network objects which is self
  638. minus other.
  639. Raises:
  640. TypeError: If self and other are of differing address
  641. versions, or if other is not a network object.
  642. ValueError: If other is not completely contained by self.
  643. """
  644. if not self._version == other._version:
  645. raise TypeError("%s and %s are not of the same version" % (
  646. self, other))
  647. if not isinstance(other, _BaseNetwork):
  648. raise TypeError("%s is not a network object" % other)
  649. if not other.subnet_of(self):
  650. raise ValueError('%s not contained in %s' % (other, self))
  651. if other == self:
  652. return
  653. # Make sure we're comparing the network of other.
  654. other = other.__class__('%s/%s' % (other.network_address,
  655. other.prefixlen))
  656. s1, s2 = self.subnets()
  657. while s1 != other and s2 != other:
  658. if other.subnet_of(s1):
  659. yield s2
  660. s1, s2 = s1.subnets()
  661. elif other.subnet_of(s2):
  662. yield s1
  663. s1, s2 = s2.subnets()
  664. else:
  665. # If we got here, there's a bug somewhere.
  666. raise AssertionError('Error performing exclusion: '
  667. 's1: %s s2: %s other: %s' %
  668. (s1, s2, other))
  669. if s1 == other:
  670. yield s2
  671. elif s2 == other:
  672. yield s1
  673. else:
  674. # If we got here, there's a bug somewhere.
  675. raise AssertionError('Error performing exclusion: '
  676. 's1: %s s2: %s other: %s' %
  677. (s1, s2, other))
  678. def compare_networks(self, other):
  679. """Compare two IP objects.
  680. This is only concerned about the comparison of the integer
  681. representation of the network addresses. This means that the
  682. host bits aren't considered at all in this method. If you want
  683. to compare host bits, you can easily enough do a
  684. 'HostA._ip < HostB._ip'
  685. Args:
  686. other: An IP object.
  687. Returns:
  688. If the IP versions of self and other are the same, returns:
  689. -1 if self < other:
  690. eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
  691. IPv6Network('2001:db8::1000/124') <
  692. IPv6Network('2001:db8::2000/124')
  693. 0 if self == other
  694. eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
  695. IPv6Network('2001:db8::1000/124') ==
  696. IPv6Network('2001:db8::1000/124')
  697. 1 if self > other
  698. eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
  699. IPv6Network('2001:db8::2000/124') >
  700. IPv6Network('2001:db8::1000/124')
  701. Raises:
  702. TypeError if the IP versions are different.
  703. """
  704. # does this need to raise a ValueError?
  705. if self._version != other._version:
  706. raise TypeError('%s and %s are not of the same type' % (
  707. self, other))
  708. # self._version == other._version below here:
  709. if self.network_address < other.network_address:
  710. return -1
  711. if self.network_address > other.network_address:
  712. return 1
  713. # self.network_address == other.network_address below here:
  714. if self.netmask < other.netmask:
  715. return -1
  716. if self.netmask > other.netmask:
  717. return 1
  718. return 0
  719. def _get_networks_key(self):
  720. """Network-only key function.
  721. Returns an object that identifies this address' network and
  722. netmask. This function is a suitable "key" argument for sorted()
  723. and list.sort().
  724. """
  725. return (self._version, self.network_address, self.netmask)
  726. def subnets(self, prefixlen_diff=1, new_prefix=None):
  727. """The subnets which join to make the current subnet.
  728. In the case that self contains only one IP
  729. (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
  730. for IPv6), yield an iterator with just ourself.
  731. Args:
  732. prefixlen_diff: An integer, the amount the prefix length
  733. should be increased by. This should not be set if
  734. new_prefix is also set.
  735. new_prefix: The desired new prefix length. This must be a
  736. larger number (smaller prefix) than the existing prefix.
  737. This should not be set if prefixlen_diff is also set.
  738. Returns:
  739. An iterator of IPv(4|6) objects.
  740. Raises:
  741. ValueError: The prefixlen_diff is too small or too large.
  742. OR
  743. prefixlen_diff and new_prefix are both set or new_prefix
  744. is a smaller number than the current prefix (smaller
  745. number means a larger network)
  746. """
  747. if self._prefixlen == self._max_prefixlen:
  748. yield self
  749. return
  750. if new_prefix is not None:
  751. if new_prefix < self._prefixlen:
  752. raise ValueError('new prefix must be longer')
  753. if prefixlen_diff != 1:
  754. raise ValueError('cannot set prefixlen_diff and new_prefix')
  755. prefixlen_diff = new_prefix - self._prefixlen
  756. if prefixlen_diff < 0:
  757. raise ValueError('prefix length diff must be > 0')
  758. new_prefixlen = self._prefixlen + prefixlen_diff
  759. if new_prefixlen > self._max_prefixlen:
  760. raise ValueError(
  761. 'prefix length diff %d is invalid for netblock %s' % (
  762. new_prefixlen, self))
  763. start = int(self.network_address)
  764. end = int(self.broadcast_address) + 1
  765. step = (int(self.hostmask) + 1) >> prefixlen_diff
  766. for new_addr in range(start, end, step):
  767. current = self.__class__((new_addr, new_prefixlen))
  768. yield current
  769. def supernet(self, prefixlen_diff=1, new_prefix=None):
  770. """The supernet containing the current network.
  771. Args:
  772. prefixlen_diff: An integer, the amount the prefix length of
  773. the network should be decreased by. For example, given a
  774. /24 network and a prefixlen_diff of 3, a supernet with a
  775. /21 netmask is returned.
  776. Returns:
  777. An IPv4 network object.
  778. Raises:
  779. ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
  780. a negative prefix length.
  781. OR
  782. If prefixlen_diff and new_prefix are both set or new_prefix is a
  783. larger number than the current prefix (larger number means a
  784. smaller network)
  785. """
  786. if self._prefixlen == 0:
  787. return self
  788. if new_prefix is not None:
  789. if new_prefix > self._prefixlen:
  790. raise ValueError('new prefix must be shorter')
  791. if prefixlen_diff != 1:
  792. raise ValueError('cannot set prefixlen_diff and new_prefix')
  793. prefixlen_diff = self._prefixlen - new_prefix
  794. new_prefixlen = self.prefixlen - prefixlen_diff
  795. if new_prefixlen < 0:
  796. raise ValueError(
  797. 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
  798. (self.prefixlen, prefixlen_diff))
  799. return self.__class__((
  800. int(self.network_address) & (int(self.netmask) << prefixlen_diff),
  801. new_prefixlen
  802. ))
  803. @property
  804. def is_multicast(self):
  805. """Test if the address is reserved for multicast use.
  806. Returns:
  807. A boolean, True if the address is a multicast address.
  808. See RFC 2373 2.7 for details.
  809. """
  810. return (self.network_address.is_multicast and
  811. self.broadcast_address.is_multicast)
  812. @staticmethod
  813. def _is_subnet_of(a, b):
  814. try:
  815. # Always false if one is v4 and the other is v6.
  816. if a._version != b._version:
  817. raise TypeError(f"{a} and {b} are not of the same version")
  818. return (b.network_address <= a.network_address and
  819. b.broadcast_address >= a.broadcast_address)
  820. except AttributeError:
  821. raise TypeError(f"Unable to test subnet containment "
  822. f"between {a} and {b}")
  823. def subnet_of(self, other):
  824. """Return True if this network is a subnet of other."""
  825. return self._is_subnet_of(self, other)
  826. def supernet_of(self, other):
  827. """Return True if this network is a supernet of other."""
  828. return self._is_subnet_of(other, self)
  829. @property
  830. def is_reserved(self):
  831. """Test if the address is otherwise IETF reserved.
  832. Returns:
  833. A boolean, True if the address is within one of the
  834. reserved IPv6 Network ranges.
  835. """
  836. return (self.network_address.is_reserved and
  837. self.broadcast_address.is_reserved)
  838. @property
  839. def is_link_local(self):
  840. """Test if the address is reserved for link-local.
  841. Returns:
  842. A boolean, True if the address is reserved per RFC 4291.
  843. """
  844. return (self.network_address.is_link_local and
  845. self.broadcast_address.is_link_local)
  846. @property
  847. def is_private(self):
  848. """Test if this address is allocated for private networks.
  849. Returns:
  850. A boolean, True if the address is reserved per
  851. iana-ipv4-special-registry or iana-ipv6-special-registry.
  852. """
  853. return (self.network_address.is_private and
  854. self.broadcast_address.is_private)
  855. @property
  856. def is_global(self):
  857. """Test if this address is allocated for public networks.
  858. Returns:
  859. A boolean, True if the address is not reserved per
  860. iana-ipv4-special-registry or iana-ipv6-special-registry.
  861. """
  862. return not self.is_private
  863. @property
  864. def is_unspecified(self):
  865. """Test if the address is unspecified.
  866. Returns:
  867. A boolean, True if this is the unspecified address as defined in
  868. RFC 2373 2.5.2.
  869. """
  870. return (self.network_address.is_unspecified and
  871. self.broadcast_address.is_unspecified)
  872. @property
  873. def is_loopback(self):
  874. """Test if the address is a loopback address.
  875. Returns:
  876. A boolean, True if the address is a loopback address as defined in
  877. RFC 2373 2.5.3.
  878. """
  879. return (self.network_address.is_loopback and
  880. self.broadcast_address.is_loopback)
  881. class _BaseV4:
  882. """Base IPv4 object.
  883. The following methods are used by IPv4 objects in both single IP
  884. addresses and networks.
  885. """
  886. __slots__ = ()
  887. _version = 4
  888. # Equivalent to 255.255.255.255 or 32 bits of 1's.
  889. _ALL_ONES = (2**IPV4LENGTH) - 1
  890. _max_prefixlen = IPV4LENGTH
  891. # There are only a handful of valid v4 netmasks, so we cache them all
  892. # when constructed (see _make_netmask()).
  893. _netmask_cache = {}
  894. def _explode_shorthand_ip_string(self):
  895. return str(self)
  896. @classmethod
  897. def _make_netmask(cls, arg):
  898. """Make a (netmask, prefix_len) tuple from the given argument.
  899. Argument can be:
  900. - an integer (the prefix length)
  901. - a string representing the prefix length (e.g. "24")
  902. - a string representing the prefix netmask (e.g. "255.255.255.0")
  903. """
  904. if arg not in cls._netmask_cache:
  905. if isinstance(arg, int):
  906. prefixlen = arg
  907. if not (0 <= prefixlen <= cls._max_prefixlen):
  908. cls._report_invalid_netmask(prefixlen)
  909. else:
  910. try:
  911. # Check for a netmask in prefix length form
  912. prefixlen = cls._prefix_from_prefix_string(arg)
  913. except NetmaskValueError:
  914. # Check for a netmask or hostmask in dotted-quad form.
  915. # This may raise NetmaskValueError.
  916. prefixlen = cls._prefix_from_ip_string(arg)
  917. netmask = IPv4Address(cls._ip_int_from_prefix(prefixlen))
  918. cls._netmask_cache[arg] = netmask, prefixlen
  919. return cls._netmask_cache[arg]
  920. @classmethod
  921. def _ip_int_from_string(cls, ip_str):
  922. """Turn the given IP string into an integer for comparison.
  923. Args:
  924. ip_str: A string, the IP ip_str.
  925. Returns:
  926. The IP ip_str as an integer.
  927. Raises:
  928. AddressValueError: if ip_str isn't a valid IPv4 Address.
  929. """
  930. if not ip_str:
  931. raise AddressValueError('Address cannot be empty')
  932. octets = ip_str.split('.')
  933. if len(octets) != 4:
  934. raise AddressValueError("Expected 4 octets in %r" % ip_str)
  935. try:
  936. return int.from_bytes(map(cls._parse_octet, octets), 'big')
  937. except ValueError as exc:
  938. raise AddressValueError("%s in %r" % (exc, ip_str)) from None
  939. @classmethod
  940. def _parse_octet(cls, octet_str):
  941. """Convert a decimal octet into an integer.
  942. Args:
  943. octet_str: A string, the number to parse.
  944. Returns:
  945. The octet as an integer.
  946. Raises:
  947. ValueError: if the octet isn't strictly a decimal from [0..255].
  948. """
  949. if not octet_str:
  950. raise ValueError("Empty octet not permitted")
  951. # Reject non-ASCII digits.
  952. if not (octet_str.isascii() and octet_str.isdigit()):
  953. msg = "Only decimal digits permitted in %r"
  954. raise ValueError(msg % octet_str)
  955. # We do the length check second, since the invalid character error
  956. # is likely to be more informative for the user
  957. if len(octet_str) > 3:
  958. msg = "At most 3 characters permitted in %r"
  959. raise ValueError(msg % octet_str)
  960. # Handle leading zeros as strict as glibc's inet_pton()
  961. # See security bug bpo-36384
  962. if octet_str != '0' and octet_str[0] == '0':
  963. msg = "Leading zeros are not permitted in %r"
  964. raise ValueError(msg % octet_str)
  965. # Convert to integer (we know digits are legal)
  966. octet_int = int(octet_str, 10)
  967. if octet_int > 255:
  968. raise ValueError("Octet %d (> 255) not permitted" % octet_int)
  969. return octet_int
  970. @classmethod
  971. def _string_from_ip_int(cls, ip_int):
  972. """Turns a 32-bit integer into dotted decimal notation.
  973. Args:
  974. ip_int: An integer, the IP address.
  975. Returns:
  976. The IP address as a string in dotted decimal notation.
  977. """
  978. return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
  979. def _reverse_pointer(self):
  980. """Return the reverse DNS pointer name for the IPv4 address.
  981. This implements the method described in RFC1035 3.5.
  982. """
  983. reverse_octets = str(self).split('.')[::-1]
  984. return '.'.join(reverse_octets) + '.in-addr.arpa'
  985. @property
  986. def max_prefixlen(self):
  987. return self._max_prefixlen
  988. @property
  989. def version(self):
  990. return self._version
  991. class IPv4Address(_BaseV4, _BaseAddress):
  992. """Represent and manipulate single IPv4 Addresses."""
  993. __slots__ = ('_ip', '__weakref__')
  994. def __init__(self, address):
  995. """
  996. Args:
  997. address: A string or integer representing the IP
  998. Additionally, an integer can be passed, so
  999. IPv4Address('192.0.2.1') == IPv4Address(3221225985).
  1000. or, more generally
  1001. IPv4Address(int(IPv4Address('192.0.2.1'))) ==
  1002. IPv4Address('192.0.2.1')
  1003. Raises:
  1004. AddressValueError: If ipaddress isn't a valid IPv4 address.
  1005. """
  1006. # Efficient constructor from integer.
  1007. if isinstance(address, int):
  1008. self._check_int_address(address)
  1009. self._ip = address
  1010. return
  1011. # Constructing from a packed address
  1012. if isinstance(address, bytes):
  1013. self._check_packed_address(address, 4)
  1014. self._ip = int.from_bytes(address, 'big')
  1015. return
  1016. # Assume input argument to be string or any object representation
  1017. # which converts into a formatted IP string.
  1018. addr_str = str(address)
  1019. if '/' in addr_str:
  1020. raise AddressValueError("Unexpected '/' in %r" % address)
  1021. self._ip = self._ip_int_from_string(addr_str)
  1022. @property
  1023. def packed(self):
  1024. """The binary representation of this address."""
  1025. return v4_int_to_packed(self._ip)
  1026. @property
  1027. def is_reserved(self):
  1028. """Test if the address is otherwise IETF reserved.
  1029. Returns:
  1030. A boolean, True if the address is within the
  1031. reserved IPv4 Network range.
  1032. """
  1033. return self in self._constants._reserved_network
  1034. @property
  1035. @functools.lru_cache()
  1036. def is_private(self):
  1037. """Test if this address is allocated for private networks.
  1038. Returns:
  1039. A boolean, True if the address is reserved per
  1040. iana-ipv4-special-registry.
  1041. """
  1042. return any(self in net for net in self._constants._private_networks)
  1043. @property
  1044. @functools.lru_cache()
  1045. def is_global(self):
  1046. return self not in self._constants._public_network and not self.is_private
  1047. @property
  1048. def is_multicast(self):
  1049. """Test if the address is reserved for multicast use.
  1050. Returns:
  1051. A boolean, True if the address is multicast.
  1052. See RFC 3171 for details.
  1053. """
  1054. return self in self._constants._multicast_network
  1055. @property
  1056. def is_unspecified(self):
  1057. """Test if the address is unspecified.
  1058. Returns:
  1059. A boolean, True if this is the unspecified address as defined in
  1060. RFC 5735 3.
  1061. """
  1062. return self == self._constants._unspecified_address
  1063. @property
  1064. def is_loopback(self):
  1065. """Test if the address is a loopback address.
  1066. Returns:
  1067. A boolean, True if the address is a loopback per RFC 3330.
  1068. """
  1069. return self in self._constants._loopback_network
  1070. @property
  1071. def is_link_local(self):
  1072. """Test if the address is reserved for link-local.
  1073. Returns:
  1074. A boolean, True if the address is link-local per RFC 3927.
  1075. """
  1076. return self in self._constants._linklocal_network
  1077. class IPv4Interface(IPv4Address):
  1078. def __init__(self, address):
  1079. addr, mask = self._split_addr_prefix(address)
  1080. IPv4Address.__init__(self, addr)
  1081. self.network = IPv4Network((addr, mask), strict=False)
  1082. self.netmask = self.network.netmask
  1083. self._prefixlen = self.network._prefixlen
  1084. @functools.cached_property
  1085. def hostmask(self):
  1086. return self.network.hostmask
  1087. def __str__(self):
  1088. return '%s/%d' % (self._string_from_ip_int(self._ip),
  1089. self._prefixlen)
  1090. def __eq__(self, other):
  1091. address_equal = IPv4Address.__eq__(self, other)
  1092. if address_equal is NotImplemented or not address_equal:
  1093. return address_equal
  1094. try:
  1095. return self.network == other.network
  1096. except AttributeError:
  1097. # An interface with an associated network is NOT the
  1098. # same as an unassociated address. That's why the hash
  1099. # takes the extra info into account.
  1100. return False
  1101. def __lt__(self, other):
  1102. address_less = IPv4Address.__lt__(self, other)
  1103. if address_less is NotImplemented:
  1104. return NotImplemented
  1105. try:
  1106. return (self.network < other.network or
  1107. self.network == other.network and address_less)
  1108. except AttributeError:
  1109. # We *do* allow addresses and interfaces to be sorted. The
  1110. # unassociated address is considered less than all interfaces.
  1111. return False
  1112. def __hash__(self):
  1113. return hash((self._ip, self._prefixlen, int(self.network.network_address)))
  1114. __reduce__ = _IPAddressBase.__reduce__
  1115. @property
  1116. def ip(self):
  1117. return IPv4Address(self._ip)
  1118. @property
  1119. def with_prefixlen(self):
  1120. return '%s/%s' % (self._string_from_ip_int(self._ip),
  1121. self._prefixlen)
  1122. @property
  1123. def with_netmask(self):
  1124. return '%s/%s' % (self._string_from_ip_int(self._ip),
  1125. self.netmask)
  1126. @property
  1127. def with_hostmask(self):
  1128. return '%s/%s' % (self._string_from_ip_int(self._ip),
  1129. self.hostmask)
  1130. class IPv4Network(_BaseV4, _BaseNetwork):
  1131. """This class represents and manipulates 32-bit IPv4 network + addresses..
  1132. Attributes: [examples for IPv4Network('192.0.2.0/27')]
  1133. .network_address: IPv4Address('192.0.2.0')
  1134. .hostmask: IPv4Address('0.0.0.31')
  1135. .broadcast_address: IPv4Address('192.0.2.32')
  1136. .netmask: IPv4Address('255.255.255.224')
  1137. .prefixlen: 27
  1138. """
  1139. # Class to use when creating address objects
  1140. _address_class = IPv4Address
  1141. def __init__(self, address, strict=True):
  1142. """Instantiate a new IPv4 network object.
  1143. Args:
  1144. address: A string or integer representing the IP [& network].
  1145. '192.0.2.0/24'
  1146. '192.0.2.0/255.255.255.0'
  1147. '192.0.2.0/0.0.0.255'
  1148. are all functionally the same in IPv4. Similarly,
  1149. '192.0.2.1'
  1150. '192.0.2.1/255.255.255.255'
  1151. '192.0.2.1/32'
  1152. are also functionally equivalent. That is to say, failing to
  1153. provide a subnetmask will create an object with a mask of /32.
  1154. If the mask (portion after the / in the argument) is given in
  1155. dotted quad form, it is treated as a netmask if it starts with a
  1156. non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
  1157. starts with a zero field (e.g. 0.255.255.255 == /8), with the
  1158. single exception of an all-zero mask which is treated as a
  1159. netmask == /0. If no mask is given, a default of /32 is used.
  1160. Additionally, an integer can be passed, so
  1161. IPv4Network('192.0.2.1') == IPv4Network(3221225985)
  1162. or, more generally
  1163. IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
  1164. IPv4Interface('192.0.2.1')
  1165. Raises:
  1166. AddressValueError: If ipaddress isn't a valid IPv4 address.
  1167. NetmaskValueError: If the netmask isn't valid for
  1168. an IPv4 address.
  1169. ValueError: If strict is True and a network address is not
  1170. supplied.
  1171. """
  1172. addr, mask = self._split_addr_prefix(address)
  1173. self.network_address = IPv4Address(addr)
  1174. self.netmask, self._prefixlen = self._make_netmask(mask)
  1175. packed = int(self.network_address)
  1176. if packed & int(self.netmask) != packed:
  1177. if strict:
  1178. raise ValueError('%s has host bits set' % self)
  1179. else:
  1180. self.network_address = IPv4Address(packed &
  1181. int(self.netmask))
  1182. if self._prefixlen == (self._max_prefixlen - 1):
  1183. self.hosts = self.__iter__
  1184. elif self._prefixlen == (self._max_prefixlen):
  1185. self.hosts = lambda: [IPv4Address(addr)]
  1186. @property
  1187. @functools.lru_cache()
  1188. def is_global(self):
  1189. """Test if this address is allocated for public networks.
  1190. Returns:
  1191. A boolean, True if the address is not reserved per
  1192. iana-ipv4-special-registry.
  1193. """
  1194. return (not (self.network_address in IPv4Network('100.64.0.0/10') and
  1195. self.broadcast_address in IPv4Network('100.64.0.0/10')) and
  1196. not self.is_private)
  1197. class _IPv4Constants:
  1198. _linklocal_network = IPv4Network('169.254.0.0/16')
  1199. _loopback_network = IPv4Network('127.0.0.0/8')
  1200. _multicast_network = IPv4Network('224.0.0.0/4')
  1201. _public_network = IPv4Network('100.64.0.0/10')
  1202. _private_networks = [
  1203. IPv4Network('0.0.0.0/8'),
  1204. IPv4Network('10.0.0.0/8'),
  1205. IPv4Network('127.0.0.0/8'),
  1206. IPv4Network('169.254.0.0/16'),
  1207. IPv4Network('172.16.0.0/12'),
  1208. IPv4Network('192.0.0.0/29'),
  1209. IPv4Network('192.0.0.170/31'),
  1210. IPv4Network('192.0.2.0/24'),
  1211. IPv4Network('192.168.0.0/16'),
  1212. IPv4Network('198.18.0.0/15'),
  1213. IPv4Network('198.51.100.0/24'),
  1214. IPv4Network('203.0.113.0/24'),
  1215. IPv4Network('240.0.0.0/4'),
  1216. IPv4Network('255.255.255.255/32'),
  1217. ]
  1218. _reserved_network = IPv4Network('240.0.0.0/4')
  1219. _unspecified_address = IPv4Address('0.0.0.0')
  1220. IPv4Address._constants = _IPv4Constants
  1221. class _BaseV6:
  1222. """Base IPv6 object.
  1223. The following methods are used by IPv6 objects in both single IP
  1224. addresses and networks.
  1225. """
  1226. __slots__ = ()
  1227. _version = 6
  1228. _ALL_ONES = (2**IPV6LENGTH) - 1
  1229. _HEXTET_COUNT = 8
  1230. _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
  1231. _max_prefixlen = IPV6LENGTH
  1232. # There are only a bunch of valid v6 netmasks, so we cache them all
  1233. # when constructed (see _make_netmask()).
  1234. _netmask_cache = {}
  1235. @classmethod
  1236. def _make_netmask(cls, arg):
  1237. """Make a (netmask, prefix_len) tuple from the given argument.
  1238. Argument can be:
  1239. - an integer (the prefix length)
  1240. - a string representing the prefix length (e.g. "24")
  1241. - a string representing the prefix netmask (e.g. "255.255.255.0")
  1242. """
  1243. if arg not in cls._netmask_cache:
  1244. if isinstance(arg, int):
  1245. prefixlen = arg
  1246. if not (0 <= prefixlen <= cls._max_prefixlen):
  1247. cls._report_invalid_netmask(prefixlen)
  1248. else:
  1249. prefixlen = cls._prefix_from_prefix_string(arg)
  1250. netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen))
  1251. cls._netmask_cache[arg] = netmask, prefixlen
  1252. return cls._netmask_cache[arg]
  1253. @classmethod
  1254. def _ip_int_from_string(cls, ip_str):
  1255. """Turn an IPv6 ip_str into an integer.
  1256. Args:
  1257. ip_str: A string, the IPv6 ip_str.
  1258. Returns:
  1259. An int, the IPv6 address
  1260. Raises:
  1261. AddressValueError: if ip_str isn't a valid IPv6 Address.
  1262. """
  1263. if not ip_str:
  1264. raise AddressValueError('Address cannot be empty')
  1265. parts = ip_str.split(':')
  1266. # An IPv6 address needs at least 2 colons (3 parts).
  1267. _min_parts = 3
  1268. if len(parts) < _min_parts:
  1269. msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
  1270. raise AddressValueError(msg)
  1271. # If the address has an IPv4-style suffix, convert it to hexadecimal.
  1272. if '.' in parts[-1]:
  1273. try:
  1274. ipv4_int = IPv4Address(parts.pop())._ip
  1275. except AddressValueError as exc:
  1276. raise AddressValueError("%s in %r" % (exc, ip_str)) from None
  1277. parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
  1278. parts.append('%x' % (ipv4_int & 0xFFFF))
  1279. # An IPv6 address can't have more than 8 colons (9 parts).
  1280. # The extra colon comes from using the "::" notation for a single
  1281. # leading or trailing zero part.
  1282. _max_parts = cls._HEXTET_COUNT + 1
  1283. if len(parts) > _max_parts:
  1284. msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
  1285. raise AddressValueError(msg)
  1286. # Disregarding the endpoints, find '::' with nothing in between.
  1287. # This indicates that a run of zeroes has been skipped.
  1288. skip_index = None
  1289. for i in range(1, len(parts) - 1):
  1290. if not parts[i]:
  1291. if skip_index is not None:
  1292. # Can't have more than one '::'
  1293. msg = "At most one '::' permitted in %r" % ip_str
  1294. raise AddressValueError(msg)
  1295. skip_index = i
  1296. # parts_hi is the number of parts to copy from above/before the '::'
  1297. # parts_lo is the number of parts to copy from below/after the '::'
  1298. if skip_index is not None:
  1299. # If we found a '::', then check if it also covers the endpoints.
  1300. parts_hi = skip_index
  1301. parts_lo = len(parts) - skip_index - 1
  1302. if not parts[0]:
  1303. parts_hi -= 1
  1304. if parts_hi:
  1305. msg = "Leading ':' only permitted as part of '::' in %r"
  1306. raise AddressValueError(msg % ip_str) # ^: requires ^::
  1307. if not parts[-1]:
  1308. parts_lo -= 1
  1309. if parts_lo:
  1310. msg = "Trailing ':' only permitted as part of '::' in %r"
  1311. raise AddressValueError(msg % ip_str) # :$ requires ::$
  1312. parts_skipped = cls._HEXTET_COUNT - (parts_hi + parts_lo)
  1313. if parts_skipped < 1:
  1314. msg = "Expected at most %d other parts with '::' in %r"
  1315. raise AddressValueError(msg % (cls._HEXTET_COUNT-1, ip_str))
  1316. else:
  1317. # Otherwise, allocate the entire address to parts_hi. The
  1318. # endpoints could still be empty, but _parse_hextet() will check
  1319. # for that.
  1320. if len(parts) != cls._HEXTET_COUNT:
  1321. msg = "Exactly %d parts expected without '::' in %r"
  1322. raise AddressValueError(msg % (cls._HEXTET_COUNT, ip_str))
  1323. if not parts[0]:
  1324. msg = "Leading ':' only permitted as part of '::' in %r"
  1325. raise AddressValueError(msg % ip_str) # ^: requires ^::
  1326. if not parts[-1]:
  1327. msg = "Trailing ':' only permitted as part of '::' in %r"
  1328. raise AddressValueError(msg % ip_str) # :$ requires ::$
  1329. parts_hi = len(parts)
  1330. parts_lo = 0
  1331. parts_skipped = 0
  1332. try:
  1333. # Now, parse the hextets into a 128-bit integer.
  1334. ip_int = 0
  1335. for i in range(parts_hi):
  1336. ip_int <<= 16
  1337. ip_int |= cls._parse_hextet(parts[i])
  1338. ip_int <<= 16 * parts_skipped
  1339. for i in range(-parts_lo, 0):
  1340. ip_int <<= 16
  1341. ip_int |= cls._parse_hextet(parts[i])
  1342. return ip_int
  1343. except ValueError as exc:
  1344. raise AddressValueError("%s in %r" % (exc, ip_str)) from None
  1345. @classmethod
  1346. def _parse_hextet(cls, hextet_str):
  1347. """Convert an IPv6 hextet string into an integer.
  1348. Args:
  1349. hextet_str: A string, the number to parse.
  1350. Returns:
  1351. The hextet as an integer.
  1352. Raises:
  1353. ValueError: if the input isn't strictly a hex number from
  1354. [0..FFFF].
  1355. """
  1356. # Reject non-ASCII digits.
  1357. if not cls._HEX_DIGITS.issuperset(hextet_str):
  1358. raise ValueError("Only hex digits permitted in %r" % hextet_str)
  1359. # We do the length check second, since the invalid character error
  1360. # is likely to be more informative for the user
  1361. if len(hextet_str) > 4:
  1362. msg = "At most 4 characters permitted in %r"
  1363. raise ValueError(msg % hextet_str)
  1364. # Length check means we can skip checking the integer value
  1365. return int(hextet_str, 16)
  1366. @classmethod
  1367. def _compress_hextets(cls, hextets):
  1368. """Compresses a list of hextets.
  1369. Compresses a list of strings, replacing the longest continuous
  1370. sequence of "0" in the list with "" and adding empty strings at
  1371. the beginning or at the end of the string such that subsequently
  1372. calling ":".join(hextets) will produce the compressed version of
  1373. the IPv6 address.
  1374. Args:
  1375. hextets: A list of strings, the hextets to compress.
  1376. Returns:
  1377. A list of strings.
  1378. """
  1379. best_doublecolon_start = -1
  1380. best_doublecolon_len = 0
  1381. doublecolon_start = -1
  1382. doublecolon_len = 0
  1383. for index, hextet in enumerate(hextets):
  1384. if hextet == '0':
  1385. doublecolon_len += 1
  1386. if doublecolon_start == -1:
  1387. # Start of a sequence of zeros.
  1388. doublecolon_start = index
  1389. if doublecolon_len > best_doublecolon_len:
  1390. # This is the longest sequence of zeros so far.
  1391. best_doublecolon_len = doublecolon_len
  1392. best_doublecolon_start = doublecolon_start
  1393. else:
  1394. doublecolon_len = 0
  1395. doublecolon_start = -1
  1396. if best_doublecolon_len > 1:
  1397. best_doublecolon_end = (best_doublecolon_start +
  1398. best_doublecolon_len)
  1399. # For zeros at the end of the address.
  1400. if best_doublecolon_end == len(hextets):
  1401. hextets += ['']
  1402. hextets[best_doublecolon_start:best_doublecolon_end] = ['']
  1403. # For zeros at the beginning of the address.
  1404. if best_doublecolon_start == 0:
  1405. hextets = [''] + hextets
  1406. return hextets
  1407. @classmethod
  1408. def _string_from_ip_int(cls, ip_int=None):
  1409. """Turns a 128-bit integer into hexadecimal notation.
  1410. Args:
  1411. ip_int: An integer, the IP address.
  1412. Returns:
  1413. A string, the hexadecimal representation of the address.
  1414. Raises:
  1415. ValueError: The address is bigger than 128 bits of all ones.
  1416. """
  1417. if ip_int is None:
  1418. ip_int = int(cls._ip)
  1419. if ip_int > cls._ALL_ONES:
  1420. raise ValueError('IPv6 address is too large')
  1421. hex_str = '%032x' % ip_int
  1422. hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
  1423. hextets = cls._compress_hextets(hextets)
  1424. return ':'.join(hextets)
  1425. def _explode_shorthand_ip_string(self):
  1426. """Expand a shortened IPv6 address.
  1427. Args:
  1428. ip_str: A string, the IPv6 address.
  1429. Returns:
  1430. A string, the expanded IPv6 address.
  1431. """
  1432. if isinstance(self, IPv6Network):
  1433. ip_str = str(self.network_address)
  1434. elif isinstance(self, IPv6Interface):
  1435. ip_str = str(self.ip)
  1436. else:
  1437. ip_str = str(self)
  1438. ip_int = self._ip_int_from_string(ip_str)
  1439. hex_str = '%032x' % ip_int
  1440. parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
  1441. if isinstance(self, (_BaseNetwork, IPv6Interface)):
  1442. return '%s/%d' % (':'.join(parts), self._prefixlen)
  1443. return ':'.join(parts)
  1444. def _reverse_pointer(self):
  1445. """Return the reverse DNS pointer name for the IPv6 address.
  1446. This implements the method described in RFC3596 2.5.
  1447. """
  1448. reverse_chars = self.exploded[::-1].replace(':', '')
  1449. return '.'.join(reverse_chars) + '.ip6.arpa'
  1450. @staticmethod
  1451. def _split_scope_id(ip_str):
  1452. """Helper function to parse IPv6 string address with scope id.
  1453. See RFC 4007 for details.
  1454. Args:
  1455. ip_str: A string, the IPv6 address.
  1456. Returns:
  1457. (addr, scope_id) tuple.
  1458. """
  1459. addr, sep, scope_id = ip_str.partition('%')
  1460. if not sep:
  1461. scope_id = None
  1462. elif not scope_id or '%' in scope_id:
  1463. raise AddressValueError('Invalid IPv6 address: "%r"' % ip_str)
  1464. return addr, scope_id
  1465. @property
  1466. def max_prefixlen(self):
  1467. return self._max_prefixlen
  1468. @property
  1469. def version(self):
  1470. return self._version
  1471. class IPv6Address(_BaseV6, _BaseAddress):
  1472. """Represent and manipulate single IPv6 Addresses."""
  1473. __slots__ = ('_ip', '_scope_id', '__weakref__')
  1474. def __init__(self, address):
  1475. """Instantiate a new IPv6 address object.
  1476. Args:
  1477. address: A string or integer representing the IP
  1478. Additionally, an integer can be passed, so
  1479. IPv6Address('2001:db8::') ==
  1480. IPv6Address(42540766411282592856903984951653826560)
  1481. or, more generally
  1482. IPv6Address(int(IPv6Address('2001:db8::'))) ==
  1483. IPv6Address('2001:db8::')
  1484. Raises:
  1485. AddressValueError: If address isn't a valid IPv6 address.
  1486. """
  1487. # Efficient constructor from integer.
  1488. if isinstance(address, int):
  1489. self._check_int_address(address)
  1490. self._ip = address
  1491. self._scope_id = None
  1492. return
  1493. # Constructing from a packed address
  1494. if isinstance(address, bytes):
  1495. self._check_packed_address(address, 16)
  1496. self._ip = int.from_bytes(address, 'big')
  1497. self._scope_id = None
  1498. return
  1499. # Assume input argument to be string or any object representation
  1500. # which converts into a formatted IP string.
  1501. addr_str = str(address)
  1502. if '/' in addr_str:
  1503. raise AddressValueError("Unexpected '/' in %r" % address)
  1504. addr_str, self._scope_id = self._split_scope_id(addr_str)
  1505. self._ip = self._ip_int_from_string(addr_str)
  1506. def __str__(self):
  1507. ip_str = super().__str__()
  1508. return ip_str + '%' + self._scope_id if self._scope_id else ip_str
  1509. def __hash__(self):
  1510. return hash((self._ip, self._scope_id))
  1511. def __eq__(self, other):
  1512. address_equal = super().__eq__(other)
  1513. if address_equal is NotImplemented:
  1514. return NotImplemented
  1515. if not address_equal:
  1516. return False
  1517. return self._scope_id == getattr(other, '_scope_id', None)
  1518. @property
  1519. def scope_id(self):
  1520. """Identifier of a particular zone of the address's scope.
  1521. See RFC 4007 for details.
  1522. Returns:
  1523. A string identifying the zone of the address if specified, else None.
  1524. """
  1525. return self._scope_id
  1526. @property
  1527. def packed(self):
  1528. """The binary representation of this address."""
  1529. return v6_int_to_packed(self._ip)
  1530. @property
  1531. def is_multicast(self):
  1532. """Test if the address is reserved for multicast use.
  1533. Returns:
  1534. A boolean, True if the address is a multicast address.
  1535. See RFC 2373 2.7 for details.
  1536. """
  1537. return self in self._constants._multicast_network
  1538. @property
  1539. def is_reserved(self):
  1540. """Test if the address is otherwise IETF reserved.
  1541. Returns:
  1542. A boolean, True if the address is within one of the
  1543. reserved IPv6 Network ranges.
  1544. """
  1545. return any(self in x for x in self._constants._reserved_networks)
  1546. @property
  1547. def is_link_local(self):
  1548. """Test if the address is reserved for link-local.
  1549. Returns:
  1550. A boolean, True if the address is reserved per RFC 4291.
  1551. """
  1552. return self in self._constants._linklocal_network
  1553. @property
  1554. def is_site_local(self):
  1555. """Test if the address is reserved for site-local.
  1556. Note that the site-local address space has been deprecated by RFC 3879.
  1557. Use is_private to test if this address is in the space of unique local
  1558. addresses as defined by RFC 4193.
  1559. Returns:
  1560. A boolean, True if the address is reserved per RFC 3513 2.5.6.
  1561. """
  1562. return self in self._constants._sitelocal_network
  1563. @property
  1564. @functools.lru_cache()
  1565. def is_private(self):
  1566. """Test if this address is allocated for private networks.
  1567. Returns:
  1568. A boolean, True if the address is reserved per
  1569. iana-ipv6-special-registry, or is ipv4_mapped and is
  1570. reserved in the iana-ipv4-special-registry.
  1571. """
  1572. ipv4_mapped = self.ipv4_mapped
  1573. if ipv4_mapped is not None:
  1574. return ipv4_mapped.is_private
  1575. return any(self in net for net in self._constants._private_networks)
  1576. @property
  1577. def is_global(self):
  1578. """Test if this address is allocated for public networks.
  1579. Returns:
  1580. A boolean, true if the address is not reserved per
  1581. iana-ipv6-special-registry.
  1582. """
  1583. return not self.is_private
  1584. @property
  1585. def is_unspecified(self):
  1586. """Test if the address is unspecified.
  1587. Returns:
  1588. A boolean, True if this is the unspecified address as defined in
  1589. RFC 2373 2.5.2.
  1590. """
  1591. return self._ip == 0
  1592. @property
  1593. def is_loopback(self):
  1594. """Test if the address is a loopback address.
  1595. Returns:
  1596. A boolean, True if the address is a loopback address as defined in
  1597. RFC 2373 2.5.3.
  1598. """
  1599. return self._ip == 1
  1600. @property
  1601. def ipv4_mapped(self):
  1602. """Return the IPv4 mapped address.
  1603. Returns:
  1604. If the IPv6 address is a v4 mapped address, return the
  1605. IPv4 mapped address. Return None otherwise.
  1606. """
  1607. if (self._ip >> 32) != 0xFFFF:
  1608. return None
  1609. return IPv4Address(self._ip & 0xFFFFFFFF)
  1610. @property
  1611. def teredo(self):
  1612. """Tuple of embedded teredo IPs.
  1613. Returns:
  1614. Tuple of the (server, client) IPs or None if the address
  1615. doesn't appear to be a teredo address (doesn't start with
  1616. 2001::/32)
  1617. """
  1618. if (self._ip >> 96) != 0x20010000:
  1619. return None
  1620. return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
  1621. IPv4Address(~self._ip & 0xFFFFFFFF))
  1622. @property
  1623. def sixtofour(self):
  1624. """Return the IPv4 6to4 embedded address.
  1625. Returns:
  1626. The IPv4 6to4-embedded address if present or None if the
  1627. address doesn't appear to contain a 6to4 embedded address.
  1628. """
  1629. if (self._ip >> 112) != 0x2002:
  1630. return None
  1631. return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
  1632. class IPv6Interface(IPv6Address):
  1633. def __init__(self, address):
  1634. addr, mask = self._split_addr_prefix(address)
  1635. IPv6Address.__init__(self, addr)
  1636. self.network = IPv6Network((addr, mask), strict=False)
  1637. self.netmask = self.network.netmask
  1638. self._prefixlen = self.network._prefixlen
  1639. @functools.cached_property
  1640. def hostmask(self):
  1641. return self.network.hostmask
  1642. def __str__(self):
  1643. return '%s/%d' % (super().__str__(),
  1644. self._prefixlen)
  1645. def __eq__(self, other):
  1646. address_equal = IPv6Address.__eq__(self, other)
  1647. if address_equal is NotImplemented or not address_equal:
  1648. return address_equal
  1649. try:
  1650. return self.network == other.network
  1651. except AttributeError:
  1652. # An interface with an associated network is NOT the
  1653. # same as an unassociated address. That's why the hash
  1654. # takes the extra info into account.
  1655. return False
  1656. def __lt__(self, other):
  1657. address_less = IPv6Address.__lt__(self, other)
  1658. if address_less is NotImplemented:
  1659. return address_less
  1660. try:
  1661. return (self.network < other.network or
  1662. self.network == other.network and address_less)
  1663. except AttributeError:
  1664. # We *do* allow addresses and interfaces to be sorted. The
  1665. # unassociated address is considered less than all interfaces.
  1666. return False
  1667. def __hash__(self):
  1668. return hash((self._ip, self._prefixlen, int(self.network.network_address)))
  1669. __reduce__ = _IPAddressBase.__reduce__
  1670. @property
  1671. def ip(self):
  1672. return IPv6Address(self._ip)
  1673. @property
  1674. def with_prefixlen(self):
  1675. return '%s/%s' % (self._string_from_ip_int(self._ip),
  1676. self._prefixlen)
  1677. @property
  1678. def with_netmask(self):
  1679. return '%s/%s' % (self._string_from_ip_int(self._ip),
  1680. self.netmask)
  1681. @property
  1682. def with_hostmask(self):
  1683. return '%s/%s' % (self._string_from_ip_int(self._ip),
  1684. self.hostmask)
  1685. @property
  1686. def is_unspecified(self):
  1687. return self._ip == 0 and self.network.is_unspecified
  1688. @property
  1689. def is_loopback(self):
  1690. return self._ip == 1 and self.network.is_loopback
  1691. class IPv6Network(_BaseV6, _BaseNetwork):
  1692. """This class represents and manipulates 128-bit IPv6 networks.
  1693. Attributes: [examples for IPv6('2001:db8::1000/124')]
  1694. .network_address: IPv6Address('2001:db8::1000')
  1695. .hostmask: IPv6Address('::f')
  1696. .broadcast_address: IPv6Address('2001:db8::100f')
  1697. .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
  1698. .prefixlen: 124
  1699. """
  1700. # Class to use when creating address objects
  1701. _address_class = IPv6Address
  1702. def __init__(self, address, strict=True):
  1703. """Instantiate a new IPv6 Network object.
  1704. Args:
  1705. address: A string or integer representing the IPv6 network or the
  1706. IP and prefix/netmask.
  1707. '2001:db8::/128'
  1708. '2001:db8:0000:0000:0000:0000:0000:0000/128'
  1709. '2001:db8::'
  1710. are all functionally the same in IPv6. That is to say,
  1711. failing to provide a subnetmask will create an object with
  1712. a mask of /128.
  1713. Additionally, an integer can be passed, so
  1714. IPv6Network('2001:db8::') ==
  1715. IPv6Network(42540766411282592856903984951653826560)
  1716. or, more generally
  1717. IPv6Network(int(IPv6Network('2001:db8::'))) ==
  1718. IPv6Network('2001:db8::')
  1719. strict: A boolean. If true, ensure that we have been passed
  1720. A true network address, eg, 2001:db8::1000/124 and not an
  1721. IP address on a network, eg, 2001:db8::1/124.
  1722. Raises:
  1723. AddressValueError: If address isn't a valid IPv6 address.
  1724. NetmaskValueError: If the netmask isn't valid for
  1725. an IPv6 address.
  1726. ValueError: If strict was True and a network address was not
  1727. supplied.
  1728. """
  1729. addr, mask = self._split_addr_prefix(address)
  1730. self.network_address = IPv6Address(addr)
  1731. self.netmask, self._prefixlen = self._make_netmask(mask)
  1732. packed = int(self.network_address)
  1733. if packed & int(self.netmask) != packed:
  1734. if strict:
  1735. raise ValueError('%s has host bits set' % self)
  1736. else:
  1737. self.network_address = IPv6Address(packed &
  1738. int(self.netmask))
  1739. if self._prefixlen == (self._max_prefixlen - 1):
  1740. self.hosts = self.__iter__
  1741. elif self._prefixlen == self._max_prefixlen:
  1742. self.hosts = lambda: [IPv6Address(addr)]
  1743. def hosts(self):
  1744. """Generate Iterator over usable hosts in a network.
  1745. This is like __iter__ except it doesn't return the
  1746. Subnet-Router anycast address.
  1747. """
  1748. network = int(self.network_address)
  1749. broadcast = int(self.broadcast_address)
  1750. for x in range(network + 1, broadcast + 1):
  1751. yield self._address_class(x)
  1752. @property
  1753. def is_site_local(self):
  1754. """Test if the address is reserved for site-local.
  1755. Note that the site-local address space has been deprecated by RFC 3879.
  1756. Use is_private to test if this address is in the space of unique local
  1757. addresses as defined by RFC 4193.
  1758. Returns:
  1759. A boolean, True if the address is reserved per RFC 3513 2.5.6.
  1760. """
  1761. return (self.network_address.is_site_local and
  1762. self.broadcast_address.is_site_local)
  1763. class _IPv6Constants:
  1764. _linklocal_network = IPv6Network('fe80::/10')
  1765. _multicast_network = IPv6Network('ff00::/8')
  1766. _private_networks = [
  1767. IPv6Network('::1/128'),
  1768. IPv6Network('::/128'),
  1769. IPv6Network('::ffff:0:0/96'),
  1770. IPv6Network('100::/64'),
  1771. IPv6Network('2001::/23'),
  1772. IPv6Network('2001:2::/48'),
  1773. IPv6Network('2001:db8::/32'),
  1774. IPv6Network('2001:10::/28'),
  1775. IPv6Network('fc00::/7'),
  1776. IPv6Network('fe80::/10'),
  1777. ]
  1778. _reserved_networks = [
  1779. IPv6Network('::/8'), IPv6Network('100::/8'),
  1780. IPv6Network('200::/7'), IPv6Network('400::/6'),
  1781. IPv6Network('800::/5'), IPv6Network('1000::/4'),
  1782. IPv6Network('4000::/3'), IPv6Network('6000::/3'),
  1783. IPv6Network('8000::/3'), IPv6Network('A000::/3'),
  1784. IPv6Network('C000::/3'), IPv6Network('E000::/4'),
  1785. IPv6Network('F000::/5'), IPv6Network('F800::/6'),
  1786. IPv6Network('FE00::/9'),
  1787. ]
  1788. _sitelocal_network = IPv6Network('fec0::/10')
  1789. IPv6Address._constants = _IPv6Constants