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 _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
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    def __reduce__(self):
536        return self.__class__, (str(self),)
537
538
539@functools.total_ordering
540class _BaseAddress(_IPAddressBase):
541
542    """A generic IP object.
543
544    This IP class contains the version independent methods which are
545    used by single IP addresses.
546    """
547
548    __slots__ = ()
549
550    def __int__(self):
551        return self._ip
552
553    def __eq__(self, other):
554        try:
555            return (self._ip == other._ip
556                    and self._version == other._version)
557        except AttributeError:
558            return NotImplemented
559
560    def __lt__(self, other):
561        if not isinstance(other, _BaseAddress):
562            return NotImplemented
563        if self._version != other._version:
564            raise TypeError('%s and %s are not of the same version' % (
565                             self, other))
566        if self._ip != other._ip:
567            return self._ip < other._ip
568        return False
569
570    # Shorthand for Integer addition and subtraction. This is not
571    # meant to ever support addition/subtraction of addresses.
572    def __add__(self, other):
573        if not isinstance(other, int):
574            return NotImplemented
575        return self.__class__(int(self) + other)
576
577    def __sub__(self, other):
578        if not isinstance(other, int):
579            return NotImplemented
580        return self.__class__(int(self) - other)
581
582    def __repr__(self):
583        return '%s(%r)' % (self.__class__.__name__, str(self))
584
585    def __str__(self):
586        return str(self._string_from_ip_int(self._ip))
587
588    def __hash__(self):
589        return hash(hex(int(self._ip)))
590
591    def _get_address_key(self):
592        return (self._version, self)
593
594    def __reduce__(self):
595        return self.__class__, (self._ip,)
596
597
598@functools.total_ordering
599class _BaseNetwork(_IPAddressBase):
600
601    """A generic IP network object.
602
603    This IP class contains the version independent methods which are
604    used by networks.
605
606    """
607    def __init__(self, address):
608        self._cache = {}
609
610    def __repr__(self):
611        return '%s(%r)' % (self.__class__.__name__, str(self))
612
613    def __str__(self):
614        return '%s/%d' % (self.network_address, self.prefixlen)
615
616    def hosts(self):
617        """Generate Iterator over usable hosts in a network.
618
619        This is like __iter__ except it doesn't return the network
620        or broadcast addresses.
621
622        """
623        network = int(self.network_address)
624        broadcast = int(self.broadcast_address)
625        for x in range(network + 1, broadcast):
626            yield self._address_class(x)
627
628    def __iter__(self):
629        network = int(self.network_address)
630        broadcast = int(self.broadcast_address)
631        for x in range(network, broadcast + 1):
632            yield self._address_class(x)
633
634    def __getitem__(self, n):
635        network = int(self.network_address)
636        broadcast = int(self.broadcast_address)
637        if n >= 0:
638            if network + n > broadcast:
639                raise IndexError('address out of range')
640            return self._address_class(network + n)
641        else:
642            n += 1
643            if broadcast + n < network:
644                raise IndexError('address out of range')
645            return self._address_class(broadcast + n)
646
647    def __lt__(self, other):
648        if not isinstance(other, _BaseNetwork):
649            return NotImplemented
650        if self._version != other._version:
651            raise TypeError('%s and %s are not of the same version' % (
652                             self, other))
653        if self.network_address != other.network_address:
654            return self.network_address < other.network_address
655        if self.netmask != other.netmask:
656            return self.netmask < other.netmask
657        return False
658
659    def __eq__(self, other):
660        try:
661            return (self._version == other._version and
662                    self.network_address == other.network_address and
663                    int(self.netmask) == int(other.netmask))
664        except AttributeError:
665            return NotImplemented
666
667    def __hash__(self):
668        return hash(int(self.network_address) ^ int(self.netmask))
669
670    def __contains__(self, other):
671        # always false if one is v4 and the other is v6.
672        if self._version != other._version:
673            return False
674        # dealing with another network.
675        if isinstance(other, _BaseNetwork):
676            return False
677        # dealing with another address
678        else:
679            # address
680            return (int(self.network_address) <= int(other._ip) <=
681                    int(self.broadcast_address))
682
683    def overlaps(self, other):
684        """Tell if self is partly contained in other."""
685        return self.network_address in other or (
686            self.broadcast_address in other or (
687                other.network_address in self or (
688                    other.broadcast_address in self)))
689
690    @property
691    def broadcast_address(self):
692        x = self._cache.get('broadcast_address')
693        if x is None:
694            x = self._address_class(int(self.network_address) |
695                                    int(self.hostmask))
696            self._cache['broadcast_address'] = x
697        return x
698
699    @property
700    def hostmask(self):
701        x = self._cache.get('hostmask')
702        if x is None:
703            x = self._address_class(int(self.netmask) ^ self._ALL_ONES)
704            self._cache['hostmask'] = x
705        return x
706
707    @property
708    def with_prefixlen(self):
709        return '%s/%d' % (self.network_address, self._prefixlen)
710
711    @property
712    def with_netmask(self):
713        return '%s/%s' % (self.network_address, self.netmask)
714
715    @property
716    def with_hostmask(self):
717        return '%s/%s' % (self.network_address, self.hostmask)
718
719    @property
720    def num_addresses(self):
721        """Number of hosts in the current subnet."""
722        return int(self.broadcast_address) - int(self.network_address) + 1
723
724    @property
725    def _address_class(self):
726        # Returning bare address objects (rather than interfaces) allows for
727        # more consistent behaviour across the network address, broadcast
728        # address and individual host addresses.
729        msg = '%200s has no associated address class' % (type(self),)
730        raise NotImplementedError(msg)
731
732    @property
733    def prefixlen(self):
734        return self._prefixlen
735
736    def address_exclude(self, other):
737        """Remove an address from a larger block.
738
739        For example:
740
741            addr1 = ip_network('192.0.2.0/28')
742            addr2 = ip_network('192.0.2.1/32')
743            list(addr1.address_exclude(addr2)) =
744                [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
745                 IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
746
747        or IPv6:
748
749            addr1 = ip_network('2001:db8::1/32')
750            addr2 = ip_network('2001:db8::1/128')
751            list(addr1.address_exclude(addr2)) =
752                [ip_network('2001:db8::1/128'),
753                 ip_network('2001:db8::2/127'),
754                 ip_network('2001:db8::4/126'),
755                 ip_network('2001:db8::8/125'),
756                 ...
757                 ip_network('2001:db8:8000::/33')]
758
759        Args:
760            other: An IPv4Network or IPv6Network object of the same type.
761
762        Returns:
763            An iterator of the IPv(4|6)Network objects which is self
764            minus other.
765
766        Raises:
767            TypeError: If self and other are of differing address
768              versions, or if other is not a network object.
769            ValueError: If other is not completely contained by self.
770
771        """
772        if not self._version == other._version:
773            raise TypeError("%s and %s are not of the same version" % (
774                             self, other))
775
776        if not isinstance(other, _BaseNetwork):
777            raise TypeError("%s is not a network object" % other)
778
779        if not other.subnet_of(self):
780            raise ValueError('%s not contained in %s' % (other, self))
781        if other == self:
782            return
783
784        # Make sure we're comparing the network of other.
785        other = other.__class__('%s/%s' % (other.network_address,
786                                           other.prefixlen))
787
788        s1, s2 = self.subnets()
789        while s1 != other and s2 != other:
790            if other.subnet_of(s1):
791                yield s2
792                s1, s2 = s1.subnets()
793            elif other.subnet_of(s2):
794                yield s1
795                s1, s2 = s2.subnets()
796            else:
797                # If we got here, there's a bug somewhere.
798                raise AssertionError('Error performing exclusion: '
799                                     's1: %s s2: %s other: %s' %
800                                     (s1, s2, other))
801        if s1 == other:
802            yield s2
803        elif s2 == other:
804            yield s1
805        else:
806            # If we got here, there's a bug somewhere.
807            raise AssertionError('Error performing exclusion: '
808                                 's1: %s s2: %s other: %s' %
809                                 (s1, s2, other))
810
811    def compare_networks(self, other):
812        """Compare two IP objects.
813
814        This is only concerned about the comparison of the integer
815        representation of the network addresses.  This means that the
816        host bits aren't considered at all in this method.  If you want
817        to compare host bits, you can easily enough do a
818        'HostA._ip < HostB._ip'
819
820        Args:
821            other: An IP object.
822
823        Returns:
824            If the IP versions of self and other are the same, returns:
825
826            -1 if self < other:
827              eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
828              IPv6Network('2001:db8::1000/124') <
829                  IPv6Network('2001:db8::2000/124')
830            0 if self == other
831              eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
832              IPv6Network('2001:db8::1000/124') ==
833                  IPv6Network('2001:db8::1000/124')
834            1 if self > other
835              eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
836                  IPv6Network('2001:db8::2000/124') >
837                      IPv6Network('2001:db8::1000/124')
838
839          Raises:
840              TypeError if the IP versions are different.
841
842        """
843        # does this need to raise a ValueError?
844        if self._version != other._version:
845            raise TypeError('%s and %s are not of the same type' % (
846                             self, other))
847        # self._version == other._version below here:
848        if self.network_address < other.network_address:
849            return -1
850        if self.network_address > other.network_address:
851            return 1
852        # self.network_address == other.network_address below here:
853        if self.netmask < other.netmask:
854            return -1
855        if self.netmask > other.netmask:
856            return 1
857        return 0
858
859    def _get_networks_key(self):
860        """Network-only key function.
861
862        Returns an object that identifies this address' network and
863        netmask. This function is a suitable "key" argument for sorted()
864        and list.sort().
865
866        """
867        return (self._version, self.network_address, self.netmask)
868
869    def subnets(self, prefixlen_diff=1, new_prefix=None):
870        """The subnets which join to make the current subnet.
871
872        In the case that self contains only one IP
873        (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
874        for IPv6), yield an iterator with just ourself.
875
876        Args:
877            prefixlen_diff: An integer, the amount the prefix length
878              should be increased by. This should not be set if
879              new_prefix is also set.
880            new_prefix: The desired new prefix length. This must be a
881              larger number (smaller prefix) than the existing prefix.
882              This should not be set if prefixlen_diff is also set.
883
884        Returns:
885            An iterator of IPv(4|6) objects.
886
887        Raises:
888            ValueError: The prefixlen_diff is too small or too large.
889                OR
890            prefixlen_diff and new_prefix are both set or new_prefix
891              is a smaller number than the current prefix (smaller
892              number means a larger network)
893
894        """
895        if self._prefixlen == self._max_prefixlen:
896            yield self
897            return
898
899        if new_prefix is not None:
900            if new_prefix < self._prefixlen:
901                raise ValueError('new prefix must be longer')
902            if prefixlen_diff != 1:
903                raise ValueError('cannot set prefixlen_diff and new_prefix')
904            prefixlen_diff = new_prefix - self._prefixlen
905
906        if prefixlen_diff < 0:
907            raise ValueError('prefix length diff must be > 0')
908        new_prefixlen = self._prefixlen + prefixlen_diff
909
910        if new_prefixlen > self._max_prefixlen:
911            raise ValueError(
912                'prefix length diff %d is invalid for netblock %s' % (
913                    new_prefixlen, self))
914
915        start = int(self.network_address)
916        end = int(self.broadcast_address) + 1
917        step = (int(self.hostmask) + 1) >> prefixlen_diff
918        for new_addr in range(start, end, step):
919            current = self.__class__((new_addr, new_prefixlen))
920            yield current
921
922    def supernet(self, prefixlen_diff=1, new_prefix=None):
923        """The supernet containing the current network.
924
925        Args:
926            prefixlen_diff: An integer, the amount the prefix length of
927              the network should be decreased by.  For example, given a
928              /24 network and a prefixlen_diff of 3, a supernet with a
929              /21 netmask is returned.
930
931        Returns:
932            An IPv4 network object.
933
934        Raises:
935            ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
936              a negative prefix length.
937                OR
938            If prefixlen_diff and new_prefix are both set or new_prefix is a
939              larger number than the current prefix (larger number means a
940              smaller network)
941
942        """
943        if self._prefixlen == 0:
944            return self
945
946        if new_prefix is not None:
947            if new_prefix > self._prefixlen:
948                raise ValueError('new prefix must be shorter')
949            if prefixlen_diff != 1:
950                raise ValueError('cannot set prefixlen_diff and new_prefix')
951            prefixlen_diff = self._prefixlen - new_prefix
952
953        new_prefixlen = self.prefixlen - prefixlen_diff
954        if new_prefixlen < 0:
955            raise ValueError(
956                'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
957                (self.prefixlen, prefixlen_diff))
958        return self.__class__((
959            int(self.network_address) & (int(self.netmask) << prefixlen_diff),
960            new_prefixlen
961            ))
962
963    @property
964    def is_multicast(self):
965        """Test if the address is reserved for multicast use.
966
967        Returns:
968            A boolean, True if the address is a multicast address.
969            See RFC 2373 2.7 for details.
970
971        """
972        return (self.network_address.is_multicast and
973                self.broadcast_address.is_multicast)
974
975    @staticmethod
976    def _is_subnet_of(a, b):
977        try:
978            # Always false if one is v4 and the other is v6.
979            if a._version != b._version:
980                raise TypeError(f"{a} and {b} are not of the same version")
981            return (b.network_address <= a.network_address and
982                    b.broadcast_address >= a.broadcast_address)
983        except AttributeError:
984            raise TypeError(f"Unable to test subnet containment "
985                            f"between {a} and {b}")
986
987    def subnet_of(self, other):
988        """Return True if this network is a subnet of other."""
989        return self._is_subnet_of(self, other)
990
991    def supernet_of(self, other):
992        """Return True if this network is a supernet of other."""
993        return self._is_subnet_of(other, self)
994
995    @property
996    def is_reserved(self):
997        """Test if the address is otherwise IETF reserved.
998
999        Returns:
1000            A boolean, True if the address is within one of the
1001            reserved IPv6 Network ranges.
1002
1003        """
1004        return (self.network_address.is_reserved and
1005                self.broadcast_address.is_reserved)
1006
1007    @property
1008    def is_link_local(self):
1009        """Test if the address is reserved for link-local.
1010
1011        Returns:
1012            A boolean, True if the address is reserved per RFC 4291.
1013
1014        """
1015        return (self.network_address.is_link_local and
1016                self.broadcast_address.is_link_local)
1017
1018    @property
1019    def is_private(self):
1020        """Test if this address is allocated for private networks.
1021
1022        Returns:
1023            A boolean, True if the address is reserved per
1024            iana-ipv4-special-registry or iana-ipv6-special-registry.
1025
1026        """
1027        return (self.network_address.is_private and
1028                self.broadcast_address.is_private)
1029
1030    @property
1031    def is_global(self):
1032        """Test if this address is allocated for public networks.
1033
1034        Returns:
1035            A boolean, True if the address is not reserved per
1036            iana-ipv4-special-registry or iana-ipv6-special-registry.
1037
1038        """
1039        return not self.is_private
1040
1041    @property
1042    def is_unspecified(self):
1043        """Test if the address is unspecified.
1044
1045        Returns:
1046            A boolean, True if this is the unspecified address as defined in
1047            RFC 2373 2.5.2.
1048
1049        """
1050        return (self.network_address.is_unspecified and
1051                self.broadcast_address.is_unspecified)
1052
1053    @property
1054    def is_loopback(self):
1055        """Test if the address is a loopback address.
1056
1057        Returns:
1058            A boolean, True if the address is a loopback address as defined in
1059            RFC 2373 2.5.3.
1060
1061        """
1062        return (self.network_address.is_loopback and
1063                self.broadcast_address.is_loopback)
1064
1065
1066class _BaseV4:
1067
1068    """Base IPv4 object.
1069
1070    The following methods are used by IPv4 objects in both single IP
1071    addresses and networks.
1072
1073    """
1074
1075    __slots__ = ()
1076    _version = 4
1077    # Equivalent to 255.255.255.255 or 32 bits of 1's.
1078    _ALL_ONES = (2**IPV4LENGTH) - 1
1079    _DECIMAL_DIGITS = frozenset('0123456789')
1080
1081    # the valid octets for host and netmasks. only useful for IPv4.
1082    _valid_mask_octets = frozenset({255, 254, 252, 248, 240, 224, 192, 128, 0})
1083
1084    _max_prefixlen = IPV4LENGTH
1085    # There are only a handful of valid v4 netmasks, so we cache them all
1086    # when constructed (see _make_netmask()).
1087    _netmask_cache = {}
1088
1089    def _explode_shorthand_ip_string(self):
1090        return str(self)
1091
1092    @classmethod
1093    def _make_netmask(cls, arg):
1094        """Make a (netmask, prefix_len) tuple from the given argument.
1095
1096        Argument can be:
1097        - an integer (the prefix length)
1098        - a string representing the prefix length (e.g. "24")
1099        - a string representing the prefix netmask (e.g. "255.255.255.0")
1100        """
1101        if arg not in cls._netmask_cache:
1102            if isinstance(arg, int):
1103                prefixlen = arg
1104            else:
1105                try:
1106                    # Check for a netmask in prefix length form
1107                    prefixlen = cls._prefix_from_prefix_string(arg)
1108                except NetmaskValueError:
1109                    # Check for a netmask or hostmask in dotted-quad form.
1110                    # This may raise NetmaskValueError.
1111                    prefixlen = cls._prefix_from_ip_string(arg)
1112            netmask = IPv4Address(cls._ip_int_from_prefix(prefixlen))
1113            cls._netmask_cache[arg] = netmask, prefixlen
1114        return cls._netmask_cache[arg]
1115
1116    @classmethod
1117    def _ip_int_from_string(cls, ip_str):
1118        """Turn the given IP string into an integer for comparison.
1119
1120        Args:
1121            ip_str: A string, the IP ip_str.
1122
1123        Returns:
1124            The IP ip_str as an integer.
1125
1126        Raises:
1127            AddressValueError: if ip_str isn't a valid IPv4 Address.
1128
1129        """
1130        if not ip_str:
1131            raise AddressValueError('Address cannot be empty')
1132
1133        octets = ip_str.split('.')
1134        if len(octets) != 4:
1135            raise AddressValueError("Expected 4 octets in %r" % ip_str)
1136
1137        try:
1138            return int.from_bytes(map(cls._parse_octet, octets), 'big')
1139        except ValueError as exc:
1140            raise AddressValueError("%s in %r" % (exc, ip_str)) from None
1141
1142    @classmethod
1143    def _parse_octet(cls, octet_str):
1144        """Convert a decimal octet into an integer.
1145
1146        Args:
1147            octet_str: A string, the number to parse.
1148
1149        Returns:
1150            The octet as an integer.
1151
1152        Raises:
1153            ValueError: if the octet isn't strictly a decimal from [0..255].
1154
1155        """
1156        if not octet_str:
1157            raise ValueError("Empty octet not permitted")
1158        # Whitelist the characters, since int() allows a lot of bizarre stuff.
1159        if not cls._DECIMAL_DIGITS.issuperset(octet_str):
1160            msg = "Only decimal digits permitted in %r"
1161            raise ValueError(msg % octet_str)
1162        # We do the length check second, since the invalid character error
1163        # is likely to be more informative for the user
1164        if len(octet_str) > 3:
1165            msg = "At most 3 characters permitted in %r"
1166            raise ValueError(msg % octet_str)
1167        # Convert to integer (we know digits are legal)
1168        octet_int = int(octet_str, 10)
1169        # Any octets that look like they *might* be written in octal,
1170        # and which don't look exactly the same in both octal and
1171        # decimal are rejected as ambiguous
1172        if octet_int > 7 and octet_str[0] == '0':
1173            msg = "Ambiguous (octal/decimal) value in %r not permitted"
1174            raise ValueError(msg % octet_str)
1175        if octet_int > 255:
1176            raise ValueError("Octet %d (> 255) not permitted" % octet_int)
1177        return octet_int
1178
1179    @classmethod
1180    def _string_from_ip_int(cls, ip_int):
1181        """Turns a 32-bit integer into dotted decimal notation.
1182
1183        Args:
1184            ip_int: An integer, the IP address.
1185
1186        Returns:
1187            The IP address as a string in dotted decimal notation.
1188
1189        """
1190        return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
1191
1192    def _is_valid_netmask(self, netmask):
1193        """Verify that the netmask is valid.
1194
1195        Args:
1196            netmask: A string, either a prefix or dotted decimal
1197              netmask.
1198
1199        Returns:
1200            A boolean, True if the prefix represents a valid IPv4
1201            netmask.
1202
1203        """
1204        mask = netmask.split('.')
1205        if len(mask) == 4:
1206            try:
1207                for x in mask:
1208                    if int(x) not in self._valid_mask_octets:
1209                        return False
1210            except ValueError:
1211                # Found something that isn't an integer or isn't valid
1212                return False
1213            for idx, y in enumerate(mask):
1214                if idx > 0 and y > mask[idx - 1]:
1215                    return False
1216            return True
1217        try:
1218            netmask = int(netmask)
1219        except ValueError:
1220            return False
1221        return 0 <= netmask <= self._max_prefixlen
1222
1223    def _is_hostmask(self, ip_str):
1224        """Test if the IP string is a hostmask (rather than a netmask).
1225
1226        Args:
1227            ip_str: A string, the potential hostmask.
1228
1229        Returns:
1230            A boolean, True if the IP string is a hostmask.
1231
1232        """
1233        bits = ip_str.split('.')
1234        try:
1235            parts = [x for x in map(int, bits) if x in self._valid_mask_octets]
1236        except ValueError:
1237            return False
1238        if len(parts) != len(bits):
1239            return False
1240        if parts[0] < parts[-1]:
1241            return True
1242        return False
1243
1244    def _reverse_pointer(self):
1245        """Return the reverse DNS pointer name for the IPv4 address.
1246
1247        This implements the method described in RFC1035 3.5.
1248
1249        """
1250        reverse_octets = str(self).split('.')[::-1]
1251        return '.'.join(reverse_octets) + '.in-addr.arpa'
1252
1253    @property
1254    def max_prefixlen(self):
1255        return self._max_prefixlen
1256
1257    @property
1258    def version(self):
1259        return self._version
1260
1261
1262class IPv4Address(_BaseV4, _BaseAddress):
1263
1264    """Represent and manipulate single IPv4 Addresses."""
1265
1266    __slots__ = ('_ip', '__weakref__')
1267
1268    def __init__(self, address):
1269
1270        """
1271        Args:
1272            address: A string or integer representing the IP
1273
1274              Additionally, an integer can be passed, so
1275              IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1276              or, more generally
1277              IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1278                IPv4Address('192.0.2.1')
1279
1280        Raises:
1281            AddressValueError: If ipaddress isn't a valid IPv4 address.
1282
1283        """
1284        # Efficient constructor from integer.
1285        if isinstance(address, int):
1286            self._check_int_address(address)
1287            self._ip = address
1288            return
1289
1290        # Constructing from a packed address
1291        if isinstance(address, bytes):
1292            self._check_packed_address(address, 4)
1293            self._ip = int.from_bytes(address, 'big')
1294            return
1295
1296        # Assume input argument to be string or any object representation
1297        # which converts into a formatted IP string.
1298        addr_str = str(address)
1299        if '/' in addr_str:
1300            raise AddressValueError("Unexpected '/' in %r" % address)
1301        self._ip = self._ip_int_from_string(addr_str)
1302
1303    @property
1304    def packed(self):
1305        """The binary representation of this address."""
1306        return v4_int_to_packed(self._ip)
1307
1308    @property
1309    def is_reserved(self):
1310        """Test if the address is otherwise IETF reserved.
1311
1312         Returns:
1313             A boolean, True if the address is within the
1314             reserved IPv4 Network range.
1315
1316        """
1317        return self in self._constants._reserved_network
1318
1319    @property
1320    @functools.lru_cache()
1321    def is_private(self):
1322        """Test if this address is allocated for private networks.
1323
1324        Returns:
1325            A boolean, True if the address is reserved per
1326            iana-ipv4-special-registry.
1327
1328        """
1329        return any(self in net for net in self._constants._private_networks)
1330
1331    @property
1332    @functools.lru_cache()
1333    def is_global(self):
1334        return self not in self._constants._public_network and not self.is_private
1335
1336    @property
1337    def is_multicast(self):
1338        """Test if the address is reserved for multicast use.
1339
1340        Returns:
1341            A boolean, True if the address is multicast.
1342            See RFC 3171 for details.
1343
1344        """
1345        return self in self._constants._multicast_network
1346
1347    @property
1348    def is_unspecified(self):
1349        """Test if the address is unspecified.
1350
1351        Returns:
1352            A boolean, True if this is the unspecified address as defined in
1353            RFC 5735 3.
1354
1355        """
1356        return self == self._constants._unspecified_address
1357
1358    @property
1359    def is_loopback(self):
1360        """Test if the address is a loopback address.
1361
1362        Returns:
1363            A boolean, True if the address is a loopback per RFC 3330.
1364
1365        """
1366        return self in self._constants._loopback_network
1367
1368    @property
1369    def is_link_local(self):
1370        """Test if the address is reserved for link-local.
1371
1372        Returns:
1373            A boolean, True if the address is link-local per RFC 3927.
1374
1375        """
1376        return self in self._constants._linklocal_network
1377
1378
1379class IPv4Interface(IPv4Address):
1380
1381    def __init__(self, address):
1382        if isinstance(address, (bytes, int)):
1383            IPv4Address.__init__(self, address)
1384            self.network = IPv4Network(self._ip)
1385            self._prefixlen = self._max_prefixlen
1386            return
1387
1388        if isinstance(address, tuple):
1389            IPv4Address.__init__(self, address[0])
1390            if len(address) > 1:
1391                self._prefixlen = int(address[1])
1392            else:
1393                self._prefixlen = self._max_prefixlen
1394
1395            self.network = IPv4Network(address, strict=False)
1396            self.netmask = self.network.netmask
1397            self.hostmask = self.network.hostmask
1398            return
1399
1400        addr = _split_optional_netmask(address)
1401        IPv4Address.__init__(self, addr[0])
1402
1403        self.network = IPv4Network(address, strict=False)
1404        self._prefixlen = self.network._prefixlen
1405
1406        self.netmask = self.network.netmask
1407        self.hostmask = self.network.hostmask
1408
1409    def __str__(self):
1410        return '%s/%d' % (self._string_from_ip_int(self._ip),
1411                          self.network.prefixlen)
1412
1413    def __eq__(self, other):
1414        address_equal = IPv4Address.__eq__(self, other)
1415        if not address_equal or address_equal is NotImplemented:
1416            return address_equal
1417        try:
1418            return self.network == other.network
1419        except AttributeError:
1420            # An interface with an associated network is NOT the
1421            # same as an unassociated address. That's why the hash
1422            # takes the extra info into account.
1423            return False
1424
1425    def __lt__(self, other):
1426        address_less = IPv4Address.__lt__(self, other)
1427        if address_less is NotImplemented:
1428            return NotImplemented
1429        try:
1430            return (self.network < other.network or
1431                    self.network == other.network and address_less)
1432        except AttributeError:
1433            # We *do* allow addresses and interfaces to be sorted. The
1434            # unassociated address is considered less than all interfaces.
1435            return False
1436
1437    def __hash__(self):
1438        return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1439
1440    __reduce__ = _IPAddressBase.__reduce__
1441
1442    @property
1443    def ip(self):
1444        return IPv4Address(self._ip)
1445
1446    @property
1447    def with_prefixlen(self):
1448        return '%s/%s' % (self._string_from_ip_int(self._ip),
1449                          self._prefixlen)
1450
1451    @property
1452    def with_netmask(self):
1453        return '%s/%s' % (self._string_from_ip_int(self._ip),
1454                          self.netmask)
1455
1456    @property
1457    def with_hostmask(self):
1458        return '%s/%s' % (self._string_from_ip_int(self._ip),
1459                          self.hostmask)
1460
1461
1462class IPv4Network(_BaseV4, _BaseNetwork):
1463
1464    """This class represents and manipulates 32-bit IPv4 network + addresses..
1465
1466    Attributes: [examples for IPv4Network('192.0.2.0/27')]
1467        .network_address: IPv4Address('192.0.2.0')
1468        .hostmask: IPv4Address('0.0.0.31')
1469        .broadcast_address: IPv4Address('192.0.2.32')
1470        .netmask: IPv4Address('255.255.255.224')
1471        .prefixlen: 27
1472
1473    """
1474    # Class to use when creating address objects
1475    _address_class = IPv4Address
1476
1477    def __init__(self, address, strict=True):
1478
1479        """Instantiate a new IPv4 network object.
1480
1481        Args:
1482            address: A string or integer representing the IP [& network].
1483              '192.0.2.0/24'
1484              '192.0.2.0/255.255.255.0'
1485              '192.0.0.2/0.0.0.255'
1486              are all functionally the same in IPv4. Similarly,
1487              '192.0.2.1'
1488              '192.0.2.1/255.255.255.255'
1489              '192.0.2.1/32'
1490              are also functionally equivalent. That is to say, failing to
1491              provide a subnetmask will create an object with a mask of /32.
1492
1493              If the mask (portion after the / in the argument) is given in
1494              dotted quad form, it is treated as a netmask if it starts with a
1495              non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1496              starts with a zero field (e.g. 0.255.255.255 == /8), with the
1497              single exception of an all-zero mask which is treated as a
1498              netmask == /0. If no mask is given, a default of /32 is used.
1499
1500              Additionally, an integer can be passed, so
1501              IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1502              or, more generally
1503              IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1504                IPv4Interface('192.0.2.1')
1505
1506        Raises:
1507            AddressValueError: If ipaddress isn't a valid IPv4 address.
1508            NetmaskValueError: If the netmask isn't valid for
1509              an IPv4 address.
1510            ValueError: If strict is True and a network address is not
1511              supplied.
1512
1513        """
1514        _BaseNetwork.__init__(self, address)
1515
1516        # Constructing from a packed address or integer
1517        if isinstance(address, (int, bytes)):
1518            addr = address
1519            mask = self._max_prefixlen
1520        # Constructing from a tuple (addr, [mask])
1521        elif isinstance(address, tuple):
1522            addr = address[0]
1523            mask = address[1] if len(address) > 1 else self._max_prefixlen
1524        # Assume input argument to be string or any object representation
1525        # which converts into a formatted IP prefix string.
1526        else:
1527            args = _split_optional_netmask(address)
1528            addr = self._ip_int_from_string(args[0])
1529            mask = args[1] if len(args) == 2 else self._max_prefixlen
1530
1531        self.network_address = IPv4Address(addr)
1532        self.netmask, self._prefixlen = self._make_netmask(mask)
1533        packed = int(self.network_address)
1534        if packed & int(self.netmask) != packed:
1535            if strict:
1536                raise ValueError('%s has host bits set' % self)
1537            else:
1538                self.network_address = IPv4Address(packed &
1539                                                   int(self.netmask))
1540
1541        if self._prefixlen == (self._max_prefixlen - 1):
1542            self.hosts = self.__iter__
1543
1544    @property
1545    @functools.lru_cache()
1546    def is_global(self):
1547        """Test if this address is allocated for public networks.
1548
1549        Returns:
1550            A boolean, True if the address is not reserved per
1551            iana-ipv4-special-registry.
1552
1553        """
1554        return (not (self.network_address in IPv4Network('100.64.0.0/10') and
1555                    self.broadcast_address in IPv4Network('100.64.0.0/10')) and
1556                not self.is_private)
1557
1558
1559class _IPv4Constants:
1560    _linklocal_network = IPv4Network('169.254.0.0/16')
1561
1562    _loopback_network = IPv4Network('127.0.0.0/8')
1563
1564    _multicast_network = IPv4Network('224.0.0.0/4')
1565
1566    _public_network = IPv4Network('100.64.0.0/10')
1567
1568    _private_networks = [
1569        IPv4Network('0.0.0.0/8'),
1570        IPv4Network('10.0.0.0/8'),
1571        IPv4Network('127.0.0.0/8'),
1572        IPv4Network('169.254.0.0/16'),
1573        IPv4Network('172.16.0.0/12'),
1574        IPv4Network('192.0.0.0/29'),
1575        IPv4Network('192.0.0.170/31'),
1576        IPv4Network('192.0.2.0/24'),
1577        IPv4Network('192.168.0.0/16'),
1578        IPv4Network('198.18.0.0/15'),
1579        IPv4Network('198.51.100.0/24'),
1580        IPv4Network('203.0.113.0/24'),
1581        IPv4Network('240.0.0.0/4'),
1582        IPv4Network('255.255.255.255/32'),
1583        ]
1584
1585    _reserved_network = IPv4Network('240.0.0.0/4')
1586
1587    _unspecified_address = IPv4Address('0.0.0.0')
1588
1589
1590IPv4Address._constants = _IPv4Constants
1591
1592
1593class _BaseV6:
1594
1595    """Base IPv6 object.
1596
1597    The following methods are used by IPv6 objects in both single IP
1598    addresses and networks.
1599
1600    """
1601
1602    __slots__ = ()
1603    _version = 6
1604    _ALL_ONES = (2**IPV6LENGTH) - 1
1605    _HEXTET_COUNT = 8
1606    _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
1607    _max_prefixlen = IPV6LENGTH
1608
1609    # There are only a bunch of valid v6 netmasks, so we cache them all
1610    # when constructed (see _make_netmask()).
1611    _netmask_cache = {}
1612
1613    @classmethod
1614    def _make_netmask(cls, arg):
1615        """Make a (netmask, prefix_len) tuple from the given argument.
1616
1617        Argument can be:
1618        - an integer (the prefix length)
1619        - a string representing the prefix length (e.g. "24")
1620        - a string representing the prefix netmask (e.g. "255.255.255.0")
1621        """
1622        if arg not in cls._netmask_cache:
1623            if isinstance(arg, int):
1624                prefixlen = arg
1625            else:
1626                prefixlen = cls._prefix_from_prefix_string(arg)
1627            netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen))
1628            cls._netmask_cache[arg] = netmask, prefixlen
1629        return cls._netmask_cache[arg]
1630
1631    @classmethod
1632    def _ip_int_from_string(cls, ip_str):
1633        """Turn an IPv6 ip_str into an integer.
1634
1635        Args:
1636            ip_str: A string, the IPv6 ip_str.
1637
1638        Returns:
1639            An int, the IPv6 address
1640
1641        Raises:
1642            AddressValueError: if ip_str isn't a valid IPv6 Address.
1643
1644        """
1645        if not ip_str:
1646            raise AddressValueError('Address cannot be empty')
1647
1648        parts = ip_str.split(':')
1649
1650        # An IPv6 address needs at least 2 colons (3 parts).
1651        _min_parts = 3
1652        if len(parts) < _min_parts:
1653            msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
1654            raise AddressValueError(msg)
1655
1656        # If the address has an IPv4-style suffix, convert it to hexadecimal.
1657        if '.' in parts[-1]:
1658            try:
1659                ipv4_int = IPv4Address(parts.pop())._ip
1660            except AddressValueError as exc:
1661                raise AddressValueError("%s in %r" % (exc, ip_str)) from None
1662            parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1663            parts.append('%x' % (ipv4_int & 0xFFFF))
1664
1665        # An IPv6 address can't have more than 8 colons (9 parts).
1666        # The extra colon comes from using the "::" notation for a single
1667        # leading or trailing zero part.
1668        _max_parts = cls._HEXTET_COUNT + 1
1669        if len(parts) > _max_parts:
1670            msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
1671            raise AddressValueError(msg)
1672
1673        # Disregarding the endpoints, find '::' with nothing in between.
1674        # This indicates that a run of zeroes has been skipped.
1675        skip_index = None
1676        for i in range(1, len(parts) - 1):
1677            if not parts[i]:
1678                if skip_index is not None:
1679                    # Can't have more than one '::'
1680                    msg = "At most one '::' permitted in %r" % ip_str
1681                    raise AddressValueError(msg)
1682                skip_index = i
1683
1684        # parts_hi is the number of parts to copy from above/before the '::'
1685        # parts_lo is the number of parts to copy from below/after the '::'
1686        if skip_index is not None:
1687            # If we found a '::', then check if it also covers the endpoints.
1688            parts_hi = skip_index
1689            parts_lo = len(parts) - skip_index - 1
1690            if not parts[0]:
1691                parts_hi -= 1
1692                if parts_hi:
1693                    msg = "Leading ':' only permitted as part of '::' in %r"
1694                    raise AddressValueError(msg % ip_str)  # ^: requires ^::
1695            if not parts[-1]:
1696                parts_lo -= 1
1697                if parts_lo:
1698                    msg = "Trailing ':' only permitted as part of '::' in %r"
1699                    raise AddressValueError(msg % ip_str)  # :$ requires ::$
1700            parts_skipped = cls._HEXTET_COUNT - (parts_hi + parts_lo)
1701            if parts_skipped < 1:
1702                msg = "Expected at most %d other parts with '::' in %r"
1703                raise AddressValueError(msg % (cls._HEXTET_COUNT-1, ip_str))
1704        else:
1705            # Otherwise, allocate the entire address to parts_hi.  The
1706            # endpoints could still be empty, but _parse_hextet() will check
1707            # for that.
1708            if len(parts) != cls._HEXTET_COUNT:
1709                msg = "Exactly %d parts expected without '::' in %r"
1710                raise AddressValueError(msg % (cls._HEXTET_COUNT, ip_str))
1711            if not parts[0]:
1712                msg = "Leading ':' only permitted as part of '::' in %r"
1713                raise AddressValueError(msg % ip_str)  # ^: requires ^::
1714            if not parts[-1]:
1715                msg = "Trailing ':' only permitted as part of '::' in %r"
1716                raise AddressValueError(msg % ip_str)  # :$ requires ::$
1717            parts_hi = len(parts)
1718            parts_lo = 0
1719            parts_skipped = 0
1720
1721        try:
1722            # Now, parse the hextets into a 128-bit integer.
1723            ip_int = 0
1724            for i in range(parts_hi):
1725                ip_int <<= 16
1726                ip_int |= cls._parse_hextet(parts[i])
1727            ip_int <<= 16 * parts_skipped
1728            for i in range(-parts_lo, 0):
1729                ip_int <<= 16
1730                ip_int |= cls._parse_hextet(parts[i])
1731            return ip_int
1732        except ValueError as exc:
1733            raise AddressValueError("%s in %r" % (exc, ip_str)) from None
1734
1735    @classmethod
1736    def _parse_hextet(cls, hextet_str):
1737        """Convert an IPv6 hextet string into an integer.
1738
1739        Args:
1740            hextet_str: A string, the number to parse.
1741
1742        Returns:
1743            The hextet as an integer.
1744
1745        Raises:
1746            ValueError: if the input isn't strictly a hex number from
1747              [0..FFFF].
1748
1749        """
1750        # Whitelist the characters, since int() allows a lot of bizarre stuff.
1751        if not cls._HEX_DIGITS.issuperset(hextet_str):
1752            raise ValueError("Only hex digits permitted in %r" % hextet_str)
1753        # We do the length check second, since the invalid character error
1754        # is likely to be more informative for the user
1755        if len(hextet_str) > 4:
1756            msg = "At most 4 characters permitted in %r"
1757            raise ValueError(msg % hextet_str)
1758        # Length check means we can skip checking the integer value
1759        return int(hextet_str, 16)
1760
1761    @classmethod
1762    def _compress_hextets(cls, hextets):
1763        """Compresses a list of hextets.
1764
1765        Compresses a list of strings, replacing the longest continuous
1766        sequence of "0" in the list with "" and adding empty strings at
1767        the beginning or at the end of the string such that subsequently
1768        calling ":".join(hextets) will produce the compressed version of
1769        the IPv6 address.
1770
1771        Args:
1772            hextets: A list of strings, the hextets to compress.
1773
1774        Returns:
1775            A list of strings.
1776
1777        """
1778        best_doublecolon_start = -1
1779        best_doublecolon_len = 0
1780        doublecolon_start = -1
1781        doublecolon_len = 0
1782        for index, hextet in enumerate(hextets):
1783            if hextet == '0':
1784                doublecolon_len += 1
1785                if doublecolon_start == -1:
1786                    # Start of a sequence of zeros.
1787                    doublecolon_start = index
1788                if doublecolon_len > best_doublecolon_len:
1789                    # This is the longest sequence of zeros so far.
1790                    best_doublecolon_len = doublecolon_len
1791                    best_doublecolon_start = doublecolon_start
1792            else:
1793                doublecolon_len = 0
1794                doublecolon_start = -1
1795
1796        if best_doublecolon_len > 1:
1797            best_doublecolon_end = (best_doublecolon_start +
1798                                    best_doublecolon_len)
1799            # For zeros at the end of the address.
1800            if best_doublecolon_end == len(hextets):
1801                hextets += ['']
1802            hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1803            # For zeros at the beginning of the address.
1804            if best_doublecolon_start == 0:
1805                hextets = [''] + hextets
1806
1807        return hextets
1808
1809    @classmethod
1810    def _string_from_ip_int(cls, ip_int=None):
1811        """Turns a 128-bit integer into hexadecimal notation.
1812
1813        Args:
1814            ip_int: An integer, the IP address.
1815
1816        Returns:
1817            A string, the hexadecimal representation of the address.
1818
1819        Raises:
1820            ValueError: The address is bigger than 128 bits of all ones.
1821
1822        """
1823        if ip_int is None:
1824            ip_int = int(cls._ip)
1825
1826        if ip_int > cls._ALL_ONES:
1827            raise ValueError('IPv6 address is too large')
1828
1829        hex_str = '%032x' % ip_int
1830        hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
1831
1832        hextets = cls._compress_hextets(hextets)
1833        return ':'.join(hextets)
1834
1835    def _explode_shorthand_ip_string(self):
1836        """Expand a shortened IPv6 address.
1837
1838        Args:
1839            ip_str: A string, the IPv6 address.
1840
1841        Returns:
1842            A string, the expanded IPv6 address.
1843
1844        """
1845        if isinstance(self, IPv6Network):
1846            ip_str = str(self.network_address)
1847        elif isinstance(self, IPv6Interface):
1848            ip_str = str(self.ip)
1849        else:
1850            ip_str = str(self)
1851
1852        ip_int = self._ip_int_from_string(ip_str)
1853        hex_str = '%032x' % ip_int
1854        parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
1855        if isinstance(self, (_BaseNetwork, IPv6Interface)):
1856            return '%s/%d' % (':'.join(parts), self._prefixlen)
1857        return ':'.join(parts)
1858
1859    def _reverse_pointer(self):
1860        """Return the reverse DNS pointer name for the IPv6 address.
1861
1862        This implements the method described in RFC3596 2.5.
1863
1864        """
1865        reverse_chars = self.exploded[::-1].replace(':', '')
1866        return '.'.join(reverse_chars) + '.ip6.arpa'
1867
1868    @property
1869    def max_prefixlen(self):
1870        return self._max_prefixlen
1871
1872    @property
1873    def version(self):
1874        return self._version
1875
1876
1877class IPv6Address(_BaseV6, _BaseAddress):
1878
1879    """Represent and manipulate single IPv6 Addresses."""
1880
1881    __slots__ = ('_ip', '__weakref__')
1882
1883    def __init__(self, address):
1884        """Instantiate a new IPv6 address object.
1885
1886        Args:
1887            address: A string or integer representing the IP
1888
1889              Additionally, an integer can be passed, so
1890              IPv6Address('2001:db8::') ==
1891                IPv6Address(42540766411282592856903984951653826560)
1892              or, more generally
1893              IPv6Address(int(IPv6Address('2001:db8::'))) ==
1894                IPv6Address('2001:db8::')
1895
1896        Raises:
1897            AddressValueError: If address isn't a valid IPv6 address.
1898
1899        """
1900        # Efficient constructor from integer.
1901        if isinstance(address, int):
1902            self._check_int_address(address)
1903            self._ip = address
1904            return
1905
1906        # Constructing from a packed address
1907        if isinstance(address, bytes):
1908            self._check_packed_address(address, 16)
1909            self._ip = int.from_bytes(address, 'big')
1910            return
1911
1912        # Assume input argument to be string or any object representation
1913        # which converts into a formatted IP string.
1914        addr_str = str(address)
1915        if '/' in addr_str:
1916            raise AddressValueError("Unexpected '/' in %r" % address)
1917        self._ip = self._ip_int_from_string(addr_str)
1918
1919    @property
1920    def packed(self):
1921        """The binary representation of this address."""
1922        return v6_int_to_packed(self._ip)
1923
1924    @property
1925    def is_multicast(self):
1926        """Test if the address is reserved for multicast use.
1927
1928        Returns:
1929            A boolean, True if the address is a multicast address.
1930            See RFC 2373 2.7 for details.
1931
1932        """
1933        return self in self._constants._multicast_network
1934
1935    @property
1936    def is_reserved(self):
1937        """Test if the address is otherwise IETF reserved.
1938
1939        Returns:
1940            A boolean, True if the address is within one of the
1941            reserved IPv6 Network ranges.
1942
1943        """
1944        return any(self in x for x in self._constants._reserved_networks)
1945
1946    @property
1947    def is_link_local(self):
1948        """Test if the address is reserved for link-local.
1949
1950        Returns:
1951            A boolean, True if the address is reserved per RFC 4291.
1952
1953        """
1954        return self in self._constants._linklocal_network
1955
1956    @property
1957    def is_site_local(self):
1958        """Test if the address is reserved for site-local.
1959
1960        Note that the site-local address space has been deprecated by RFC 3879.
1961        Use is_private to test if this address is in the space of unique local
1962        addresses as defined by RFC 4193.
1963
1964        Returns:
1965            A boolean, True if the address is reserved per RFC 3513 2.5.6.
1966
1967        """
1968        return self in self._constants._sitelocal_network
1969
1970    @property
1971    @functools.lru_cache()
1972    def is_private(self):
1973        """Test if this address is allocated for private networks.
1974
1975        Returns:
1976            A boolean, True if the address is reserved per
1977            iana-ipv6-special-registry.
1978
1979        """
1980        return any(self in net for net in self._constants._private_networks)
1981
1982    @property
1983    def is_global(self):
1984        """Test if this address is allocated for public networks.
1985
1986        Returns:
1987            A boolean, true if the address is not reserved per
1988            iana-ipv6-special-registry.
1989
1990        """
1991        return not self.is_private
1992
1993    @property
1994    def is_unspecified(self):
1995        """Test if the address is unspecified.
1996
1997        Returns:
1998            A boolean, True if this is the unspecified address as defined in
1999            RFC 2373 2.5.2.
2000
2001        """
2002        return self._ip == 0
2003
2004    @property
2005    def is_loopback(self):
2006        """Test if the address is a loopback address.
2007
2008        Returns:
2009            A boolean, True if the address is a loopback address as defined in
2010            RFC 2373 2.5.3.
2011
2012        """
2013        return self._ip == 1
2014
2015    @property
2016    def ipv4_mapped(self):
2017        """Return the IPv4 mapped address.
2018
2019        Returns:
2020            If the IPv6 address is a v4 mapped address, return the
2021            IPv4 mapped address. Return None otherwise.
2022
2023        """
2024        if (self._ip >> 32) != 0xFFFF:
2025            return None
2026        return IPv4Address(self._ip & 0xFFFFFFFF)
2027
2028    @property
2029    def teredo(self):
2030        """Tuple of embedded teredo IPs.
2031
2032        Returns:
2033            Tuple of the (server, client) IPs or None if the address
2034            doesn't appear to be a teredo address (doesn't start with
2035            2001::/32)
2036
2037        """
2038        if (self._ip >> 96) != 0x20010000:
2039            return None
2040        return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
2041                IPv4Address(~self._ip & 0xFFFFFFFF))
2042
2043    @property
2044    def sixtofour(self):
2045        """Return the IPv4 6to4 embedded address.
2046
2047        Returns:
2048            The IPv4 6to4-embedded address if present or None if the
2049            address doesn't appear to contain a 6to4 embedded address.
2050
2051        """
2052        if (self._ip >> 112) != 0x2002:
2053            return None
2054        return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
2055
2056
2057class IPv6Interface(IPv6Address):
2058
2059    def __init__(self, address):
2060        if isinstance(address, (bytes, int)):
2061            IPv6Address.__init__(self, address)
2062            self.network = IPv6Network(self._ip)
2063            self._prefixlen = self._max_prefixlen
2064            return
2065        if isinstance(address, tuple):
2066            IPv6Address.__init__(self, address[0])
2067            if len(address) > 1:
2068                self._prefixlen = int(address[1])
2069            else:
2070                self._prefixlen = self._max_prefixlen
2071            self.network = IPv6Network(address, strict=False)
2072            self.netmask = self.network.netmask
2073            self.hostmask = self.network.hostmask
2074            return
2075
2076        addr = _split_optional_netmask(address)
2077        IPv6Address.__init__(self, addr[0])
2078        self.network = IPv6Network(address, strict=False)
2079        self.netmask = self.network.netmask
2080        self._prefixlen = self.network._prefixlen
2081        self.hostmask = self.network.hostmask
2082
2083    def __str__(self):
2084        return '%s/%d' % (self._string_from_ip_int(self._ip),
2085                          self.network.prefixlen)
2086
2087    def __eq__(self, other):
2088        address_equal = IPv6Address.__eq__(self, other)
2089        if not address_equal or address_equal is NotImplemented:
2090            return address_equal
2091        try:
2092            return self.network == other.network
2093        except AttributeError:
2094            # An interface with an associated network is NOT the
2095            # same as an unassociated address. That's why the hash
2096            # takes the extra info into account.
2097            return False
2098
2099    def __lt__(self, other):
2100        address_less = IPv6Address.__lt__(self, other)
2101        if address_less is NotImplemented:
2102            return NotImplemented
2103        try:
2104            return (self.network < other.network or
2105                    self.network == other.network and address_less)
2106        except AttributeError:
2107            # We *do* allow addresses and interfaces to be sorted. The
2108            # unassociated address is considered less than all interfaces.
2109            return False
2110
2111    def __hash__(self):
2112        return self._ip ^ self._prefixlen ^ int(self.network.network_address)
2113
2114    __reduce__ = _IPAddressBase.__reduce__
2115
2116    @property
2117    def ip(self):
2118        return IPv6Address(self._ip)
2119
2120    @property
2121    def with_prefixlen(self):
2122        return '%s/%s' % (self._string_from_ip_int(self._ip),
2123                          self._prefixlen)
2124
2125    @property
2126    def with_netmask(self):
2127        return '%s/%s' % (self._string_from_ip_int(self._ip),
2128                          self.netmask)
2129
2130    @property
2131    def with_hostmask(self):
2132        return '%s/%s' % (self._string_from_ip_int(self._ip),
2133                          self.hostmask)
2134
2135    @property
2136    def is_unspecified(self):
2137        return self._ip == 0 and self.network.is_unspecified
2138
2139    @property
2140    def is_loopback(self):
2141        return self._ip == 1 and self.network.is_loopback
2142
2143
2144class IPv6Network(_BaseV6, _BaseNetwork):
2145
2146    """This class represents and manipulates 128-bit IPv6 networks.
2147
2148    Attributes: [examples for IPv6('2001:db8::1000/124')]
2149        .network_address: IPv6Address('2001:db8::1000')
2150        .hostmask: IPv6Address('::f')
2151        .broadcast_address: IPv6Address('2001:db8::100f')
2152        .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
2153        .prefixlen: 124
2154
2155    """
2156
2157    # Class to use when creating address objects
2158    _address_class = IPv6Address
2159
2160    def __init__(self, address, strict=True):
2161        """Instantiate a new IPv6 Network object.
2162
2163        Args:
2164            address: A string or integer representing the IPv6 network or the
2165              IP and prefix/netmask.
2166              '2001:db8::/128'
2167              '2001:db8:0000:0000:0000:0000:0000:0000/128'
2168              '2001:db8::'
2169              are all functionally the same in IPv6.  That is to say,
2170              failing to provide a subnetmask will create an object with
2171              a mask of /128.
2172
2173              Additionally, an integer can be passed, so
2174              IPv6Network('2001:db8::') ==
2175                IPv6Network(42540766411282592856903984951653826560)
2176              or, more generally
2177              IPv6Network(int(IPv6Network('2001:db8::'))) ==
2178                IPv6Network('2001:db8::')
2179
2180            strict: A boolean. If true, ensure that we have been passed
2181              A true network address, eg, 2001:db8::1000/124 and not an
2182              IP address on a network, eg, 2001:db8::1/124.
2183
2184        Raises:
2185            AddressValueError: If address isn't a valid IPv6 address.
2186            NetmaskValueError: If the netmask isn't valid for
2187              an IPv6 address.
2188            ValueError: If strict was True and a network address was not
2189              supplied.
2190
2191        """
2192        _BaseNetwork.__init__(self, address)
2193
2194        # Constructing from a packed address or integer
2195        if isinstance(address, (int, bytes)):
2196            addr = address
2197            mask = self._max_prefixlen
2198        # Constructing from a tuple (addr, [mask])
2199        elif isinstance(address, tuple):
2200            addr = address[0]
2201            mask = address[1] if len(address) > 1 else self._max_prefixlen
2202        # Assume input argument to be string or any object representation
2203        # which converts into a formatted IP prefix string.
2204        else:
2205            args = _split_optional_netmask(address)
2206            addr = self._ip_int_from_string(args[0])
2207            mask = args[1] if len(args) == 2 else self._max_prefixlen
2208
2209        self.network_address = IPv6Address(addr)
2210        self.netmask, self._prefixlen = self._make_netmask(mask)
2211        packed = int(self.network_address)
2212        if packed & int(self.netmask) != packed:
2213            if strict:
2214                raise ValueError('%s has host bits set' % self)
2215            else:
2216                self.network_address = IPv6Address(packed &
2217                                                   int(self.netmask))
2218
2219        if self._prefixlen == (self._max_prefixlen - 1):
2220            self.hosts = self.__iter__
2221
2222    def hosts(self):
2223        """Generate Iterator over usable hosts in a network.
2224
2225          This is like __iter__ except it doesn't return the
2226          Subnet-Router anycast address.
2227
2228        """
2229        network = int(self.network_address)
2230        broadcast = int(self.broadcast_address)
2231        for x in range(network + 1, broadcast + 1):
2232            yield self._address_class(x)
2233
2234    @property
2235    def is_site_local(self):
2236        """Test if the address is reserved for site-local.
2237
2238        Note that the site-local address space has been deprecated by RFC 3879.
2239        Use is_private to test if this address is in the space of unique local
2240        addresses as defined by RFC 4193.
2241
2242        Returns:
2243            A boolean, True if the address is reserved per RFC 3513 2.5.6.
2244
2245        """
2246        return (self.network_address.is_site_local and
2247                self.broadcast_address.is_site_local)
2248
2249
2250class _IPv6Constants:
2251
2252    _linklocal_network = IPv6Network('fe80::/10')
2253
2254    _multicast_network = IPv6Network('ff00::/8')
2255
2256    _private_networks = [
2257        IPv6Network('::1/128'),
2258        IPv6Network('::/128'),
2259        IPv6Network('::ffff:0:0/96'),
2260        IPv6Network('100::/64'),
2261        IPv6Network('2001::/23'),
2262        IPv6Network('2001:2::/48'),
2263        IPv6Network('2001:db8::/32'),
2264        IPv6Network('2001:10::/28'),
2265        IPv6Network('fc00::/7'),
2266        IPv6Network('fe80::/10'),
2267        ]
2268
2269    _reserved_networks = [
2270        IPv6Network('::/8'), IPv6Network('100::/8'),
2271        IPv6Network('200::/7'), IPv6Network('400::/6'),
2272        IPv6Network('800::/5'), IPv6Network('1000::/4'),
2273        IPv6Network('4000::/3'), IPv6Network('6000::/3'),
2274        IPv6Network('8000::/3'), IPv6Network('A000::/3'),
2275        IPv6Network('C000::/3'), IPv6Network('E000::/4'),
2276        IPv6Network('F000::/5'), IPv6Network('F800::/6'),
2277        IPv6Network('FE00::/9'),
2278    ]
2279
2280    _sitelocal_network = IPv6Network('fec0::/10')
2281
2282
2283IPv6Address._constants = _IPv6Constants
2284