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
6This library is used to create/poke/manipulate IPv4 and IPv6 addresses
7and networks.
8
9"""
10
11__version__ = '1.0'
12
13
14import functools
15
16IPV4LENGTH = 32
17IPV6LENGTH = 128
18
19
20class AddressValueError(ValueError):
21    """A Value Error related to the address."""
22
23
24class NetmaskValueError(ValueError):
25    """A Value Error related to the netmask."""
26
27
28def 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
57def 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
86def 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
120def 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
140def 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
156def _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
164def _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
184def _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
200def 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
255def _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
304def 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 iterator 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
358def 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
383class _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
564class _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
672class _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)
1090
1091    @property
1092    def is_global(self):
1093        """Test if this address is allocated for public networks.
1094
1095        Returns:
1096            A boolean, True if the address is not reserved per
1097            iana-ipv4-special-registry or iana-ipv6-special-registry.
1098
1099        """
1100        return not self.is_private
1101
1102    @property
1103    def is_unspecified(self):
1104        """Test if the address is unspecified.
1105
1106        Returns:
1107            A boolean, True if this is the unspecified address as defined in
1108            RFC 2373 2.5.2.
1109
1110        """
1111        return (self.network_address.is_unspecified and
1112                self.broadcast_address.is_unspecified)
1113
1114    @property
1115    def is_loopback(self):
1116        """Test if the address is a loopback address.
1117
1118        Returns:
1119            A boolean, True if the address is a loopback address as defined in
1120            RFC 2373 2.5.3.
1121
1122        """
1123        return (self.network_address.is_loopback and
1124                self.broadcast_address.is_loopback)
1125
1126
1127class _BaseConstants:
1128
1129    _private_networks = []
1130
1131
1132_BaseNetwork._constants = _BaseConstants
1133
1134
1135class _BaseV4:
1136
1137    """Base IPv4 object.
1138
1139    The following methods are used by IPv4 objects in both single IP
1140    addresses and networks.
1141
1142    """
1143
1144    __slots__ = ()
1145    _version = 4
1146    # Equivalent to 255.255.255.255 or 32 bits of 1's.
1147    _ALL_ONES = (2**IPV4LENGTH) - 1
1148
1149    _max_prefixlen = IPV4LENGTH
1150    # There are only a handful of valid v4 netmasks, so we cache them all
1151    # when constructed (see _make_netmask()).
1152    _netmask_cache = {}
1153
1154    def _explode_shorthand_ip_string(self):
1155        return str(self)
1156
1157    @classmethod
1158    def _make_netmask(cls, arg):
1159        """Make a (netmask, prefix_len) tuple from the given argument.
1160
1161        Argument can be:
1162        - an integer (the prefix length)
1163        - a string representing the prefix length (e.g. "24")
1164        - a string representing the prefix netmask (e.g. "255.255.255.0")
1165        """
1166        if arg not in cls._netmask_cache:
1167            if isinstance(arg, int):
1168                prefixlen = arg
1169                if not (0 <= prefixlen <= cls._max_prefixlen):
1170                    cls._report_invalid_netmask(prefixlen)
1171            else:
1172                try:
1173                    # Check for a netmask in prefix length form
1174                    prefixlen = cls._prefix_from_prefix_string(arg)
1175                except NetmaskValueError:
1176                    # Check for a netmask or hostmask in dotted-quad form.
1177                    # This may raise NetmaskValueError.
1178                    prefixlen = cls._prefix_from_ip_string(arg)
1179            netmask = IPv4Address(cls._ip_int_from_prefix(prefixlen))
1180            cls._netmask_cache[arg] = netmask, prefixlen
1181        return cls._netmask_cache[arg]
1182
1183    @classmethod
1184    def _ip_int_from_string(cls, ip_str):
1185        """Turn the given IP string into an integer for comparison.
1186
1187        Args:
1188            ip_str: A string, the IP ip_str.
1189
1190        Returns:
1191            The IP ip_str as an integer.
1192
1193        Raises:
1194            AddressValueError: if ip_str isn't a valid IPv4 Address.
1195
1196        """
1197        if not ip_str:
1198            raise AddressValueError('Address cannot be empty')
1199
1200        octets = ip_str.split('.')
1201        if len(octets) != 4:
1202            raise AddressValueError("Expected 4 octets in %r" % ip_str)
1203
1204        try:
1205            return int.from_bytes(map(cls._parse_octet, octets), 'big')
1206        except ValueError as exc:
1207            raise AddressValueError("%s in %r" % (exc, ip_str)) from None
1208
1209    @classmethod
1210    def _parse_octet(cls, octet_str):
1211        """Convert a decimal octet into an integer.
1212
1213        Args:
1214            octet_str: A string, the number to parse.
1215
1216        Returns:
1217            The octet as an integer.
1218
1219        Raises:
1220            ValueError: if the octet isn't strictly a decimal from [0..255].
1221
1222        """
1223        if not octet_str:
1224            raise ValueError("Empty octet not permitted")
1225        # Reject non-ASCII digits.
1226        if not (octet_str.isascii() and octet_str.isdigit()):
1227            msg = "Only decimal digits permitted in %r"
1228            raise ValueError(msg % octet_str)
1229        # We do the length check second, since the invalid character error
1230        # is likely to be more informative for the user
1231        if len(octet_str) > 3:
1232            msg = "At most 3 characters permitted in %r"
1233            raise ValueError(msg % octet_str)
1234        # Handle leading zeros as strict as glibc's inet_pton()
1235        # See security bug bpo-36384
1236        if octet_str != '0' and octet_str[0] == '0':
1237            msg = "Leading zeros are not permitted in %r"
1238            raise ValueError(msg % octet_str)
1239        # Convert to integer (we know digits are legal)
1240        octet_int = int(octet_str, 10)
1241        if octet_int > 255:
1242            raise ValueError("Octet %d (> 255) not permitted" % octet_int)
1243        return octet_int
1244
1245    @classmethod
1246    def _string_from_ip_int(cls, ip_int):
1247        """Turns a 32-bit integer into dotted decimal notation.
1248
1249        Args:
1250            ip_int: An integer, the IP address.
1251
1252        Returns:
1253            The IP address as a string in dotted decimal notation.
1254
1255        """
1256        return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
1257
1258    def _reverse_pointer(self):
1259        """Return the reverse DNS pointer name for the IPv4 address.
1260
1261        This implements the method described in RFC1035 3.5.
1262
1263        """
1264        reverse_octets = str(self).split('.')[::-1]
1265        return '.'.join(reverse_octets) + '.in-addr.arpa'
1266
1267    @property
1268    def max_prefixlen(self):
1269        return self._max_prefixlen
1270
1271    @property
1272    def version(self):
1273        return self._version
1274
1275
1276class IPv4Address(_BaseV4, _BaseAddress):
1277
1278    """Represent and manipulate single IPv4 Addresses."""
1279
1280    __slots__ = ('_ip', '__weakref__')
1281
1282    def __init__(self, address):
1283
1284        """
1285        Args:
1286            address: A string or integer representing the IP
1287
1288              Additionally, an integer can be passed, so
1289              IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1290              or, more generally
1291              IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1292                IPv4Address('192.0.2.1')
1293
1294        Raises:
1295            AddressValueError: If ipaddress isn't a valid IPv4 address.
1296
1297        """
1298        # Efficient constructor from integer.
1299        if isinstance(address, int):
1300            self._check_int_address(address)
1301            self._ip = address
1302            return
1303
1304        # Constructing from a packed address
1305        if isinstance(address, bytes):
1306            self._check_packed_address(address, 4)
1307            self._ip = int.from_bytes(address)  # big endian
1308            return
1309
1310        # Assume input argument to be string or any object representation
1311        # which converts into a formatted IP string.
1312        addr_str = str(address)
1313        if '/' in addr_str:
1314            raise AddressValueError(f"Unexpected '/' in {address!r}")
1315        self._ip = self._ip_int_from_string(addr_str)
1316
1317    @property
1318    def packed(self):
1319        """The binary representation of this address."""
1320        return v4_int_to_packed(self._ip)
1321
1322    @property
1323    def is_reserved(self):
1324        """Test if the address is otherwise IETF reserved.
1325
1326         Returns:
1327             A boolean, True if the address is within the
1328             reserved IPv4 Network range.
1329
1330        """
1331        return self in self._constants._reserved_network
1332
1333    @property
1334    @functools.lru_cache()
1335    def is_private(self):
1336        """Test if this address is allocated for private networks.
1337
1338        Returns:
1339            A boolean, True if the address is reserved per
1340            iana-ipv4-special-registry.
1341
1342        """
1343        return any(self in net for net in self._constants._private_networks)
1344
1345    @property
1346    @functools.lru_cache()
1347    def is_global(self):
1348        return self not in self._constants._public_network and not self.is_private
1349
1350    @property
1351    def is_multicast(self):
1352        """Test if the address is reserved for multicast use.
1353
1354        Returns:
1355            A boolean, True if the address is multicast.
1356            See RFC 3171 for details.
1357
1358        """
1359        return self in self._constants._multicast_network
1360
1361    @property
1362    def is_unspecified(self):
1363        """Test if the address is unspecified.
1364
1365        Returns:
1366            A boolean, True if this is the unspecified address as defined in
1367            RFC 5735 3.
1368
1369        """
1370        return self == self._constants._unspecified_address
1371
1372    @property
1373    def is_loopback(self):
1374        """Test if the address is a loopback address.
1375
1376        Returns:
1377            A boolean, True if the address is a loopback per RFC 3330.
1378
1379        """
1380        return self in self._constants._loopback_network
1381
1382    @property
1383    def is_link_local(self):
1384        """Test if the address is reserved for link-local.
1385
1386        Returns:
1387            A boolean, True if the address is link-local per RFC 3927.
1388
1389        """
1390        return self in self._constants._linklocal_network
1391
1392
1393class IPv4Interface(IPv4Address):
1394
1395    def __init__(self, address):
1396        addr, mask = self._split_addr_prefix(address)
1397
1398        IPv4Address.__init__(self, addr)
1399        self.network = IPv4Network((addr, mask), strict=False)
1400        self.netmask = self.network.netmask
1401        self._prefixlen = self.network._prefixlen
1402
1403    @functools.cached_property
1404    def hostmask(self):
1405        return self.network.hostmask
1406
1407    def __str__(self):
1408        return '%s/%d' % (self._string_from_ip_int(self._ip),
1409                          self._prefixlen)
1410
1411    def __eq__(self, other):
1412        address_equal = IPv4Address.__eq__(self, other)
1413        if address_equal is NotImplemented or not address_equal:
1414            return address_equal
1415        try:
1416            return self.network == other.network
1417        except AttributeError:
1418            # An interface with an associated network is NOT the
1419            # same as an unassociated address. That's why the hash
1420            # takes the extra info into account.
1421            return False
1422
1423    def __lt__(self, other):
1424        address_less = IPv4Address.__lt__(self, other)
1425        if address_less is NotImplemented:
1426            return NotImplemented
1427        try:
1428            return (self.network < other.network or
1429                    self.network == other.network and address_less)
1430        except AttributeError:
1431            # We *do* allow addresses and interfaces to be sorted. The
1432            # unassociated address is considered less than all interfaces.
1433            return False
1434
1435    def __hash__(self):
1436        return hash((self._ip, self._prefixlen, int(self.network.network_address)))
1437
1438    __reduce__ = _IPAddressBase.__reduce__
1439
1440    @property
1441    def ip(self):
1442        return IPv4Address(self._ip)
1443
1444    @property
1445    def with_prefixlen(self):
1446        return '%s/%s' % (self._string_from_ip_int(self._ip),
1447                          self._prefixlen)
1448
1449    @property
1450    def with_netmask(self):
1451        return '%s/%s' % (self._string_from_ip_int(self._ip),
1452                          self.netmask)
1453
1454    @property
1455    def with_hostmask(self):
1456        return '%s/%s' % (self._string_from_ip_int(self._ip),
1457                          self.hostmask)
1458
1459
1460class IPv4Network(_BaseV4, _BaseNetwork):
1461
1462    """This class represents and manipulates 32-bit IPv4 network + addresses..
1463
1464    Attributes: [examples for IPv4Network('192.0.2.0/27')]
1465        .network_address: IPv4Address('192.0.2.0')
1466        .hostmask: IPv4Address('0.0.0.31')
1467        .broadcast_address: IPv4Address('192.0.2.32')
1468        .netmask: IPv4Address('255.255.255.224')
1469        .prefixlen: 27
1470
1471    """
1472    # Class to use when creating address objects
1473    _address_class = IPv4Address
1474
1475    def __init__(self, address, strict=True):
1476        """Instantiate a new IPv4 network object.
1477
1478        Args:
1479            address: A string or integer representing the IP [& network].
1480              '192.0.2.0/24'
1481              '192.0.2.0/255.255.255.0'
1482              '192.0.2.0/0.0.0.255'
1483              are all functionally the same in IPv4. Similarly,
1484              '192.0.2.1'
1485              '192.0.2.1/255.255.255.255'
1486              '192.0.2.1/32'
1487              are also functionally equivalent. That is to say, failing to
1488              provide a subnetmask will create an object with a mask of /32.
1489
1490              If the mask (portion after the / in the argument) is given in
1491              dotted quad form, it is treated as a netmask if it starts with a
1492              non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1493              starts with a zero field (e.g. 0.255.255.255 == /8), with the
1494              single exception of an all-zero mask which is treated as a
1495              netmask == /0. If no mask is given, a default of /32 is used.
1496
1497              Additionally, an integer can be passed, so
1498              IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1499              or, more generally
1500              IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1501                IPv4Interface('192.0.2.1')
1502
1503        Raises:
1504            AddressValueError: If ipaddress isn't a valid IPv4 address.
1505            NetmaskValueError: If the netmask isn't valid for
1506              an IPv4 address.
1507            ValueError: If strict is True and a network address is not
1508              supplied.
1509        """
1510        addr, mask = self._split_addr_prefix(address)
1511
1512        self.network_address = IPv4Address(addr)
1513        self.netmask, self._prefixlen = self._make_netmask(mask)
1514        packed = int(self.network_address)
1515        if packed & int(self.netmask) != packed:
1516            if strict:
1517                raise ValueError('%s has host bits set' % self)
1518            else:
1519                self.network_address = IPv4Address(packed &
1520                                                   int(self.netmask))
1521
1522        if self._prefixlen == (self._max_prefixlen - 1):
1523            self.hosts = self.__iter__
1524        elif self._prefixlen == (self._max_prefixlen):
1525            self.hosts = lambda: [IPv4Address(addr)]
1526
1527    @property
1528    @functools.lru_cache()
1529    def is_global(self):
1530        """Test if this address is allocated for public networks.
1531
1532        Returns:
1533            A boolean, True if the address is not reserved per
1534            iana-ipv4-special-registry.
1535
1536        """
1537        return (not (self.network_address in IPv4Network('100.64.0.0/10') and
1538                    self.broadcast_address in IPv4Network('100.64.0.0/10')) and
1539                not self.is_private)
1540
1541
1542class _IPv4Constants:
1543    _linklocal_network = IPv4Network('169.254.0.0/16')
1544
1545    _loopback_network = IPv4Network('127.0.0.0/8')
1546
1547    _multicast_network = IPv4Network('224.0.0.0/4')
1548
1549    _public_network = IPv4Network('100.64.0.0/10')
1550
1551    _private_networks = [
1552        IPv4Network('0.0.0.0/8'),
1553        IPv4Network('10.0.0.0/8'),
1554        IPv4Network('127.0.0.0/8'),
1555        IPv4Network('169.254.0.0/16'),
1556        IPv4Network('172.16.0.0/12'),
1557        IPv4Network('192.0.0.0/29'),
1558        IPv4Network('192.0.0.170/31'),
1559        IPv4Network('192.0.2.0/24'),
1560        IPv4Network('192.168.0.0/16'),
1561        IPv4Network('198.18.0.0/15'),
1562        IPv4Network('198.51.100.0/24'),
1563        IPv4Network('203.0.113.0/24'),
1564        IPv4Network('240.0.0.0/4'),
1565        IPv4Network('255.255.255.255/32'),
1566        ]
1567
1568    _reserved_network = IPv4Network('240.0.0.0/4')
1569
1570    _unspecified_address = IPv4Address('0.0.0.0')
1571
1572
1573IPv4Address._constants = _IPv4Constants
1574IPv4Network._constants = _IPv4Constants
1575
1576
1577class _BaseV6:
1578
1579    """Base IPv6 object.
1580
1581    The following methods are used by IPv6 objects in both single IP
1582    addresses and networks.
1583
1584    """
1585
1586    __slots__ = ()
1587    _version = 6
1588    _ALL_ONES = (2**IPV6LENGTH) - 1
1589    _HEXTET_COUNT = 8
1590    _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
1591    _max_prefixlen = IPV6LENGTH
1592
1593    # There are only a bunch of valid v6 netmasks, so we cache them all
1594    # when constructed (see _make_netmask()).
1595    _netmask_cache = {}
1596
1597    @classmethod
1598    def _make_netmask(cls, arg):
1599        """Make a (netmask, prefix_len) tuple from the given argument.
1600
1601        Argument can be:
1602        - an integer (the prefix length)
1603        - a string representing the prefix length (e.g. "24")
1604        - a string representing the prefix netmask (e.g. "255.255.255.0")
1605        """
1606        if arg not in cls._netmask_cache:
1607            if isinstance(arg, int):
1608                prefixlen = arg
1609                if not (0 <= prefixlen <= cls._max_prefixlen):
1610                    cls._report_invalid_netmask(prefixlen)
1611            else:
1612                prefixlen = cls._prefix_from_prefix_string(arg)
1613            netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen))
1614            cls._netmask_cache[arg] = netmask, prefixlen
1615        return cls._netmask_cache[arg]
1616
1617    @classmethod
1618    def _ip_int_from_string(cls, ip_str):
1619        """Turn an IPv6 ip_str into an integer.
1620
1621        Args:
1622            ip_str: A string, the IPv6 ip_str.
1623
1624        Returns:
1625            An int, the IPv6 address
1626
1627        Raises:
1628            AddressValueError: if ip_str isn't a valid IPv6 Address.
1629
1630        """
1631        if not ip_str:
1632            raise AddressValueError('Address cannot be empty')
1633
1634        parts = ip_str.split(':')
1635
1636        # An IPv6 address needs at least 2 colons (3 parts).
1637        _min_parts = 3
1638        if len(parts) < _min_parts:
1639            msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
1640            raise AddressValueError(msg)
1641
1642        # If the address has an IPv4-style suffix, convert it to hexadecimal.
1643        if '.' in parts[-1]:
1644            try:
1645                ipv4_int = IPv4Address(parts.pop())._ip
1646            except AddressValueError as exc:
1647                raise AddressValueError("%s in %r" % (exc, ip_str)) from None
1648            parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1649            parts.append('%x' % (ipv4_int & 0xFFFF))
1650
1651        # An IPv6 address can't have more than 8 colons (9 parts).
1652        # The extra colon comes from using the "::" notation for a single
1653        # leading or trailing zero part.
1654        _max_parts = cls._HEXTET_COUNT + 1
1655        if len(parts) > _max_parts:
1656            msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
1657            raise AddressValueError(msg)
1658
1659        # Disregarding the endpoints, find '::' with nothing in between.
1660        # This indicates that a run of zeroes has been skipped.
1661        skip_index = None
1662        for i in range(1, len(parts) - 1):
1663            if not parts[i]:
1664                if skip_index is not None:
1665                    # Can't have more than one '::'
1666                    msg = "At most one '::' permitted in %r" % ip_str
1667                    raise AddressValueError(msg)
1668                skip_index = i
1669
1670        # parts_hi is the number of parts to copy from above/before the '::'
1671        # parts_lo is the number of parts to copy from below/after the '::'
1672        if skip_index is not None:
1673            # If we found a '::', then check if it also covers the endpoints.
1674            parts_hi = skip_index
1675            parts_lo = len(parts) - skip_index - 1
1676            if not parts[0]:
1677                parts_hi -= 1
1678                if parts_hi:
1679                    msg = "Leading ':' only permitted as part of '::' in %r"
1680                    raise AddressValueError(msg % ip_str)  # ^: requires ^::
1681            if not parts[-1]:
1682                parts_lo -= 1
1683                if parts_lo:
1684                    msg = "Trailing ':' only permitted as part of '::' in %r"
1685                    raise AddressValueError(msg % ip_str)  # :$ requires ::$
1686            parts_skipped = cls._HEXTET_COUNT - (parts_hi + parts_lo)
1687            if parts_skipped < 1:
1688                msg = "Expected at most %d other parts with '::' in %r"
1689                raise AddressValueError(msg % (cls._HEXTET_COUNT-1, ip_str))
1690        else:
1691            # Otherwise, allocate the entire address to parts_hi.  The
1692            # endpoints could still be empty, but _parse_hextet() will check
1693            # for that.
1694            if len(parts) != cls._HEXTET_COUNT:
1695                msg = "Exactly %d parts expected without '::' in %r"
1696                raise AddressValueError(msg % (cls._HEXTET_COUNT, ip_str))
1697            if not parts[0]:
1698                msg = "Leading ':' only permitted as part of '::' in %r"
1699                raise AddressValueError(msg % ip_str)  # ^: requires ^::
1700            if not parts[-1]:
1701                msg = "Trailing ':' only permitted as part of '::' in %r"
1702                raise AddressValueError(msg % ip_str)  # :$ requires ::$
1703            parts_hi = len(parts)
1704            parts_lo = 0
1705            parts_skipped = 0
1706
1707        try:
1708            # Now, parse the hextets into a 128-bit integer.
1709            ip_int = 0
1710            for i in range(parts_hi):
1711                ip_int <<= 16
1712                ip_int |= cls._parse_hextet(parts[i])
1713            ip_int <<= 16 * parts_skipped
1714            for i in range(-parts_lo, 0):
1715                ip_int <<= 16
1716                ip_int |= cls._parse_hextet(parts[i])
1717            return ip_int
1718        except ValueError as exc:
1719            raise AddressValueError("%s in %r" % (exc, ip_str)) from None
1720
1721    @classmethod
1722    def _parse_hextet(cls, hextet_str):
1723        """Convert an IPv6 hextet string into an integer.
1724
1725        Args:
1726            hextet_str: A string, the number to parse.
1727
1728        Returns:
1729            The hextet as an integer.
1730
1731        Raises:
1732            ValueError: if the input isn't strictly a hex number from
1733              [0..FFFF].
1734
1735        """
1736        # Reject non-ASCII digits.
1737        if not cls._HEX_DIGITS.issuperset(hextet_str):
1738            raise ValueError("Only hex digits permitted in %r" % hextet_str)
1739        # We do the length check second, since the invalid character error
1740        # is likely to be more informative for the user
1741        if len(hextet_str) > 4:
1742            msg = "At most 4 characters permitted in %r"
1743            raise ValueError(msg % hextet_str)
1744        # Length check means we can skip checking the integer value
1745        return int(hextet_str, 16)
1746
1747    @classmethod
1748    def _compress_hextets(cls, hextets):
1749        """Compresses a list of hextets.
1750
1751        Compresses a list of strings, replacing the longest continuous
1752        sequence of "0" in the list with "" and adding empty strings at
1753        the beginning or at the end of the string such that subsequently
1754        calling ":".join(hextets) will produce the compressed version of
1755        the IPv6 address.
1756
1757        Args:
1758            hextets: A list of strings, the hextets to compress.
1759
1760        Returns:
1761            A list of strings.
1762
1763        """
1764        best_doublecolon_start = -1
1765        best_doublecolon_len = 0
1766        doublecolon_start = -1
1767        doublecolon_len = 0
1768        for index, hextet in enumerate(hextets):
1769            if hextet == '0':
1770                doublecolon_len += 1
1771                if doublecolon_start == -1:
1772                    # Start of a sequence of zeros.
1773                    doublecolon_start = index
1774                if doublecolon_len > best_doublecolon_len:
1775                    # This is the longest sequence of zeros so far.
1776                    best_doublecolon_len = doublecolon_len
1777                    best_doublecolon_start = doublecolon_start
1778            else:
1779                doublecolon_len = 0
1780                doublecolon_start = -1
1781
1782        if best_doublecolon_len > 1:
1783            best_doublecolon_end = (best_doublecolon_start +
1784                                    best_doublecolon_len)
1785            # For zeros at the end of the address.
1786            if best_doublecolon_end == len(hextets):
1787                hextets += ['']
1788            hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1789            # For zeros at the beginning of the address.
1790            if best_doublecolon_start == 0:
1791                hextets = [''] + hextets
1792
1793        return hextets
1794
1795    @classmethod
1796    def _string_from_ip_int(cls, ip_int=None):
1797        """Turns a 128-bit integer into hexadecimal notation.
1798
1799        Args:
1800            ip_int: An integer, the IP address.
1801
1802        Returns:
1803            A string, the hexadecimal representation of the address.
1804
1805        Raises:
1806            ValueError: The address is bigger than 128 bits of all ones.
1807
1808        """
1809        if ip_int is None:
1810            ip_int = int(cls._ip)
1811
1812        if ip_int > cls._ALL_ONES:
1813            raise ValueError('IPv6 address is too large')
1814
1815        hex_str = '%032x' % ip_int
1816        hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
1817
1818        hextets = cls._compress_hextets(hextets)
1819        return ':'.join(hextets)
1820
1821    def _explode_shorthand_ip_string(self):
1822        """Expand a shortened IPv6 address.
1823
1824        Args:
1825            ip_str: A string, the IPv6 address.
1826
1827        Returns:
1828            A string, the expanded IPv6 address.
1829
1830        """
1831        if isinstance(self, IPv6Network):
1832            ip_str = str(self.network_address)
1833        elif isinstance(self, IPv6Interface):
1834            ip_str = str(self.ip)
1835        else:
1836            ip_str = str(self)
1837
1838        ip_int = self._ip_int_from_string(ip_str)
1839        hex_str = '%032x' % ip_int
1840        parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
1841        if isinstance(self, (_BaseNetwork, IPv6Interface)):
1842            return '%s/%d' % (':'.join(parts), self._prefixlen)
1843        return ':'.join(parts)
1844
1845    def _reverse_pointer(self):
1846        """Return the reverse DNS pointer name for the IPv6 address.
1847
1848        This implements the method described in RFC3596 2.5.
1849
1850        """
1851        reverse_chars = self.exploded[::-1].replace(':', '')
1852        return '.'.join(reverse_chars) + '.ip6.arpa'
1853
1854    @staticmethod
1855    def _split_scope_id(ip_str):
1856        """Helper function to parse IPv6 string address with scope id.
1857
1858        See RFC 4007 for details.
1859
1860        Args:
1861            ip_str: A string, the IPv6 address.
1862
1863        Returns:
1864            (addr, scope_id) tuple.
1865
1866        """
1867        addr, sep, scope_id = ip_str.partition('%')
1868        if not sep:
1869            scope_id = None
1870        elif not scope_id or '%' in scope_id:
1871            raise AddressValueError('Invalid IPv6 address: "%r"' % ip_str)
1872        return addr, scope_id
1873
1874    @property
1875    def max_prefixlen(self):
1876        return self._max_prefixlen
1877
1878    @property
1879    def version(self):
1880        return self._version
1881
1882
1883class IPv6Address(_BaseV6, _BaseAddress):
1884
1885    """Represent and manipulate single IPv6 Addresses."""
1886
1887    __slots__ = ('_ip', '_scope_id', '__weakref__')
1888
1889    def __init__(self, address):
1890        """Instantiate a new IPv6 address object.
1891
1892        Args:
1893            address: A string or integer representing the IP
1894
1895              Additionally, an integer can be passed, so
1896              IPv6Address('2001:db8::') ==
1897                IPv6Address(42540766411282592856903984951653826560)
1898              or, more generally
1899              IPv6Address(int(IPv6Address('2001:db8::'))) ==
1900                IPv6Address('2001:db8::')
1901
1902        Raises:
1903            AddressValueError: If address isn't a valid IPv6 address.
1904
1905        """
1906        # Efficient constructor from integer.
1907        if isinstance(address, int):
1908            self._check_int_address(address)
1909            self._ip = address
1910            self._scope_id = None
1911            return
1912
1913        # Constructing from a packed address
1914        if isinstance(address, bytes):
1915            self._check_packed_address(address, 16)
1916            self._ip = int.from_bytes(address, 'big')
1917            self._scope_id = None
1918            return
1919
1920        # Assume input argument to be string or any object representation
1921        # which converts into a formatted IP string.
1922        addr_str = str(address)
1923        if '/' in addr_str:
1924            raise AddressValueError(f"Unexpected '/' in {address!r}")
1925        addr_str, self._scope_id = self._split_scope_id(addr_str)
1926
1927        self._ip = self._ip_int_from_string(addr_str)
1928
1929    def __str__(self):
1930        ip_str = super().__str__()
1931        return ip_str + '%' + self._scope_id if self._scope_id else ip_str
1932
1933    def __hash__(self):
1934        return hash((self._ip, self._scope_id))
1935
1936    def __eq__(self, other):
1937        address_equal = super().__eq__(other)
1938        if address_equal is NotImplemented:
1939            return NotImplemented
1940        if not address_equal:
1941            return False
1942        return self._scope_id == getattr(other, '_scope_id', None)
1943
1944    @property
1945    def scope_id(self):
1946        """Identifier of a particular zone of the address's scope.
1947
1948        See RFC 4007 for details.
1949
1950        Returns:
1951            A string identifying the zone of the address if specified, else None.
1952
1953        """
1954        return self._scope_id
1955
1956    @property
1957    def packed(self):
1958        """The binary representation of this address."""
1959        return v6_int_to_packed(self._ip)
1960
1961    @property
1962    def is_multicast(self):
1963        """Test if the address is reserved for multicast use.
1964
1965        Returns:
1966            A boolean, True if the address is a multicast address.
1967            See RFC 2373 2.7 for details.
1968
1969        """
1970        return self in self._constants._multicast_network
1971
1972    @property
1973    def is_reserved(self):
1974        """Test if the address is otherwise IETF reserved.
1975
1976        Returns:
1977            A boolean, True if the address is within one of the
1978            reserved IPv6 Network ranges.
1979
1980        """
1981        return any(self in x for x in self._constants._reserved_networks)
1982
1983    @property
1984    def is_link_local(self):
1985        """Test if the address is reserved for link-local.
1986
1987        Returns:
1988            A boolean, True if the address is reserved per RFC 4291.
1989
1990        """
1991        return self in self._constants._linklocal_network
1992
1993    @property
1994    def is_site_local(self):
1995        """Test if the address is reserved for site-local.
1996
1997        Note that the site-local address space has been deprecated by RFC 3879.
1998        Use is_private to test if this address is in the space of unique local
1999        addresses as defined by RFC 4193.
2000
2001        Returns:
2002            A boolean, True if the address is reserved per RFC 3513 2.5.6.
2003
2004        """
2005        return self in self._constants._sitelocal_network
2006
2007    @property
2008    @functools.lru_cache()
2009    def is_private(self):
2010        """Test if this address is allocated for private networks.
2011
2012        Returns:
2013            A boolean, True if the address is reserved per
2014            iana-ipv6-special-registry, or is ipv4_mapped and is
2015            reserved in the iana-ipv4-special-registry.
2016
2017        """
2018        ipv4_mapped = self.ipv4_mapped
2019        if ipv4_mapped is not None:
2020            return ipv4_mapped.is_private
2021        return any(self in net for net in self._constants._private_networks)
2022
2023    @property
2024    def is_global(self):
2025        """Test if this address is allocated for public networks.
2026
2027        Returns:
2028            A boolean, true if the address is not reserved per
2029            iana-ipv6-special-registry.
2030
2031        """
2032        return not self.is_private
2033
2034    @property
2035    def is_unspecified(self):
2036        """Test if the address is unspecified.
2037
2038        Returns:
2039            A boolean, True if this is the unspecified address as defined in
2040            RFC 2373 2.5.2.
2041
2042        """
2043        return self._ip == 0
2044
2045    @property
2046    def is_loopback(self):
2047        """Test if the address is a loopback address.
2048
2049        Returns:
2050            A boolean, True if the address is a loopback address as defined in
2051            RFC 2373 2.5.3.
2052
2053        """
2054        return self._ip == 1
2055
2056    @property
2057    def ipv4_mapped(self):
2058        """Return the IPv4 mapped address.
2059
2060        Returns:
2061            If the IPv6 address is a v4 mapped address, return the
2062            IPv4 mapped address. Return None otherwise.
2063
2064        """
2065        if (self._ip >> 32) != 0xFFFF:
2066            return None
2067        return IPv4Address(self._ip & 0xFFFFFFFF)
2068
2069    @property
2070    def teredo(self):
2071        """Tuple of embedded teredo IPs.
2072
2073        Returns:
2074            Tuple of the (server, client) IPs or None if the address
2075            doesn't appear to be a teredo address (doesn't start with
2076            2001::/32)
2077
2078        """
2079        if (self._ip >> 96) != 0x20010000:
2080            return None
2081        return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
2082                IPv4Address(~self._ip & 0xFFFFFFFF))
2083
2084    @property
2085    def sixtofour(self):
2086        """Return the IPv4 6to4 embedded address.
2087
2088        Returns:
2089            The IPv4 6to4-embedded address if present or None if the
2090            address doesn't appear to contain a 6to4 embedded address.
2091
2092        """
2093        if (self._ip >> 112) != 0x2002:
2094            return None
2095        return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
2096
2097
2098class IPv6Interface(IPv6Address):
2099
2100    def __init__(self, address):
2101        addr, mask = self._split_addr_prefix(address)
2102
2103        IPv6Address.__init__(self, addr)
2104        self.network = IPv6Network((addr, mask), strict=False)
2105        self.netmask = self.network.netmask
2106        self._prefixlen = self.network._prefixlen
2107
2108    @functools.cached_property
2109    def hostmask(self):
2110        return self.network.hostmask
2111
2112    def __str__(self):
2113        return '%s/%d' % (super().__str__(),
2114                          self._prefixlen)
2115
2116    def __eq__(self, other):
2117        address_equal = IPv6Address.__eq__(self, other)
2118        if address_equal is NotImplemented or not address_equal:
2119            return address_equal
2120        try:
2121            return self.network == other.network
2122        except AttributeError:
2123            # An interface with an associated network is NOT the
2124            # same as an unassociated address. That's why the hash
2125            # takes the extra info into account.
2126            return False
2127
2128    def __lt__(self, other):
2129        address_less = IPv6Address.__lt__(self, other)
2130        if address_less is NotImplemented:
2131            return address_less
2132        try:
2133            return (self.network < other.network or
2134                    self.network == other.network and address_less)
2135        except AttributeError:
2136            # We *do* allow addresses and interfaces to be sorted. The
2137            # unassociated address is considered less than all interfaces.
2138            return False
2139
2140    def __hash__(self):
2141        return hash((self._ip, self._prefixlen, int(self.network.network_address)))
2142
2143    __reduce__ = _IPAddressBase.__reduce__
2144
2145    @property
2146    def ip(self):
2147        return IPv6Address(self._ip)
2148
2149    @property
2150    def with_prefixlen(self):
2151        return '%s/%s' % (self._string_from_ip_int(self._ip),
2152                          self._prefixlen)
2153
2154    @property
2155    def with_netmask(self):
2156        return '%s/%s' % (self._string_from_ip_int(self._ip),
2157                          self.netmask)
2158
2159    @property
2160    def with_hostmask(self):
2161        return '%s/%s' % (self._string_from_ip_int(self._ip),
2162                          self.hostmask)
2163
2164    @property
2165    def is_unspecified(self):
2166        return self._ip == 0 and self.network.is_unspecified
2167
2168    @property
2169    def is_loopback(self):
2170        return self._ip == 1 and self.network.is_loopback
2171
2172
2173class IPv6Network(_BaseV6, _BaseNetwork):
2174
2175    """This class represents and manipulates 128-bit IPv6 networks.
2176
2177    Attributes: [examples for IPv6('2001:db8::1000/124')]
2178        .network_address: IPv6Address('2001:db8::1000')
2179        .hostmask: IPv6Address('::f')
2180        .broadcast_address: IPv6Address('2001:db8::100f')
2181        .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
2182        .prefixlen: 124
2183
2184    """
2185
2186    # Class to use when creating address objects
2187    _address_class = IPv6Address
2188
2189    def __init__(self, address, strict=True):
2190        """Instantiate a new IPv6 Network object.
2191
2192        Args:
2193            address: A string or integer representing the IPv6 network or the
2194              IP and prefix/netmask.
2195              '2001:db8::/128'
2196              '2001:db8:0000:0000:0000:0000:0000:0000/128'
2197              '2001:db8::'
2198              are all functionally the same in IPv6.  That is to say,
2199              failing to provide a subnetmask will create an object with
2200              a mask of /128.
2201
2202              Additionally, an integer can be passed, so
2203              IPv6Network('2001:db8::') ==
2204                IPv6Network(42540766411282592856903984951653826560)
2205              or, more generally
2206              IPv6Network(int(IPv6Network('2001:db8::'))) ==
2207                IPv6Network('2001:db8::')
2208
2209            strict: A boolean. If true, ensure that we have been passed
2210              A true network address, eg, 2001:db8::1000/124 and not an
2211              IP address on a network, eg, 2001:db8::1/124.
2212
2213        Raises:
2214            AddressValueError: If address isn't a valid IPv6 address.
2215            NetmaskValueError: If the netmask isn't valid for
2216              an IPv6 address.
2217            ValueError: If strict was True and a network address was not
2218              supplied.
2219        """
2220        addr, mask = self._split_addr_prefix(address)
2221
2222        self.network_address = IPv6Address(addr)
2223        self.netmask, self._prefixlen = self._make_netmask(mask)
2224        packed = int(self.network_address)
2225        if packed & int(self.netmask) != packed:
2226            if strict:
2227                raise ValueError('%s has host bits set' % self)
2228            else:
2229                self.network_address = IPv6Address(packed &
2230                                                   int(self.netmask))
2231
2232        if self._prefixlen == (self._max_prefixlen - 1):
2233            self.hosts = self.__iter__
2234        elif self._prefixlen == self._max_prefixlen:
2235            self.hosts = lambda: [IPv6Address(addr)]
2236
2237    def hosts(self):
2238        """Generate Iterator over usable hosts in a network.
2239
2240          This is like __iter__ except it doesn't return the
2241          Subnet-Router anycast address.
2242
2243        """
2244        network = int(self.network_address)
2245        broadcast = int(self.broadcast_address)
2246        for x in range(network + 1, broadcast + 1):
2247            yield self._address_class(x)
2248
2249    @property
2250    def is_site_local(self):
2251        """Test if the address is reserved for site-local.
2252
2253        Note that the site-local address space has been deprecated by RFC 3879.
2254        Use is_private to test if this address is in the space of unique local
2255        addresses as defined by RFC 4193.
2256
2257        Returns:
2258            A boolean, True if the address is reserved per RFC 3513 2.5.6.
2259
2260        """
2261        return (self.network_address.is_site_local and
2262                self.broadcast_address.is_site_local)
2263
2264
2265class _IPv6Constants:
2266
2267    _linklocal_network = IPv6Network('fe80::/10')
2268
2269    _multicast_network = IPv6Network('ff00::/8')
2270
2271    _private_networks = [
2272        IPv6Network('::1/128'),
2273        IPv6Network('::/128'),
2274        IPv6Network('::ffff:0:0/96'),
2275        IPv6Network('100::/64'),
2276        IPv6Network('2001::/23'),
2277        IPv6Network('2001:2::/48'),
2278        IPv6Network('2001:db8::/32'),
2279        IPv6Network('2001:10::/28'),
2280        IPv6Network('fc00::/7'),
2281        IPv6Network('fe80::/10'),
2282        ]
2283
2284    _reserved_networks = [
2285        IPv6Network('::/8'), IPv6Network('100::/8'),
2286        IPv6Network('200::/7'), IPv6Network('400::/6'),
2287        IPv6Network('800::/5'), IPv6Network('1000::/4'),
2288        IPv6Network('4000::/3'), IPv6Network('6000::/3'),
2289        IPv6Network('8000::/3'), IPv6Network('A000::/3'),
2290        IPv6Network('C000::/3'), IPv6Network('E000::/4'),
2291        IPv6Network('F000::/5'), IPv6Network('F800::/6'),
2292        IPv6Network('FE00::/9'),
2293    ]
2294
2295    _sitelocal_network = IPv6Network('fec0::/10')
2296
2297
2298IPv6Address._constants = _IPv6Constants
2299IPv6Network._constants = _IPv6Constants
2300