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