Debian Codegraph @

lib-python/3/ipaddress.py

raw symbols SCIP
1 # Copyright 2007 Google Inc.
2 # Licensed to PSF under a Contributor Agreement.
3
4 """A fast, lightweight IPv4/IPv6 manipulation library in Python.
5
6 This library is used to create/poke/manipulate IPv4 and IPv6 addresses
7 and networks.
8
9 """
10
11 __version__ = '1.0'
12
13
14 import functools
15
16 IPV4LENGTH = 32
17 IPV6LENGTH = 128
18
19
20 class AddressValueError(ValueError):
21 """A Value Error related to the address."""
22
23
24 class NetmaskValueError(ValueError):
25 """A Value Error related to the netmask."""
26
27
28 def ip_address(address):
29 """Take an IP string/int and return an object of the correct type.
30
31 Args:
32 address: A string or integer, the IP address. Either IPv4 or
33 IPv6 addresses may be supplied; integers less than 2**32 will
34 be considered to be IPv4 by default.
35
36 Returns:
37 An IPv4Address or IPv6Address object.
38
39 Raises:
40 ValueError: if the *address* passed isn't either a v4 or a v6
41 address
42
43 """
44 try:
45 return IPv4Address(address)
46 except (AddressValueError, NetmaskValueError):
47 pass
48
49 try:
50 return IPv6Address(address)
51 except (AddressValueError, NetmaskValueError):
52 pass
53
54 raise ValueError(f'{address!r} does not appear to be an IPv4 or IPv6 address')
55
56
57 def ip_network(address, strict=True):
58 """Take an IP string/int and return an object of the correct type.
59
60 Args:
61 address: A string or integer, the IP network. Either IPv4 or
62 IPv6 networks may be supplied; integers less than 2**32 will
63 be considered to be IPv4 by default.
64
65 Returns:
66 An IPv4Network or IPv6Network object.
67
68 Raises:
69 ValueError: if the string passed isn't either a v4 or a v6
70 address. Or if the network has host bits set.
71
72 """
73 try:
74 return IPv4Network(address, strict)
75 except (AddressValueError, NetmaskValueError):
76 pass
77
78 try:
79 return IPv6Network(address, strict)
80 except (AddressValueError, NetmaskValueError):
81 pass
82
83 raise ValueError(f'{address!r} does not appear to be an IPv4 or IPv6 network')
84
85
86 def ip_interface(address):
87 """Take an IP string/int and return an object of the correct type.
88
89 Args:
90 address: A string or integer, the IP address. Either IPv4 or
91 IPv6 addresses may be supplied; integers less than 2**32 will
92 be considered to be IPv4 by default.
93
94 Returns:
95 An IPv4Interface or IPv6Interface object.
96
97 Raises:
98 ValueError: if the string passed isn't either a v4 or a v6
99 address.
100
101 Notes:
102 The IPv?Interface classes describe an Address on a particular
103 Network, so they're basically a combination of both the Address
104 and Network classes.
105
106 """
107 try:
108 return IPv4Interface(address)
109 except (AddressValueError, NetmaskValueError):
110 pass
111
112 try:
113 return IPv6Interface(address)
114 except (AddressValueError, NetmaskValueError):
115 pass
116
117 raise ValueError(f'{address!r} does not appear to be an IPv4 or IPv6 interface')
118
119
120 def v4_int_to_packed(address):
121 """Represent an address as 4 packed bytes in network (big-endian) order.
122
123 Args:
124 address: An integer representation of an IPv4 IP address.
125
126 Returns:
127 The integer address packed as 4 bytes in network (big-endian) order.
128
129 Raises:
130 ValueError: If the integer is negative or too large to be an
131 IPv4 IP address.
132
133 """
134 try:
135 return address.to_bytes(4) # big endian
136 except OverflowError:
137 raise ValueError("Address negative or too large for IPv4")
138
139
140 def v6_int_to_packed(address):
141 """Represent an address as 16 packed bytes in network (big-endian) order.
142
143 Args:
144 address: An integer representation of an IPv6 IP address.
145
146 Returns:
147 The integer address packed as 16 bytes in network (big-endian) order.
148
149 """
150 try:
151 return address.to_bytes(16) # big endian
152 except OverflowError:
153 raise ValueError("Address negative or too large for IPv6")
154
155
156 def _split_optional_netmask(address):
157 """Helper to split the netmask and raise AddressValueError if needed"""
158 addr = str(address).split('/')
159 if len(addr) > 2:
160 raise AddressValueError(f"Only one '/' permitted in {address!r}")
161 return addr
162
163
164 def _find_address_range(addresses):
165 """Find a sequence of sorted deduplicated IPv#Address.
166
167 Args:
168 addresses: a list of IPv#Address objects.
169
170 Yields:
171 A tuple containing the first and last IP addresses in the sequence.
172
173 """
174 it = iter(addresses)
175 first = last = next(it)
176 for ip in it:
177 if ip._ip != last._ip + 1:
178 yield first, last
179 first = ip
180 last = ip
181 yield first, last
182
183
184 def _count_righthand_zero_bits(number, bits):
185 """Count the number of zero bits on the right hand side.
186
187 Args:
188 number: an integer.
189 bits: maximum number of bits to count.
190
191 Returns:
192 The number of zero bits on the right hand side of the number.
193
194 """
195 if number == 0:
196 return bits
197 return min(bits, (~number & (number-1)).bit_length())
198
199
200 def summarize_address_range(first, last):
201 """Summarize a network range given the first and last IP addresses.
202
203 Example:
204 >>> list(summarize_address_range(IPv4Address('192.0.2.0'),
205 ... IPv4Address('192.0.2.130')))
206 ... #doctest: +NORMALIZE_WHITESPACE
207 [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'),
208 IPv4Network('192.0.2.130/32')]
209
210 Args:
211 first: the first IPv4Address or IPv6Address in the range.
212 last: the last IPv4Address or IPv6Address in the range.
213
214 Returns:
215 An iterator of the summarized IPv(4|6) network objects.
216
217 Raise:
218 TypeError:
219 If the first and last objects are not IP addresses.
220 If the first and last objects are not the same version.
221 ValueError:
222 If the last object is not greater than the first.
223 If the version of the first address is not 4 or 6.
224
225 """
226 if (not (isinstance(first, _BaseAddress) and
227 isinstance(last, _BaseAddress))):
228 raise TypeError('first and last must be IP addresses, not networks')
229 if first.version != last.version:
230 raise TypeError("%s and %s are not of the same version" % (
231 first, last))
232 if first > last:
233 raise ValueError('last IP address must be greater than first')
234
235 if first.version == 4:
236 ip = IPv4Network
237 elif first.version == 6:
238 ip = IPv6Network
239 else:
240 raise ValueError('unknown IP version')
241
242 ip_bits = first._max_prefixlen
243 first_int = first._ip
244 last_int = last._ip
245 while first_int <= last_int:
246 nbits = min(_count_righthand_zero_bits(first_int, ip_bits),
247 (last_int - first_int + 1).bit_length() - 1)
248 net = ip((first_int, ip_bits - nbits))
249 yield net
250 first_int += 1 << nbits
251 if first_int - 1 == ip._ALL_ONES:
252 break
253
254
255 def _collapse_addresses_internal(addresses):
256 """Loops through the addresses, collapsing concurrent netblocks.
257
258 Example:
259
260 ip1 = IPv4Network('192.0.2.0/26')
261 ip2 = IPv4Network('192.0.2.64/26')
262 ip3 = IPv4Network('192.0.2.128/26')
263 ip4 = IPv4Network('192.0.2.192/26')
264
265 _collapse_addresses_internal([ip1, ip2, ip3, ip4]) ->
266 [IPv4Network('192.0.2.0/24')]
267
268 This shouldn't be called directly; it is called via
269 collapse_addresses([]).
270
271 Args:
272 addresses: A list of IPv4Network's or IPv6Network's
273
274 Returns:
275 A list of IPv4Network's or IPv6Network's depending on what we were
276 passed.
277
278 """
279 # First merge
280 to_merge = list(addresses)
281 subnets = {}
282 while to_merge:
283 net = to_merge.pop()
284 supernet = net.supernet()
285 existing = subnets.get(supernet)
286 if existing is None:
287 subnets[supernet] = net
288 elif existing != net:
289 # Merge consecutive subnets
290 del subnets[supernet]
291 to_merge.append(supernet)
292 # Then iterate over resulting networks, skipping subsumed subnets
293 last = None
294 for net in sorted(subnets.values()):
295 if last is not None:
296 # Since they are sorted, last.network_address <= net.network_address
297 # is a given.
298 if last.broadcast_address >= net.broadcast_address:
299 continue
300 yield net
301 last = net
302
303
304 def collapse_addresses(addresses):
305 """Collapse a list of IP objects.
306
307 Example:
308 collapse_addresses([IPv4Network('192.0.2.0/25'),
309 IPv4Network('192.0.2.128/25')]) ->
310 [IPv4Network('192.0.2.0/24')]
311
312 Args:
313 addresses: An iterable of IPv4Network or IPv6Network objects.
314
315 Returns:
316 An iterator of the collapsed IPv(4|6)Network objects.
317
318 Raises:
319 TypeError: If passed a list of mixed version objects.
320
321 """
322 addrs = []
323 ips = []
324 nets = []
325
326 # split IP addresses and networks
327 for ip in addresses:
328 if isinstance(ip, _BaseAddress):
329 if ips and ips[-1]._version != ip._version:
330 raise TypeError("%s and %s are not of the same version" % (
331 ip, ips[-1]))
332 ips.append(ip)
333 elif ip._prefixlen == ip._max_prefixlen:
334 if ips and ips[-1]._version != ip._version:
335 raise TypeError("%s and %s are not of the same version" % (
336 ip, ips[-1]))
337 try:
338 ips.append(ip.ip)
339 except AttributeError:
340 ips.append(ip.network_address)
341 else:
342 if nets and nets[-1]._version != ip._version:
343 raise TypeError("%s and %s are not of the same version" % (
344 ip, nets[-1]))
345 nets.append(ip)
346
347 # sort and dedup
348 ips = sorted(set(ips))
349
350 # find consecutive address ranges in the sorted sequence and summarize them
351 if ips:
352 for first, last in _find_address_range(ips):
353 addrs.extend(summarize_address_range(first, last))
354
355 return _collapse_addresses_internal(addrs + nets)
356
357
358 def get_mixed_type_key(obj):
359 """Return a key suitable for sorting between networks and addresses.
360
361 Address and Network objects are not sortable by default; they're
362 fundamentally different so the expression
363
364 IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
365
366 doesn't make any sense. There are some times however, where you may wish
367 to have ipaddress sort these for you anyway. If you need to do this, you
368 can use this function as the key= argument to sorted().
369
370 Args:
371 obj: either a Network or Address object.
372 Returns:
373 appropriate key.
374
375 """
376 if isinstance(obj, _BaseNetwork):
377 return obj._get_networks_key()
378 elif isinstance(obj, _BaseAddress):
379 return obj._get_address_key()
380 return NotImplemented
381
382
383 class _IPAddressBase:
384
385 """The mother class."""
386
387 __slots__ = ()
388
389 @property
390 def exploded(self):
391 """Return the longhand version of the IP address as a string."""
392 return self._explode_shorthand_ip_string()
393
394 @property
395 def compressed(self):
396 """Return the shorthand version of the IP address as a string."""
397 return str(self)
398
399 @property
400 def reverse_pointer(self):
401 """The name of the reverse DNS pointer for the IP address, e.g.:
402 >>> ipaddress.ip_address("127.0.0.1").reverse_pointer
403 '1.0.0.127.in-addr.arpa'
404 >>> ipaddress.ip_address("2001:db8::1").reverse_pointer
405 '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'
406
407 """
408 return self._reverse_pointer()
409
410 @property
411 def version(self):
412 msg = '%200s has no version specified' % (type(self),)
413 raise NotImplementedError(msg)
414
415 def _check_int_address(self, address):
416 if address < 0:
417 msg = "%d (< 0) is not permitted as an IPv%d address"
418 raise AddressValueError(msg % (address, self._version))
419 if address > self._ALL_ONES:
420 msg = "%d (>= 2**%d) is not permitted as an IPv%d address"
421 raise AddressValueError(msg % (address, self._max_prefixlen,
422 self._version))
423
424 def _check_packed_address(self, address, expected_len):
425 address_len = len(address)
426 if address_len != expected_len:
427 msg = "%r (len %d != %d) is not permitted as an IPv%d address"
428 raise AddressValueError(msg % (address, address_len,
429 expected_len, self._version))
430
431 @classmethod
432 def _ip_int_from_prefix(cls, prefixlen):
433 """Turn the prefix length into a bitwise netmask
434
435 Args:
436 prefixlen: An integer, the prefix length.
437
438 Returns:
439 An integer.
440
441 """
442 return cls._ALL_ONES ^ (cls._ALL_ONES >> prefixlen)
443
444 @classmethod
445 def _prefix_from_ip_int(cls, ip_int):
446 """Return prefix length from the bitwise netmask.
447
448 Args:
449 ip_int: An integer, the netmask in expanded bitwise format
450
451 Returns:
452 An integer, the prefix length.
453
454 Raises:
455 ValueError: If the input intermingles zeroes & ones
456 """
457 trailing_zeroes = _count_righthand_zero_bits(ip_int,
458 cls._max_prefixlen)
459 prefixlen = cls._max_prefixlen - trailing_zeroes
460 leading_ones = ip_int >> trailing_zeroes
461 all_ones = (1 << prefixlen) - 1
462 if leading_ones != all_ones:
463 byteslen = cls._max_prefixlen // 8
464 details = ip_int.to_bytes(byteslen, 'big')
465 msg = 'Netmask pattern %r mixes zeroes & ones'
466 raise ValueError(msg % details)
467 return prefixlen
468
469 @classmethod
470 def _report_invalid_netmask(cls, netmask_str):
471 msg = '%r is not a valid netmask' % netmask_str
472 raise NetmaskValueError(msg) from None
473
474 @classmethod
475 def _prefix_from_prefix_string(cls, prefixlen_str):
476 """Return prefix length from a numeric string
477
478 Args:
479 prefixlen_str: The string to be converted
480
481 Returns:
482 An integer, the prefix length.
483
484 Raises:
485 NetmaskValueError: If the input is not a valid netmask
486 """
487 # int allows a leading +/- as well as surrounding whitespace,
488 # so we ensure that isn't the case
489 if not (prefixlen_str.isascii() and prefixlen_str.isdigit()):
490 cls._report_invalid_netmask(prefixlen_str)
491 try:
492 prefixlen = int(prefixlen_str)
493 except ValueError:
494 cls._report_invalid_netmask(prefixlen_str)
495 if not (0 <= prefixlen <= cls._max_prefixlen):
496 cls._report_invalid_netmask(prefixlen_str)
497 return prefixlen
498
499 @classmethod
500 def _prefix_from_ip_string(cls, ip_str):
501 """Turn a netmask/hostmask string into a prefix length
502
503 Args:
504 ip_str: The netmask/hostmask to be converted
505
506 Returns:
507 An integer, the prefix length.
508
509 Raises:
510 NetmaskValueError: If the input is not a valid netmask/hostmask
511 """
512 # Parse the netmask/hostmask like an IP address.
513 try:
514 ip_int = cls._ip_int_from_string(ip_str)
515 except AddressValueError:
516 cls._report_invalid_netmask(ip_str)
517
518 # Try matching a netmask (this would be /1*0*/ as a bitwise regexp).
519 # Note that the two ambiguous cases (all-ones and all-zeroes) are
520 # treated as netmasks.
521 try:
522 return cls._prefix_from_ip_int(ip_int)
523 except ValueError:
524 pass
525
526 # Invert the bits, and try matching a /0+1+/ hostmask instead.
527 ip_int ^= cls._ALL_ONES
528 try:
529 return cls._prefix_from_ip_int(ip_int)
530 except ValueError:
531 cls._report_invalid_netmask(ip_str)
532
533 @classmethod
534 def _split_addr_prefix(cls, address):
535 """Helper function to parse address of Network/Interface.
536
537 Arg:
538 address: Argument of Network/Interface.
539
540 Returns:
541 (addr, prefix) tuple.
542 """
543 # a packed address or integer
544 if isinstance(address, (bytes, int)):
545 return address, cls._max_prefixlen
546
547 if not isinstance(address, tuple):
548 # Assume input argument to be string or any object representation
549 # which converts into a formatted IP prefix string.
550 address = _split_optional_netmask(address)
551
552 # Constructing from a tuple (addr, [mask])
553 if len(address) > 1:
554 return address
555 return address[0], cls._max_prefixlen
556
557 def __reduce__(self):
558 return self.__class__, (str(self),)
559
560
561 _address_fmt_re = None
562
563 @functools.total_ordering
564 class _BaseAddress(_IPAddressBase):
565
566 """A generic IP object.
567
568 This IP class contains the version independent methods which are
569 used by single IP addresses.
570 """
571
572 __slots__ = ()
573
574 def __int__(self):
575 return self._ip
576
577 def __eq__(self, other):
578 try:
579 return (self._ip == other._ip
580 and self._version == other._version)
581 except AttributeError:
582 return NotImplemented
583
584 def __lt__(self, other):
585 if not isinstance(other, _BaseAddress):
586 return NotImplemented
587 if self._version != other._version:
588 raise TypeError('%s and %s are not of the same version' % (
589 self, other))
590 if self._ip != other._ip:
591 return self._ip < other._ip
592 return False
593
594 # Shorthand for Integer addition and subtraction. This is not
595 # meant to ever support addition/subtraction of addresses.
596 def __add__(self, other):
597 if not isinstance(other, int):
598 return NotImplemented
599 return self.__class__(int(self) + other)
600
601 def __sub__(self, other):
602 if not isinstance(other, int):
603 return NotImplemented
604 return self.__class__(int(self) - other)
605
606 def __repr__(self):
607 return '%s(%r)' % (self.__class__.__name__, str(self))
608
609 def __str__(self):
610 return str(self._string_from_ip_int(self._ip))
611
612 def __hash__(self):
613 return hash(hex(int(self._ip)))
614
615 def _get_address_key(self):
616 return (self._version, self)
617
618 def __reduce__(self):
619 return self.__class__, (self._ip,)
620
621 def __format__(self, fmt):
622 """Returns an IP address as a formatted string.
623
624 Supported presentation types are:
625 's': returns the IP address as a string (default)
626 'b': converts to binary and returns a zero-padded string
627 'X' or 'x': converts to upper- or lower-case hex and returns a zero-padded string
628 'n': the same as 'b' for IPv4 and 'x' for IPv6
629
630 For binary and hex presentation types, the alternate form specifier
631 '#' and the grouping option '_' are supported.
632 """
633
634 # Support string formatting
635 if not fmt or fmt[-1] == 's':
636 return format(str(self), fmt)
637
638 # From here on down, support for 'bnXx'
639 global _address_fmt_re
640 if _address_fmt_re is None:
641 import re
642 _address_fmt_re = re.compile('(#?)(_?)([xbnX])')
643
644 m = _address_fmt_re.fullmatch(fmt)
645 if not m:
646 return super().__format__(fmt)
647
648 alternate, grouping, fmt_base = m.groups()
649
650 # Set some defaults
651 if fmt_base == 'n':
652 if self._version == 4:
653 fmt_base = 'b' # Binary is default for ipv4
654 else:
655 fmt_base = 'x' # Hex is default for ipv6
656
657 if fmt_base == 'b':
658 padlen = self._max_prefixlen
659 else:
660 padlen = self._max_prefixlen // 4
661
662 if grouping:
663 padlen += padlen // 4 - 1
664
665 if alternate:
666 padlen += 2 # 0b or 0x
667
668 return format(int(self), f'{alternate}0{padlen}{grouping}{fmt_base}')
669
670
671 @functools.total_ordering
672 class _BaseNetwork(_IPAddressBase):
673 """A generic IP network object.
674
675 This IP class contains the version independent methods which are
676 used by networks.
677 """
678
679 def __repr__(self):
680 return '%s(%r)' % (self.__class__.__name__, str(self))
681
682 def __str__(self):
683 return '%s/%d' % (self.network_address, self.prefixlen)
684
685 def hosts(self):
686 """Generate Iterator over usable hosts in a network.
687
688 This is like __iter__ except it doesn't return the network
689 or broadcast addresses.
690
691 """
692 network = int(self.network_address)
693 broadcast = int(self.broadcast_address)
694 for x in range(network + 1, broadcast):
695 yield self._address_class(x)
696
697 def __iter__(self):
698 network = int(self.network_address)
699 broadcast = int(self.broadcast_address)
700 for x in range(network, broadcast + 1):
701 yield self._address_class(x)
702
703 def __getitem__(self, n):
704 network = int(self.network_address)
705 broadcast = int(self.broadcast_address)
706 if n >= 0:
707 if network + n > broadcast:
708 raise IndexError('address out of range')
709 return self._address_class(network + n)
710 else:
711 n += 1
712 if broadcast + n < network:
713 raise IndexError('address out of range')
714 return self._address_class(broadcast + n)
715
716 def __lt__(self, other):
717 if not isinstance(other, _BaseNetwork):
718 return NotImplemented
719 if self._version != other._version:
720 raise TypeError('%s and %s are not of the same version' % (
721 self, other))
722 if self.network_address != other.network_address:
723 return self.network_address < other.network_address
724 if self.netmask != other.netmask:
725 return self.netmask < other.netmask
726 return False
727
728 def __eq__(self, other):
729 try:
730 return (self._version == other._version and
731 self.network_address == other.network_address and
732 int(self.netmask) == int(other.netmask))
733 except AttributeError:
734 return NotImplemented
735
736 def __hash__(self):
737 return hash((int(self.network_address), int(self.netmask)))
738
739 def __contains__(self, other):
740 # always false if one is v4 and the other is v6.
741 if self._version != other._version:
742 return False
743 # dealing with another network.
744 if isinstance(other, _BaseNetwork):
745 return False
746 # dealing with another address
747 else:
748 # address
749 return other._ip & self.netmask._ip == self.network_address._ip
750
751 def overlaps(self, other):
752 """Tell if self is partly contained in other."""
753 return self.network_address in other or (
754 self.broadcast_address in other or (
755 other.network_address in self or (
756 other.broadcast_address in self)))
757
758 @functools.cached_property
759 def broadcast_address(self):
760 return self._address_class(int(self.network_address) |
761 int(self.hostmask))
762
763 @functools.cached_property
764 def hostmask(self):
765 return self._address_class(int(self.netmask) ^ self._ALL_ONES)
766
767 @property
768 def with_prefixlen(self):
769 return '%s/%d' % (self.network_address, self._prefixlen)
770
771 @property
772 def with_netmask(self):
773 return '%s/%s' % (self.network_address, self.netmask)
774
775 @property
776 def with_hostmask(self):
777 return '%s/%s' % (self.network_address, self.hostmask)
778
779 @property
780 def num_addresses(self):
781 """Number of hosts in the current subnet."""
782 return int(self.broadcast_address) - int(self.network_address) + 1
783
784 @property
785 def _address_class(self):
786 # Returning bare address objects (rather than interfaces) allows for
787 # more consistent behaviour across the network address, broadcast
788 # address and individual host addresses.
789 msg = '%200s has no associated address class' % (type(self),)
790 raise NotImplementedError(msg)
791
792 @property
793 def prefixlen(self):
794 return self._prefixlen
795
796 def address_exclude(self, other):
797 """Remove an address from a larger block.
798
799 For example:
800
801 addr1 = ip_network('192.0.2.0/28')
802 addr2 = ip_network('192.0.2.1/32')
803 list(addr1.address_exclude(addr2)) =
804 [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
805 IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
806
807 or IPv6:
808
809 addr1 = ip_network('2001:db8::1/32')
810 addr2 = ip_network('2001:db8::1/128')
811 list(addr1.address_exclude(addr2)) =
812 [ip_network('2001:db8::1/128'),
813 ip_network('2001:db8::2/127'),
814 ip_network('2001:db8::4/126'),
815 ip_network('2001:db8::8/125'),
816 ...
817 ip_network('2001:db8:8000::/33')]
818
819 Args:
820 other: An IPv4Network or IPv6Network object of the same type.
821
822 Returns:
823 An iterator of the IPv(4|6)Network objects which is self
824 minus other.
825
826 Raises:
827 TypeError: If self and other are of differing address
828 versions, or if other is not a network object.
829 ValueError: If other is not completely contained by self.
830
831 """
832 if not self._version == other._version:
833 raise TypeError("%s and %s are not of the same version" % (
834 self, other))
835
836 if not isinstance(other, _BaseNetwork):
837 raise TypeError("%s is not a network object" % other)
838
839 if not other.subnet_of(self):
840 raise ValueError('%s not contained in %s' % (other, self))
841 if other == self:
842 return
843
844 # Make sure we're comparing the network of other.
845 other = other.__class__('%s/%s' % (other.network_address,
846 other.prefixlen))
847
848 s1, s2 = self.subnets()
849 while s1 != other and s2 != other:
850 if other.subnet_of(s1):
851 yield s2
852 s1, s2 = s1.subnets()
853 elif other.subnet_of(s2):
854 yield s1
855 s1, s2 = s2.subnets()
856 else:
857 # If we got here, there's a bug somewhere.
858 raise AssertionError('Error performing exclusion: '
859 's1: %s s2: %s other: %s' %
860 (s1, s2, other))
861 if s1 == other:
862 yield s2
863 elif s2 == other:
864 yield s1
865 else:
866 # If we got here, there's a bug somewhere.
867 raise AssertionError('Error performing exclusion: '
868 's1: %s s2: %s other: %s' %
869 (s1, s2, other))
870
871 def compare_networks(self, other):
872 """Compare two IP objects.
873
874 This is only concerned about the comparison of the integer
875 representation of the network addresses. This means that the
876 host bits aren't considered at all in this method. If you want
877 to compare host bits, you can easily enough do a
878 'HostA._ip < HostB._ip'
879
880 Args:
881 other: An IP object.
882
883 Returns:
884 If the IP versions of self and other are the same, returns:
885
886 -1 if self < other:
887 eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
888 IPv6Network('2001:db8::1000/124') <
889 IPv6Network('2001:db8::2000/124')
890 0 if self == other
891 eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
892 IPv6Network('2001:db8::1000/124') ==
893 IPv6Network('2001:db8::1000/124')
894 1 if self > other
895 eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
896 IPv6Network('2001:db8::2000/124') >
897 IPv6Network('2001:db8::1000/124')
898
899 Raises:
900 TypeError if the IP versions are different.
901
902 """
903 # does this need to raise a ValueError?
904 if self._version != other._version:
905 raise TypeError('%s and %s are not of the same type' % (
906 self, other))
907 # self._version == other._version below here:
908 if self.network_address < other.network_address:
909 return -1
910 if self.network_address > other.network_address:
911 return 1
912 # self.network_address == other.network_address below here:
913 if self.netmask < other.netmask:
914 return -1
915 if self.netmask > other.netmask:
916 return 1
917 return 0
918
919 def _get_networks_key(self):
920 """Network-only key function.
921
922 Returns an object that identifies this address' network and
923 netmask. This function is a suitable "key" argument for sorted()
924 and list.sort().
925
926 """
927 return (self._version, self.network_address, self.netmask)
928
929 def subnets(self, prefixlen_diff=1, new_prefix=None):
930 """The subnets which join to make the current subnet.
931
932 In the case that self contains only one IP
933 (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
934 for IPv6), yield an iterator with just ourself.
935
936 Args:
937 prefixlen_diff: An integer, the amount the prefix length
938 should be increased by. This should not be set if
939 new_prefix is also set.
940 new_prefix: The desired new prefix length. This must be a
941 larger number (smaller prefix) than the existing prefix.
942 This should not be set if prefixlen_diff is also set.
943
944 Returns:
945 An iterator of IPv(4|6) objects.
946
947 Raises:
948 ValueError: The prefixlen_diff is too small or too large.
949 OR
950 prefixlen_diff and new_prefix are both set or new_prefix
951 is a smaller number than the current prefix (smaller
952 number means a larger network)
953
954 """
955 if self._prefixlen == self._max_prefixlen:
956 yield self
957 return
958
959 if new_prefix is not None:
960 if new_prefix < self._prefixlen:
961 raise ValueError('new prefix must be longer')
962 if prefixlen_diff != 1:
963 raise ValueError('cannot set prefixlen_diff and new_prefix')
964 prefixlen_diff = new_prefix - self._prefixlen
965
966 if prefixlen_diff < 0:
967 raise ValueError('prefix length diff must be > 0')
968 new_prefixlen = self._prefixlen + prefixlen_diff
969
970 if new_prefixlen > self._max_prefixlen:
971 raise ValueError(
972 'prefix length diff %d is invalid for netblock %s' % (
973 new_prefixlen, self))
974
975 start = int(self.network_address)
976 end = int(self.broadcast_address) + 1
977 step = (int(self.hostmask) + 1) >> prefixlen_diff
978 for new_addr in range(start, end, step):
979 current = self.__class__((new_addr, new_prefixlen))
980 yield current
981
982 def supernet(self, prefixlen_diff=1, new_prefix=None):
983 """The supernet containing the current network.
984
985 Args:
986 prefixlen_diff: An integer, the amount the prefix length of
987 the network should be decreased by. For example, given a
988 /24 network and a prefixlen_diff of 3, a supernet with a
989 /21 netmask is returned.
990
991 Returns:
992 An IPv4 network object.
993
994 Raises:
995 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
996 a negative prefix length.
997 OR
998 If prefixlen_diff and new_prefix are both set or new_prefix is a
999 larger number than the current prefix (larger number means a
1000 smaller network)
1001
1002 """
1003 if self._prefixlen == 0:
1004 return self
1005
1006 if new_prefix is not None:
1007 if new_prefix > self._prefixlen:
1008 raise ValueError('new prefix must be shorter')
1009 if prefixlen_diff != 1:
1010 raise ValueError('cannot set prefixlen_diff and new_prefix')
1011 prefixlen_diff = self._prefixlen - new_prefix
1012
1013 new_prefixlen = self.prefixlen - prefixlen_diff
1014 if new_prefixlen < 0:
1015 raise ValueError(
1016 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
1017 (self.prefixlen, prefixlen_diff))
1018 return self.__class__((
1019 int(self.network_address) & (int(self.netmask) << prefixlen_diff),
1020 new_prefixlen
1021 ))
1022
1023 @property
1024 def is_multicast(self):
1025 """Test if the address is reserved for multicast use.
1026
1027 Returns:
1028 A boolean, True if the address is a multicast address.
1029 See RFC 2373 2.7 for details.
1030
1031 """
1032 return (self.network_address.is_multicast and
1033 self.broadcast_address.is_multicast)
1034
1035 @staticmethod
1036 def _is_subnet_of(a, b):
1037 try:
1038 # Always false if one is v4 and the other is v6.
1039 if a._version != b._version:
1040 raise TypeError(f"{a} and {b} are not of the same version")
1041 return (b.network_address <= a.network_address and
1042 b.broadcast_address >= a.broadcast_address)
1043 except AttributeError:
1044 raise TypeError(f"Unable to test subnet containment "
1045 f"between {a} and {b}")
1046
1047 def subnet_of(self, other):
1048 """Return True if this network is a subnet of other."""
1049 return self._is_subnet_of(self, other)
1050
1051 def supernet_of(self, other):
1052 """Return True if this network is a supernet of other."""
1053 return self._is_subnet_of(other, self)
1054
1055 @property
1056 def is_reserved(self):
1057 """Test if the address is otherwise IETF reserved.
1058
1059 Returns:
1060 A boolean, True if the address is within one of the
1061 reserved IPv6 Network ranges.
1062
1063 """
1064 return (self.network_address.is_reserved and
1065 self.broadcast_address.is_reserved)
1066
1067 @property
1068 def is_link_local(self):
1069 """Test if the address is reserved for link-local.
1070
1071 Returns:
1072 A boolean, True if the address is reserved per RFC 4291.
1073
1074 """
1075 return (self.network_address.is_link_local and
1076 self.broadcast_address.is_link_local)
1077
1078 @property
1079 def is_private(self):
1080 """Test if this network belongs to a private range.
1081
1082 Returns:
1083 A boolean, True if the network is reserved per
1084 iana-ipv4-special-registry or iana-ipv6-special-registry.
1085
1086 """
1087 return any(self.network_address in priv_network and
1088 self.broadcast_address in priv_network
1089 for priv_network in self._constants._private_networks) and all(
1090 self.network_address not in network and
1091 self.broadcast_address not in network
1092 for network in self._constants._private_networks_exceptions
1093 )
1094
1095 @property
1096 def is_global(self):
1097 """Test if this address is allocated for public networks.
1098
1099 Returns:
1100 A boolean, True if the address is not reserved per
1101 iana-ipv4-special-registry or iana-ipv6-special-registry.
1102
1103 """
1104 return not self.is_private
1105
1106 @property
1107 def is_unspecified(self):
1108 """Test if the address is unspecified.
1109
1110 Returns:
1111 A boolean, True if this is the unspecified address as defined in
1112 RFC 2373 2.5.2.
1113
1114 """
1115 return (self.network_address.is_unspecified and
1116 self.broadcast_address.is_unspecified)
1117
1118 @property
1119 def is_loopback(self):
1120 """Test if the address is a loopback address.
1121
1122 Returns:
1123 A boolean, True if the address is a loopback address as defined in
1124 RFC 2373 2.5.3.
1125
1126 """
1127 return (self.network_address.is_loopback and
1128 self.broadcast_address.is_loopback)
1129
1130
1131 class _BaseConstants:
1132
1133 _private_networks = []
1134
1135
1136 _BaseNetwork._constants = _BaseConstants
1137
1138
1139 class _BaseV4:
1140
1141 """Base IPv4 object.
1142
1143 The following methods are used by IPv4 objects in both single IP
1144 addresses and networks.
1145
1146 """
1147
1148 __slots__ = ()
1149 _version = 4
1150 # Equivalent to 255.255.255.255 or 32 bits of 1's.
1151 _ALL_ONES = (2**IPV4LENGTH) - 1
1152
1153 _max_prefixlen = IPV4LENGTH
1154 # There are only a handful of valid v4 netmasks, so we cache them all
1155 # when constructed (see _make_netmask()).
1156 _netmask_cache = {}
1157
1158 def _explode_shorthand_ip_string(self):
1159 return str(self)
1160
1161 @classmethod
1162 def _make_netmask(cls, arg):
1163 """Make a (netmask, prefix_len) tuple from the given argument.
1164
1165 Argument can be:
1166 - an integer (the prefix length)
1167 - a string representing the prefix length (e.g. "24")
1168 - a string representing the prefix netmask (e.g. "255.255.255.0")
1169 """
1170 if arg not in cls._netmask_cache:
1171 if isinstance(arg, int):
1172 prefixlen = arg
1173 if not (0 <= prefixlen <= cls._max_prefixlen):
1174 cls._report_invalid_netmask(prefixlen)
1175 else:
1176 try:
1177 # Check for a netmask in prefix length form
1178 prefixlen = cls._prefix_from_prefix_string(arg)
1179 except NetmaskValueError:
1180 # Check for a netmask or hostmask in dotted-quad form.
1181 # This may raise NetmaskValueError.
1182 prefixlen = cls._prefix_from_ip_string(arg)
1183 netmask = IPv4Address(cls._ip_int_from_prefix(prefixlen))
1184 cls._netmask_cache[arg] = netmask, prefixlen
1185 return cls._netmask_cache[arg]
1186
1187 @classmethod
1188 def _ip_int_from_string(cls, ip_str):
1189 """Turn the given IP string into an integer for comparison.
1190
1191 Args:
1192 ip_str: A string, the IP ip_str.
1193
1194 Returns:
1195 The IP ip_str as an integer.
1196
1197 Raises:
1198 AddressValueError: if ip_str isn't a valid IPv4 Address.
1199
1200 """
1201 if not ip_str:
1202 raise AddressValueError('Address cannot be empty')
1203
1204 octets = ip_str.split('.')
1205 if len(octets) != 4:
1206 raise AddressValueError("Expected 4 octets in %r" % ip_str)
1207
1208 try:
1209 return int.from_bytes(map(cls._parse_octet, octets), 'big')
1210 except ValueError as exc:
1211 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
1212
1213 @classmethod
1214 def _parse_octet(cls, octet_str):
1215 """Convert a decimal octet into an integer.
1216
1217 Args:
1218 octet_str: A string, the number to parse.
1219
1220 Returns:
1221 The octet as an integer.
1222
1223 Raises:
1224 ValueError: if the octet isn't strictly a decimal from [0..255].
1225
1226 """
1227 if not octet_str:
1228 raise ValueError("Empty octet not permitted")
1229 # Reject non-ASCII digits.
1230 if not (octet_str.isascii() and octet_str.isdigit()):
1231 msg = "Only decimal digits permitted in %r"
1232 raise ValueError(msg % octet_str)
1233 # We do the length check second, since the invalid character error
1234 # is likely to be more informative for the user
1235 if len(octet_str) > 3:
1236 msg = "At most 3 characters permitted in %r"
1237 raise ValueError(msg % octet_str)
1238 # Handle leading zeros as strict as glibc's inet_pton()
1239 # See security bug bpo-36384
1240 if octet_str != '0' and octet_str[0] == '0':
1241 msg = "Leading zeros are not permitted in %r"
1242 raise ValueError(msg % octet_str)
1243 # Convert to integer (we know digits are legal)
1244 octet_int = int(octet_str, 10)
1245 if octet_int > 255:
1246 raise ValueError("Octet %d (> 255) not permitted" % octet_int)
1247 return octet_int
1248
1249 @classmethod
1250 def _string_from_ip_int(cls, ip_int):
1251 """Turns a 32-bit integer into dotted decimal notation.
1252
1253 Args:
1254 ip_int: An integer, the IP address.
1255
1256 Returns:
1257 The IP address as a string in dotted decimal notation.
1258
1259 """
1260 return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
1261
1262 def _reverse_pointer(self):
1263 """Return the reverse DNS pointer name for the IPv4 address.
1264
1265 This implements the method described in RFC1035 3.5.
1266
1267 """
1268 reverse_octets = str(self).split('.')[::-1]
1269 return '.'.join(reverse_octets) + '.in-addr.arpa'
1270
1271 @property
1272 def max_prefixlen(self):
1273 return self._max_prefixlen
1274
1275 @property
1276 def version(self):
1277 return self._version
1278
1279
1280 class IPv4Address(_BaseV4, _BaseAddress):
1281
1282 """Represent and manipulate single IPv4 Addresses."""
1283
1284 __slots__ = ('_ip', '__weakref__')
1285
1286 def __init__(self, address):
1287
1288 """
1289 Args:
1290 address: A string or integer representing the IP
1291
1292 Additionally, an integer can be passed, so
1293 IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1294 or, more generally
1295 IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1296 IPv4Address('192.0.2.1')
1297
1298 Raises:
1299 AddressValueError: If ipaddress isn't a valid IPv4 address.
1300
1301 """
1302 # Efficient constructor from integer.
1303 if isinstance(address, int):
1304 self._check_int_address(address)
1305 self._ip = address
1306 return
1307
1308 # Constructing from a packed address
1309 if isinstance(address, bytes):
1310 self._check_packed_address(address, 4)
1311 self._ip = int.from_bytes(address) # big endian
1312 return
1313
1314 # Assume input argument to be string or any object representation
1315 # which converts into a formatted IP string.
1316 addr_str = str(address)
1317 if '/' in addr_str:
1318 raise AddressValueError(f"Unexpected '/' in {address!r}")
1319 self._ip = self._ip_int_from_string(addr_str)
1320
1321 @property
1322 def packed(self):
1323 """The binary representation of this address."""
1324 return v4_int_to_packed(self._ip)
1325
1326 @property
1327 def is_reserved(self):
1328 """Test if the address is otherwise IETF reserved.
1329
1330 Returns:
1331 A boolean, True if the address is within the
1332 reserved IPv4 Network range.
1333
1334 """
1335 return self in self._constants._reserved_network
1336
1337 @property
1338 @functools.lru_cache()
1339 def is_private(self):
1340 """``True`` if the address is defined as not globally reachable by
1341 iana-ipv4-special-registry_ (for IPv4) or iana-ipv6-special-registry_
1342 (for IPv6) with the following exceptions:
1343
1344 * ``is_private`` is ``False`` for ``100.64.0.0/10``
1345 * For IPv4-mapped IPv6-addresses the ``is_private`` value is determined by the
1346 semantics of the underlying IPv4 addresses and the following condition holds
1347 (see :attr:`IPv6Address.ipv4_mapped`)::
1348
1349 address.is_private == address.ipv4_mapped.is_private
1350
1351 ``is_private`` has value opposite to :attr:`is_global`, except for the ``100.64.0.0/10``
1352 IPv4 range where they are both ``False``.
1353 """
1354 return (
1355 any(self in net for net in self._constants._private_networks)
1356 and all(self not in net for net in self._constants._private_networks_exceptions)
1357 )
1358
1359 @property
1360 @functools.lru_cache()
1361 def is_global(self):
1362 """``True`` if the address is defined as globally reachable by
1363 iana-ipv4-special-registry_ (for IPv4) or iana-ipv6-special-registry_
1364 (for IPv6) with the following exception:
1365
1366 For IPv4-mapped IPv6-addresses the ``is_private`` value is determined by the
1367 semantics of the underlying IPv4 addresses and the following condition holds
1368 (see :attr:`IPv6Address.ipv4_mapped`)::
1369
1370 address.is_global == address.ipv4_mapped.is_global
1371
1372 ``is_global`` has value opposite to :attr:`is_private`, except for the ``100.64.0.0/10``
1373 IPv4 range where they are both ``False``.
1374 """
1375 return self not in self._constants._public_network and not self.is_private
1376
1377 @property
1378 def is_multicast(self):
1379 """Test if the address is reserved for multicast use.
1380
1381 Returns:
1382 A boolean, True if the address is multicast.
1383 See RFC 3171 for details.
1384
1385 """
1386 return self in self._constants._multicast_network
1387
1388 @property
1389 def is_unspecified(self):
1390 """Test if the address is unspecified.
1391
1392 Returns:
1393 A boolean, True if this is the unspecified address as defined in
1394 RFC 5735 3.
1395
1396 """
1397 return self == self._constants._unspecified_address
1398
1399 @property
1400 def is_loopback(self):
1401 """Test if the address is a loopback address.
1402
1403 Returns:
1404 A boolean, True if the address is a loopback per RFC 3330.
1405
1406 """
1407 return self in self._constants._loopback_network
1408
1409 @property
1410 def is_link_local(self):
1411 """Test if the address is reserved for link-local.
1412
1413 Returns:
1414 A boolean, True if the address is link-local per RFC 3927.
1415
1416 """
1417 return self in self._constants._linklocal_network
1418
1419
1420 class IPv4Interface(IPv4Address):
1421
1422 def __init__(self, address):
1423 addr, mask = self._split_addr_prefix(address)
1424
1425 IPv4Address.__init__(self, addr)
1426 self.network = IPv4Network((addr, mask), strict=False)
1427 self.netmask = self.network.netmask
1428 self._prefixlen = self.network._prefixlen
1429
1430 @functools.cached_property
1431 def hostmask(self):
1432 return self.network.hostmask
1433
1434 def __str__(self):
1435 return '%s/%d' % (self._string_from_ip_int(self._ip),
1436 self._prefixlen)
1437
1438 def __eq__(self, other):
1439 address_equal = IPv4Address.__eq__(self, other)
1440 if address_equal is NotImplemented or not address_equal:
1441 return address_equal
1442 try:
1443 return self.network == other.network
1444 except AttributeError:
1445 # An interface with an associated network is NOT the
1446 # same as an unassociated address. That's why the hash
1447 # takes the extra info into account.
1448 return False
1449
1450 def __lt__(self, other):
1451 address_less = IPv4Address.__lt__(self, other)
1452 if address_less is NotImplemented:
1453 return NotImplemented
1454 try:
1455 return (self.network < other.network or
1456 self.network == other.network and address_less)
1457 except AttributeError:
1458 # We *do* allow addresses and interfaces to be sorted. The
1459 # unassociated address is considered less than all interfaces.
1460 return False
1461
1462 def __hash__(self):
1463 return hash((self._ip, self._prefixlen, int(self.network.network_address)))
1464
1465 __reduce__ = _IPAddressBase.__reduce__
1466
1467 @property
1468 def ip(self):
1469 return IPv4Address(self._ip)
1470
1471 @property
1472 def with_prefixlen(self):
1473 return '%s/%s' % (self._string_from_ip_int(self._ip),
1474 self._prefixlen)
1475
1476 @property
1477 def with_netmask(self):
1478 return '%s/%s' % (self._string_from_ip_int(self._ip),
1479 self.netmask)
1480
1481 @property
1482 def with_hostmask(self):
1483 return '%s/%s' % (self._string_from_ip_int(self._ip),
1484 self.hostmask)
1485
1486
1487 class IPv4Network(_BaseV4, _BaseNetwork):
1488
1489 """This class represents and manipulates 32-bit IPv4 network + addresses..
1490
1491 Attributes: [examples for IPv4Network('192.0.2.0/27')]
1492 .network_address: IPv4Address('192.0.2.0')
1493 .hostmask: IPv4Address('0.0.0.31')
1494 .broadcast_address: IPv4Address('192.0.2.32')
1495 .netmask: IPv4Address('255.255.255.224')
1496 .prefixlen: 27
1497
1498 """
1499 # Class to use when creating address objects
1500 _address_class = IPv4Address
1501
1502 def __init__(self, address, strict=True):
1503 """Instantiate a new IPv4 network object.
1504
1505 Args:
1506 address: A string or integer representing the IP [& network].
1507 '192.0.2.0/24'
1508 '192.0.2.0/255.255.255.0'
1509 '192.0.2.0/0.0.0.255'
1510 are all functionally the same in IPv4. Similarly,
1511 '192.0.2.1'
1512 '192.0.2.1/255.255.255.255'
1513 '192.0.2.1/32'
1514 are also functionally equivalent. That is to say, failing to
1515 provide a subnetmask will create an object with a mask of /32.
1516
1517 If the mask (portion after the / in the argument) is given in
1518 dotted quad form, it is treated as a netmask if it starts with a
1519 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1520 starts with a zero field (e.g. 0.255.255.255 == /8), with the
1521 single exception of an all-zero mask which is treated as a
1522 netmask == /0. If no mask is given, a default of /32 is used.
1523
1524 Additionally, an integer can be passed, so
1525 IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1526 or, more generally
1527 IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1528 IPv4Interface('192.0.2.1')
1529
1530 Raises:
1531 AddressValueError: If ipaddress isn't a valid IPv4 address.
1532 NetmaskValueError: If the netmask isn't valid for
1533 an IPv4 address.
1534 ValueError: If strict is True and a network address is not
1535 supplied.
1536 """
1537 addr, mask = self._split_addr_prefix(address)
1538
1539 self.network_address = IPv4Address(addr)
1540 self.netmask, self._prefixlen = self._make_netmask(mask)
1541 packed = int(self.network_address)
1542 if packed & int(self.netmask) != packed:
1543 if strict:
1544 raise ValueError('%s has host bits set' % self)
1545 else:
1546 self.network_address = IPv4Address(packed &
1547 int(self.netmask))
1548
1549 if self._prefixlen == (self._max_prefixlen - 1):
1550 self.hosts = self.__iter__
1551 elif self._prefixlen == (self._max_prefixlen):
1552 self.hosts = lambda: [IPv4Address(addr)]
1553
1554 @property
1555 @functools.lru_cache()
1556 def is_global(self):
1557 """Test if this address is allocated for public networks.
1558
1559 Returns:
1560 A boolean, True if the address is not reserved per
1561 iana-ipv4-special-registry.
1562
1563 """
1564 return (not (self.network_address in IPv4Network('100.64.0.0/10') and
1565 self.broadcast_address in IPv4Network('100.64.0.0/10')) and
1566 not self.is_private)
1567
1568
1569 class _IPv4Constants:
1570 _linklocal_network = IPv4Network('169.254.0.0/16')
1571
1572 _loopback_network = IPv4Network('127.0.0.0/8')
1573
1574 _multicast_network = IPv4Network('224.0.0.0/4')
1575
1576 _public_network = IPv4Network('100.64.0.0/10')
1577
1578 # Not globally reachable address blocks listed on
1579 # https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
1580 _private_networks = [
1581 IPv4Network('0.0.0.0/8'),
1582 IPv4Network('10.0.0.0/8'),
1583 IPv4Network('127.0.0.0/8'),
1584 IPv4Network('169.254.0.0/16'),
1585 IPv4Network('172.16.0.0/12'),
1586 IPv4Network('192.0.0.0/24'),
1587 IPv4Network('192.0.0.170/31'),
1588 IPv4Network('192.0.2.0/24'),
1589 IPv4Network('192.168.0.0/16'),
1590 IPv4Network('198.18.0.0/15'),
1591 IPv4Network('198.51.100.0/24'),
1592 IPv4Network('203.0.113.0/24'),
1593 IPv4Network('240.0.0.0/4'),
1594 IPv4Network('255.255.255.255/32'),
1595 ]
1596
1597 _private_networks_exceptions = [
1598 IPv4Network('192.0.0.9/32'),
1599 IPv4Network('192.0.0.10/32'),
1600 ]
1601
1602 _reserved_network = IPv4Network('240.0.0.0/4')
1603
1604 _unspecified_address = IPv4Address('0.0.0.0')
1605
1606
1607 IPv4Address._constants = _IPv4Constants
1608 IPv4Network._constants = _IPv4Constants
1609
1610
1611 class _BaseV6:
1612
1613 """Base IPv6 object.
1614
1615 The following methods are used by IPv6 objects in both single IP
1616 addresses and networks.
1617
1618 """
1619
1620 __slots__ = ()
1621 _version = 6
1622 _ALL_ONES = (2**IPV6LENGTH) - 1
1623 _HEXTET_COUNT = 8
1624 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
1625 _max_prefixlen = IPV6LENGTH
1626
1627 # There are only a bunch of valid v6 netmasks, so we cache them all
1628 # when constructed (see _make_netmask()).
1629 _netmask_cache = {}
1630
1631 @classmethod
1632 def _make_netmask(cls, arg):
1633 """Make a (netmask, prefix_len) tuple from the given argument.
1634
1635 Argument can be:
1636 - an integer (the prefix length)
1637 - a string representing the prefix length (e.g. "24")
1638 - a string representing the prefix netmask (e.g. "255.255.255.0")
1639 """
1640 if arg not in cls._netmask_cache:
1641 if isinstance(arg, int):
1642 prefixlen = arg
1643 if not (0 <= prefixlen <= cls._max_prefixlen):
1644 cls._report_invalid_netmask(prefixlen)
1645 else:
1646 prefixlen = cls._prefix_from_prefix_string(arg)
1647 netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen))
1648 cls._netmask_cache[arg] = netmask, prefixlen
1649 return cls._netmask_cache[arg]
1650
1651 @classmethod
1652 def _ip_int_from_string(cls, ip_str):
1653 """Turn an IPv6 ip_str into an integer.
1654
1655 Args:
1656 ip_str: A string, the IPv6 ip_str.
1657
1658 Returns:
1659 An int, the IPv6 address
1660
1661 Raises:
1662 AddressValueError: if ip_str isn't a valid IPv6 Address.
1663
1664 """
1665 if not ip_str:
1666 raise AddressValueError('Address cannot be empty')
1667 if len(ip_str) > 45:
1668 shorten = ip_str
1669 if len(shorten) > 100:
1670 shorten = f'{ip_str[:45]}({len(ip_str)-90} chars elided){ip_str[-45:]}'
1671 raise AddressValueError(f"At most 45 characters expected in "
1672 f"{shorten!r}")
1673
1674 # We want to allow more parts than the max to be 'split'
1675 # to preserve the correct error message when there are
1676 # too many parts combined with '::'
1677 _max_parts = cls._HEXTET_COUNT + 1
1678 parts = ip_str.split(':', maxsplit=_max_parts)
1679
1680 # An IPv6 address needs at least 2 colons (3 parts).
1681 _min_parts = 3
1682 if len(parts) < _min_parts:
1683 msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
1684 raise AddressValueError(msg)
1685
1686 # If the address has an IPv4-style suffix, convert it to hexadecimal.
1687 if '.' in parts[-1]:
1688 try:
1689 ipv4_int = IPv4Address(parts.pop())._ip
1690 except AddressValueError as exc:
1691 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
1692 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1693 parts.append('%x' % (ipv4_int & 0xFFFF))
1694
1695 # An IPv6 address can't have more than 8 colons (9 parts).
1696 # The extra colon comes from using the "::" notation for a single
1697 # leading or trailing zero part.
1698 if len(parts) > _max_parts:
1699 msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
1700 raise AddressValueError(msg)
1701
1702 # Disregarding the endpoints, find '::' with nothing in between.
1703 # This indicates that a run of zeroes has been skipped.
1704 skip_index = None
1705 for i in range(1, len(parts) - 1):
1706 if not parts[i]:
1707 if skip_index is not None:
1708 # Can't have more than one '::'
1709 msg = "At most one '::' permitted in %r" % ip_str
1710 raise AddressValueError(msg)
1711 skip_index = i
1712
1713 # parts_hi is the number of parts to copy from above/before the '::'
1714 # parts_lo is the number of parts to copy from below/after the '::'
1715 if skip_index is not None:
1716 # If we found a '::', then check if it also covers the endpoints.
1717 parts_hi = skip_index
1718 parts_lo = len(parts) - skip_index - 1
1719 if not parts[0]:
1720 parts_hi -= 1
1721 if parts_hi:
1722 msg = "Leading ':' only permitted as part of '::' in %r"
1723 raise AddressValueError(msg % ip_str) # ^: requires ^::
1724 if not parts[-1]:
1725 parts_lo -= 1
1726 if parts_lo:
1727 msg = "Trailing ':' only permitted as part of '::' in %r"
1728 raise AddressValueError(msg % ip_str) # :$ requires ::$
1729 parts_skipped = cls._HEXTET_COUNT - (parts_hi + parts_lo)
1730 if parts_skipped < 1:
1731 msg = "Expected at most %d other parts with '::' in %r"
1732 raise AddressValueError(msg % (cls._HEXTET_COUNT-1, ip_str))
1733 else:
1734 # Otherwise, allocate the entire address to parts_hi. The
1735 # endpoints could still be empty, but _parse_hextet() will check
1736 # for that.
1737 if len(parts) != cls._HEXTET_COUNT:
1738 msg = "Exactly %d parts expected without '::' in %r"
1739 raise AddressValueError(msg % (cls._HEXTET_COUNT, ip_str))
1740 if not parts[0]:
1741 msg = "Leading ':' only permitted as part of '::' in %r"
1742 raise AddressValueError(msg % ip_str) # ^: requires ^::
1743 if not parts[-1]:
1744 msg = "Trailing ':' only permitted as part of '::' in %r"
1745 raise AddressValueError(msg % ip_str) # :$ requires ::$
1746 parts_hi = len(parts)
1747 parts_lo = 0
1748 parts_skipped = 0
1749
1750 try:
1751 # Now, parse the hextets into a 128-bit integer.
1752 ip_int = 0
1753 for i in range(parts_hi):
1754 ip_int <<= 16
1755 ip_int |= cls._parse_hextet(parts[i])
1756 ip_int <<= 16 * parts_skipped
1757 for i in range(-parts_lo, 0):
1758 ip_int <<= 16
1759 ip_int |= cls._parse_hextet(parts[i])
1760 return ip_int
1761 except ValueError as exc:
1762 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
1763
1764 @classmethod
1765 def _parse_hextet(cls, hextet_str):
1766 """Convert an IPv6 hextet string into an integer.
1767
1768 Args:
1769 hextet_str: A string, the number to parse.
1770
1771 Returns:
1772 The hextet as an integer.
1773
1774 Raises:
1775 ValueError: if the input isn't strictly a hex number from
1776 [0..FFFF].
1777
1778 """
1779 # Reject non-ASCII digits.
1780 if not cls._HEX_DIGITS.issuperset(hextet_str):
1781 raise ValueError("Only hex digits permitted in %r" % hextet_str)
1782 # We do the length check second, since the invalid character error
1783 # is likely to be more informative for the user
1784 if len(hextet_str) > 4:
1785 msg = "At most 4 characters permitted in %r"
1786 raise ValueError(msg % hextet_str)
1787 # Length check means we can skip checking the integer value
1788 return int(hextet_str, 16)
1789
1790 @classmethod
1791 def _compress_hextets(cls, hextets):
1792 """Compresses a list of hextets.
1793
1794 Compresses a list of strings, replacing the longest continuous
1795 sequence of "0" in the list with "" and adding empty strings at
1796 the beginning or at the end of the string such that subsequently
1797 calling ":".join(hextets) will produce the compressed version of
1798 the IPv6 address.
1799
1800 Args:
1801 hextets: A list of strings, the hextets to compress.
1802
1803 Returns:
1804 A list of strings.
1805
1806 """
1807 best_doublecolon_start = -1
1808 best_doublecolon_len = 0
1809 doublecolon_start = -1
1810 doublecolon_len = 0
1811 for index, hextet in enumerate(hextets):
1812 if hextet == '0':
1813 doublecolon_len += 1
1814 if doublecolon_start == -1:
1815 # Start of a sequence of zeros.
1816 doublecolon_start = index
1817 if doublecolon_len > best_doublecolon_len:
1818 # This is the longest sequence of zeros so far.
1819 best_doublecolon_len = doublecolon_len
1820 best_doublecolon_start = doublecolon_start
1821 else:
1822 doublecolon_len = 0
1823 doublecolon_start = -1
1824
1825 if best_doublecolon_len > 1:
1826 best_doublecolon_end = (best_doublecolon_start +
1827 best_doublecolon_len)
1828 # For zeros at the end of the address.
1829 if best_doublecolon_end == len(hextets):
1830 hextets += ['']
1831 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1832 # For zeros at the beginning of the address.
1833 if best_doublecolon_start == 0:
1834 hextets = [''] + hextets
1835
1836 return hextets
1837
1838 @classmethod
1839 def _string_from_ip_int(cls, ip_int=None):
1840 """Turns a 128-bit integer into hexadecimal notation.
1841
1842 Args:
1843 ip_int: An integer, the IP address.
1844
1845 Returns:
1846 A string, the hexadecimal representation of the address.
1847
1848 Raises:
1849 ValueError: The address is bigger than 128 bits of all ones.
1850
1851 """
1852 if ip_int is None:
1853 ip_int = int(cls._ip)
1854
1855 if ip_int > cls._ALL_ONES:
1856 raise ValueError('IPv6 address is too large')
1857
1858 hex_str = '%032x' % ip_int
1859 hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
1860
1861 hextets = cls._compress_hextets(hextets)
1862 return ':'.join(hextets)
1863
1864 def _explode_shorthand_ip_string(self):
1865 """Expand a shortened IPv6 address.
1866
1867 Returns:
1868 A string, the expanded IPv6 address.
1869
1870 """
1871 if isinstance(self, IPv6Network):
1872 ip_str = str(self.network_address)
1873 elif isinstance(self, IPv6Interface):
1874 ip_str = str(self.ip)
1875 else:
1876 ip_str = str(self)
1877
1878 ip_int = self._ip_int_from_string(ip_str)
1879 hex_str = '%032x' % ip_int
1880 parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
1881 if isinstance(self, (_BaseNetwork, IPv6Interface)):
1882 return '%s/%d' % (':'.join(parts), self._prefixlen)
1883 return ':'.join(parts)
1884
1885 def _reverse_pointer(self):
1886 """Return the reverse DNS pointer name for the IPv6 address.
1887
1888 This implements the method described in RFC3596 2.5.
1889
1890 """
1891 reverse_chars = self.exploded[::-1].replace(':', '')
1892 return '.'.join(reverse_chars) + '.ip6.arpa'
1893
1894 @staticmethod
1895 def _split_scope_id(ip_str):
1896 """Helper function to parse IPv6 string address with scope id.
1897
1898 See RFC 4007 for details.
1899
1900 Args:
1901 ip_str: A string, the IPv6 address.
1902
1903 Returns:
1904 (addr, scope_id) tuple.
1905
1906 """
1907 addr, sep, scope_id = ip_str.partition('%')
1908 if not sep:
1909 scope_id = None
1910 elif not scope_id or '%' in scope_id:
1911 raise AddressValueError('Invalid IPv6 address: "%r"' % ip_str)
1912 return addr, scope_id
1913
1914 @property
1915 def max_prefixlen(self):
1916 return self._max_prefixlen
1917
1918 @property
1919 def version(self):
1920 return self._version
1921
1922
1923 class IPv6Address(_BaseV6, _BaseAddress):
1924
1925 """Represent and manipulate single IPv6 Addresses."""
1926
1927 __slots__ = ('_ip', '_scope_id', '__weakref__')
1928
1929 def __init__(self, address):
1930 """Instantiate a new IPv6 address object.
1931
1932 Args:
1933 address: A string or integer representing the IP
1934
1935 Additionally, an integer can be passed, so
1936 IPv6Address('2001:db8::') ==
1937 IPv6Address(42540766411282592856903984951653826560)
1938 or, more generally
1939 IPv6Address(int(IPv6Address('2001:db8::'))) ==
1940 IPv6Address('2001:db8::')
1941
1942 Raises:
1943 AddressValueError: If address isn't a valid IPv6 address.
1944
1945 """
1946 # Efficient constructor from integer.
1947 if isinstance(address, int):
1948 self._check_int_address(address)
1949 self._ip = address
1950 self._scope_id = None
1951 return
1952
1953 # Constructing from a packed address
1954 if isinstance(address, bytes):
1955 self._check_packed_address(address, 16)
1956 self._ip = int.from_bytes(address, 'big')
1957 self._scope_id = None
1958 return
1959
1960 # Assume input argument to be string or any object representation
1961 # which converts into a formatted IP string.
1962 addr_str = str(address)
1963 if '/' in addr_str:
1964 raise AddressValueError(f"Unexpected '/' in {address!r}")
1965 addr_str, self._scope_id = self._split_scope_id(addr_str)
1966
1967 self._ip = self._ip_int_from_string(addr_str)
1968
1969 def _explode_shorthand_ip_string(self):
1970 ipv4_mapped = self.ipv4_mapped
1971 if ipv4_mapped is None:
1972 return super()._explode_shorthand_ip_string()
1973 prefix_len = 30
1974 raw_exploded_str = super()._explode_shorthand_ip_string()
1975 return f"{raw_exploded_str[:prefix_len]}{ipv4_mapped!s}"
1976
1977 def _reverse_pointer(self):
1978 ipv4_mapped = self.ipv4_mapped
1979 if ipv4_mapped is None:
1980 return super()._reverse_pointer()
1981 prefix_len = 30
1982 raw_exploded_str = super()._explode_shorthand_ip_string()[:prefix_len]
1983 # ipv4 encoded using hexadecimal nibbles instead of decimals
1984 ipv4_int = ipv4_mapped._ip
1985 reverse_chars = f"{raw_exploded_str}{ipv4_int:008x}"[::-1].replace(':', '')
1986 return '.'.join(reverse_chars) + '.ip6.arpa'
1987
1988 def _ipv4_mapped_ipv6_to_str(self):
1989 """Return convenient text representation of IPv4-mapped IPv6 address
1990
1991 See RFC 4291 2.5.5.2, 2.2 p.3 for details.
1992
1993 Returns:
1994 A string, 'x:x:x:x:x:x:d.d.d.d', where the 'x's are the hexadecimal values of
1995 the six high-order 16-bit pieces of the address, and the 'd's are
1996 the decimal values of the four low-order 8-bit pieces of the
1997 address (standard IPv4 representation) as defined in RFC 4291 2.2 p.3.
1998
1999 """
2000 ipv4_mapped = self.ipv4_mapped
2001 if ipv4_mapped is None:
2002 raise AddressValueError("Can not apply to non-IPv4-mapped IPv6 address %s" % str(self))
2003 high_order_bits = self._ip >> 32
2004 return "%s:%s" % (self._string_from_ip_int(high_order_bits), str(ipv4_mapped))
2005
2006 def __str__(self):
2007 ipv4_mapped = self.ipv4_mapped
2008 if ipv4_mapped is None:
2009 ip_str = super().__str__()
2010 else:
2011 ip_str = self._ipv4_mapped_ipv6_to_str()
2012 return ip_str + '%' + self._scope_id if self._scope_id else ip_str
2013
2014 def __hash__(self):
2015 return hash((self._ip, self._scope_id))
2016
2017 def __eq__(self, other):
2018 address_equal = super().__eq__(other)
2019 if address_equal is NotImplemented:
2020 return NotImplemented
2021 if not address_equal:
2022 return False
2023 return self._scope_id == getattr(other, '_scope_id', None)
2024
2025 def __reduce__(self):
2026 return (self.__class__, (str(self),))
2027
2028 @property
2029 def scope_id(self):
2030 """Identifier of a particular zone of the address's scope.
2031
2032 See RFC 4007 for details.
2033
2034 Returns:
2035 A string identifying the zone of the address if specified, else None.
2036
2037 """
2038 return self._scope_id
2039
2040 @property
2041 def packed(self):
2042 """The binary representation of this address."""
2043 return v6_int_to_packed(self._ip)
2044
2045 @property
2046 def is_multicast(self):
2047 """Test if the address is reserved for multicast use.
2048
2049 Returns:
2050 A boolean, True if the address is a multicast address.
2051 See RFC 2373 2.7 for details.
2052
2053 """
2054 ipv4_mapped = self.ipv4_mapped
2055 if ipv4_mapped is not None:
2056 return ipv4_mapped.is_multicast
2057 return self in self._constants._multicast_network
2058
2059 @property
2060 def is_reserved(self):
2061 """Test if the address is otherwise IETF reserved.
2062
2063 Returns:
2064 A boolean, True if the address is within one of the
2065 reserved IPv6 Network ranges.
2066
2067 """
2068 ipv4_mapped = self.ipv4_mapped
2069 if ipv4_mapped is not None:
2070 return ipv4_mapped.is_reserved
2071 return any(self in x for x in self._constants._reserved_networks)
2072
2073 @property
2074 def is_link_local(self):
2075 """Test if the address is reserved for link-local.
2076
2077 Returns:
2078 A boolean, True if the address is reserved per RFC 4291.
2079
2080 """
2081 ipv4_mapped = self.ipv4_mapped
2082 if ipv4_mapped is not None:
2083 return ipv4_mapped.is_link_local
2084 return self in self._constants._linklocal_network
2085
2086 @property
2087 def is_site_local(self):
2088 """Test if the address is reserved for site-local.
2089
2090 Note that the site-local address space has been deprecated by RFC 3879.
2091 Use is_private to test if this address is in the space of unique local
2092 addresses as defined by RFC 4193.
2093
2094 Returns:
2095 A boolean, True if the address is reserved per RFC 3513 2.5.6.
2096
2097 """
2098 return self in self._constants._sitelocal_network
2099
2100 @property
2101 @functools.lru_cache()
2102 def is_private(self):
2103 """``True`` if the address is defined as not globally reachable by
2104 iana-ipv4-special-registry_ (for IPv4) or iana-ipv6-special-registry_
2105 (for IPv6) with the following exceptions:
2106
2107 * ``is_private`` is ``False`` for ``100.64.0.0/10``
2108 * For IPv4-mapped IPv6-addresses the ``is_private`` value is determined by the
2109 semantics of the underlying IPv4 addresses and the following condition holds
2110 (see :attr:`IPv6Address.ipv4_mapped`)::
2111
2112 address.is_private == address.ipv4_mapped.is_private
2113
2114 ``is_private`` has value opposite to :attr:`is_global`, except for the ``100.64.0.0/10``
2115 IPv4 range where they are both ``False``.
2116 """
2117 ipv4_mapped = self.ipv4_mapped
2118 if ipv4_mapped is not None:
2119 return ipv4_mapped.is_private
2120 return (
2121 any(self in net for net in self._constants._private_networks)
2122 and all(self not in net for net in self._constants._private_networks_exceptions)
2123 )
2124
2125 @property
2126 def is_global(self):
2127 """``True`` if the address is defined as globally reachable by
2128 iana-ipv4-special-registry_ (for IPv4) or iana-ipv6-special-registry_
2129 (for IPv6) with the following exception:
2130
2131 For IPv4-mapped IPv6-addresses the ``is_private`` value is determined by the
2132 semantics of the underlying IPv4 addresses and the following condition holds
2133 (see :attr:`IPv6Address.ipv4_mapped`)::
2134
2135 address.is_global == address.ipv4_mapped.is_global
2136
2137 ``is_global`` has value opposite to :attr:`is_private`, except for the ``100.64.0.0/10``
2138 IPv4 range where they are both ``False``.
2139 """
2140 ipv4_mapped = self.ipv4_mapped
2141 if ipv4_mapped is not None:
2142 return ipv4_mapped.is_global
2143 return not self.is_private
2144
2145 @property
2146 def is_unspecified(self):
2147 """Test if the address is unspecified.
2148
2149 Returns:
2150 A boolean, True if this is the unspecified address as defined in
2151 RFC 2373 2.5.2.
2152
2153 """
2154 ipv4_mapped = self.ipv4_mapped
2155 if ipv4_mapped is not None:
2156 return ipv4_mapped.is_unspecified
2157 return self._ip == 0
2158
2159 @property
2160 def is_loopback(self):
2161 """Test if the address is a loopback address.
2162
2163 Returns:
2164 A boolean, True if the address is a loopback address as defined in
2165 RFC 2373 2.5.3.
2166
2167 """
2168 ipv4_mapped = self.ipv4_mapped
2169 if ipv4_mapped is not None:
2170 return ipv4_mapped.is_loopback
2171 return self._ip == 1
2172
2173 @property
2174 def ipv4_mapped(self):
2175 """Return the IPv4 mapped address.
2176
2177 Returns:
2178 If the IPv6 address is a v4 mapped address, return the
2179 IPv4 mapped address. Return None otherwise.
2180
2181 """
2182 if (self._ip >> 32) != 0xFFFF:
2183 return None
2184 return IPv4Address(self._ip & 0xFFFFFFFF)
2185
2186 @property
2187 def teredo(self):
2188 """Tuple of embedded teredo IPs.
2189
2190 Returns:
2191 Tuple of the (server, client) IPs or None if the address
2192 doesn't appear to be a teredo address (doesn't start with
2193 2001::/32)
2194
2195 """
2196 if (self._ip >> 96) != 0x20010000:
2197 return None
2198 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
2199 IPv4Address(~self._ip & 0xFFFFFFFF))
2200
2201 @property
2202 def sixtofour(self):
2203 """Return the IPv4 6to4 embedded address.
2204
2205 Returns:
2206 The IPv4 6to4-embedded address if present or None if the
2207 address doesn't appear to contain a 6to4 embedded address.
2208
2209 """
2210 if (self._ip >> 112) != 0x2002:
2211 return None
2212 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
2213
2214
2215 class IPv6Interface(IPv6Address):
2216
2217 def __init__(self, address):
2218 addr, mask = self._split_addr_prefix(address)
2219
2220 IPv6Address.__init__(self, addr)
2221 self.network = IPv6Network((addr, mask), strict=False)
2222 self.netmask = self.network.netmask
2223 self._prefixlen = self.network._prefixlen
2224
2225 @functools.cached_property
2226 def hostmask(self):
2227 return self.network.hostmask
2228
2229 def __str__(self):
2230 return '%s/%d' % (super().__str__(),
2231 self._prefixlen)
2232
2233 def __eq__(self, other):
2234 address_equal = IPv6Address.__eq__(self, other)
2235 if address_equal is NotImplemented or not address_equal:
2236 return address_equal
2237 try:
2238 return self.network == other.network
2239 except AttributeError:
2240 # An interface with an associated network is NOT the
2241 # same as an unassociated address. That's why the hash
2242 # takes the extra info into account.
2243 return False
2244
2245 def __lt__(self, other):
2246 address_less = IPv6Address.__lt__(self, other)
2247 if address_less is NotImplemented:
2248 return address_less
2249 try:
2250 return (self.network < other.network or
2251 self.network == other.network and address_less)
2252 except AttributeError:
2253 # We *do* allow addresses and interfaces to be sorted. The
2254 # unassociated address is considered less than all interfaces.
2255 return False
2256
2257 def __hash__(self):
2258 return hash((self._ip, self._prefixlen, int(self.network.network_address)))
2259
2260 __reduce__ = _IPAddressBase.__reduce__
2261
2262 @property
2263 def ip(self):
2264 return IPv6Address(self._ip)
2265
2266 @property
2267 def with_prefixlen(self):
2268 return '%s/%s' % (self._string_from_ip_int(self._ip),
2269 self._prefixlen)
2270
2271 @property
2272 def with_netmask(self):
2273 return '%s/%s' % (self._string_from_ip_int(self._ip),
2274 self.netmask)
2275
2276 @property
2277 def with_hostmask(self):
2278 return '%s/%s' % (self._string_from_ip_int(self._ip),
2279 self.hostmask)
2280
2281 @property
2282 def is_unspecified(self):
2283 return self._ip == 0 and self.network.is_unspecified
2284
2285 @property
2286 def is_loopback(self):
2287 return super().is_loopback and self.network.is_loopback
2288
2289
2290 class IPv6Network(_BaseV6, _BaseNetwork):
2291
2292 """This class represents and manipulates 128-bit IPv6 networks.
2293
2294 Attributes: [examples for IPv6('2001:db8::1000/124')]
2295 .network_address: IPv6Address('2001:db8::1000')
2296 .hostmask: IPv6Address('::f')
2297 .broadcast_address: IPv6Address('2001:db8::100f')
2298 .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
2299 .prefixlen: 124
2300
2301 """
2302
2303 # Class to use when creating address objects
2304 _address_class = IPv6Address
2305
2306 def __init__(self, address, strict=True):
2307 """Instantiate a new IPv6 Network object.
2308
2309 Args:
2310 address: A string or integer representing the IPv6 network or the
2311 IP and prefix/netmask.
2312 '2001:db8::/128'
2313 '2001:db8:0000:0000:0000:0000:0000:0000/128'
2314 '2001:db8::'
2315 are all functionally the same in IPv6. That is to say,
2316 failing to provide a subnetmask will create an object with
2317 a mask of /128.
2318
2319 Additionally, an integer can be passed, so
2320 IPv6Network('2001:db8::') ==
2321 IPv6Network(42540766411282592856903984951653826560)
2322 or, more generally
2323 IPv6Network(int(IPv6Network('2001:db8::'))) ==
2324 IPv6Network('2001:db8::')
2325
2326 strict: A boolean. If true, ensure that we have been passed
2327 A true network address, eg, 2001:db8::1000/124 and not an
2328 IP address on a network, eg, 2001:db8::1/124.
2329
2330 Raises:
2331 AddressValueError: If address isn't a valid IPv6 address.
2332 NetmaskValueError: If the netmask isn't valid for
2333 an IPv6 address.
2334 ValueError: If strict was True and a network address was not
2335 supplied.
2336 """
2337 addr, mask = self._split_addr_prefix(address)
2338
2339 self.network_address = IPv6Address(addr)
2340 self.netmask, self._prefixlen = self._make_netmask(mask)
2341 packed = int(self.network_address)
2342 if packed & int(self.netmask) != packed:
2343 if strict:
2344 raise ValueError('%s has host bits set' % self)
2345 else:
2346 self.network_address = IPv6Address(packed &
2347 int(self.netmask))
2348
2349 if self._prefixlen == (self._max_prefixlen - 1):
2350 self.hosts = self.__iter__
2351 elif self._prefixlen == self._max_prefixlen:
2352 self.hosts = lambda: [IPv6Address(addr)]
2353
2354 def hosts(self):
2355 """Generate Iterator over usable hosts in a network.
2356
2357 This is like __iter__ except it doesn't return the
2358 Subnet-Router anycast address.
2359
2360 """
2361 network = int(self.network_address)
2362 broadcast = int(self.broadcast_address)
2363 for x in range(network + 1, broadcast + 1):
2364 yield self._address_class(x)
2365
2366 @property
2367 def is_site_local(self):
2368 """Test if the address is reserved for site-local.
2369
2370 Note that the site-local address space has been deprecated by RFC 3879.
2371 Use is_private to test if this address is in the space of unique local
2372 addresses as defined by RFC 4193.
2373
2374 Returns:
2375 A boolean, True if the address is reserved per RFC 3513 2.5.6.
2376
2377 """
2378 return (self.network_address.is_site_local and
2379 self.broadcast_address.is_site_local)
2380
2381
2382 class _IPv6Constants:
2383
2384 _linklocal_network = IPv6Network('fe80::/10')
2385
2386 _multicast_network = IPv6Network('ff00::/8')
2387
2388 # Not globally reachable address blocks listed on
2389 # https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml
2390 _private_networks = [
2391 IPv6Network('::1/128'),
2392 IPv6Network('::/128'),
2393 IPv6Network('::ffff:0:0/96'),
2394 IPv6Network('64:ff9b:1::/48'),
2395 IPv6Network('100::/64'),
2396 IPv6Network('2001::/23'),
2397 IPv6Network('2001:db8::/32'),
2398 # IANA says N/A, let's consider it not globally reachable to be safe
2399 IPv6Network('2002::/16'),
2400 # RFC 9637: https://www.rfc-editor.org/rfc/rfc9637.html#section-6-2.2
2401 IPv6Network('3fff::/20'),
2402 IPv6Network('fc00::/7'),
2403 IPv6Network('fe80::/10'),
2404 ]
2405
2406 _private_networks_exceptions = [
2407 IPv6Network('2001:1::1/128'),
2408 IPv6Network('2001:1::2/128'),
2409 IPv6Network('2001:3::/32'),
2410 IPv6Network('2001:4:112::/48'),
2411 IPv6Network('2001:20::/28'),
2412 IPv6Network('2001:30::/28'),
2413 ]
2414
2415 _reserved_networks = [
2416 IPv6Network('::/8'), IPv6Network('100::/8'),
2417 IPv6Network('200::/7'), IPv6Network('400::/6'),
2418 IPv6Network('800::/5'), IPv6Network('1000::/4'),
2419 IPv6Network('4000::/3'), IPv6Network('6000::/3'),
2420 IPv6Network('8000::/3'), IPv6Network('A000::/3'),
2421 IPv6Network('C000::/3'), IPv6Network('E000::/4'),
2422 IPv6Network('F000::/5'), IPv6Network('F800::/6'),
2423 IPv6Network('FE00::/9'),
2424 ]
2425
2426 _sitelocal_network = IPv6Network('fec0::/10')
2427
2428
2429 IPv6Address._constants = _IPv6Constants
2430 IPv6Network._constants = _IPv6Constants