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