1#!/usr/bin/python
2#
3# Copyright 2007 Google Inc.
4#  Licensed to PSF under a Contributor Agreement.
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10#      http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15# implied. See the License for the specific language governing
16# permissions and limitations under the License.
17
18"""A fast, lightweight IPv4/IPv6 manipulation library in Python.
19
20This library is used to create/poke/manipulate IPv4 and IPv6 addresses
21and networks.
22
23"""
24
25__version__ = '2.2.0'
26
27import struct
28import sys
29
30if sys.version_info > (3,):
31    long = int
32    xrange = range
33
34IPV4LENGTH = 32
35IPV6LENGTH = 128
36
37
38class AddressValueError(ValueError):
39    """A Value Error related to the address."""
40
41
42class NetmaskValueError(ValueError):
43    """A Value Error related to the netmask."""
44
45
46def IPAddress(address, version=None):
47    """Take an IP string/int and return an object of the correct type.
48
49    Args:
50        address: A string or integer, the IP address.  Either IPv4 or
51          IPv6 addresses may be supplied; integers less than 2**32 will
52          be considered to be IPv4 by default.
53        version: An Integer, 4 or 6. If set, don't try to automatically
54          determine what the IP address type is. important for things
55          like IPAddress(1), which could be IPv4, '0.0.0.1',  or IPv6,
56          '::1'.
57
58    Returns:
59        An IPv4Address or IPv6Address object.
60
61    Raises:
62        ValueError: if the string passed isn't either a v4 or a v6
63          address.
64
65    """
66    if version:
67        if version == 4:
68            return IPv4Address(address)
69        elif version == 6:
70            return IPv6Address(address)
71
72    try:
73        return IPv4Address(address)
74    except (AddressValueError, NetmaskValueError):
75        pass
76
77    try:
78        return IPv6Address(address)
79    except (AddressValueError, NetmaskValueError):
80        pass
81
82    raise ValueError('%r does not appear to be an IPv4 or IPv6 address' %
83                     address)
84
85
86def IPNetwork(address, version=None, strict=False):
87    """Take an IP string/int and return an object of the correct type.
88
89    Args:
90        address: A string or integer, the IP address.  Either IPv4 or
91          IPv6 addresses may be supplied; integers less than 2**32 will
92          be considered to be IPv4 by default.
93        version: An Integer, if set, don't try to automatically
94          determine what the IP address type is. important for things
95          like IPNetwork(1), which could be IPv4, '0.0.0.1/32', or IPv6,
96          '::1/128'.
97
98    Returns:
99        An IPv4Network or IPv6Network object.
100
101    Raises:
102        ValueError: if the string passed isn't either a v4 or a v6
103          address. Or if a strict network was requested and a strict
104          network wasn't given.
105
106    """
107    if version:
108        if version == 4:
109            return IPv4Network(address, strict)
110        elif version == 6:
111            return IPv6Network(address, strict)
112
113    try:
114        return IPv4Network(address, strict)
115    except (AddressValueError, NetmaskValueError):
116        pass
117
118    try:
119        return IPv6Network(address, strict)
120    except (AddressValueError, NetmaskValueError):
121        pass
122
123    raise ValueError('%r does not appear to be an IPv4 or IPv6 network' %
124                     address)
125
126
127def v4_int_to_packed(address):
128    """The binary representation of this address.
129
130    Args:
131        address: An integer representation of an IPv4 IP address.
132
133    Returns:
134        The binary representation of this address.
135
136    Raises:
137        ValueError: If the integer is too large to be an IPv4 IP
138          address.
139    """
140    if address > _BaseV4._ALL_ONES:
141        raise ValueError('Address too large for IPv4')
142    return Bytes(struct.pack('!I', address))
143
144
145def v6_int_to_packed(address):
146    """The binary representation of this address.
147
148    Args:
149        address: An integer representation of an IPv6 IP address.
150
151    Returns:
152        The binary representation of this address.
153    """
154    return Bytes(struct.pack('!QQ', address >> 64, address & (2**64 - 1)))
155
156
157def _find_address_range(addresses):
158    """Find a sequence of addresses.
159
160    Args:
161        addresses: a list of IPv4 or IPv6 addresses.
162
163    Returns:
164        A tuple containing the first and last IP addresses in the sequence,
165        and the index of the last IP address in the sequence.
166
167    """
168    first = last = addresses[0]
169    last_index = 0
170    for ip in addresses[1:]:
171        if ip._ip == last._ip + 1:
172            last = ip
173            last_index += 1
174        else:
175            break
176    return (first, last, last_index)
177
178def _get_prefix_length(number1, number2, bits):
179    """Get the number of leading bits that are same for two numbers.
180
181    Args:
182        number1: an integer.
183        number2: another integer.
184        bits: the maximum number of bits to compare.
185
186    Returns:
187        The number of leading bits that are the same for two numbers.
188
189    """
190    for i in range(bits):
191        if number1 >> i == number2 >> i:
192            return bits - i
193    return 0
194
195def _count_righthand_zero_bits(number, bits):
196    """Count the number of zero bits on the right hand side.
197
198    Args:
199        number: an integer.
200        bits: maximum number of bits to count.
201
202    Returns:
203        The number of zero bits on the right hand side of the number.
204
205    """
206    if number == 0:
207        return bits
208    for i in range(bits):
209        if (number >> i) % 2:
210            return i
211
212def summarize_address_range(first, last):
213    """Summarize a network range given the first and last IP addresses.
214
215    Example:
216        >>> summarize_address_range(IPv4Address('1.1.1.0'),
217            IPv4Address('1.1.1.130'))
218        [IPv4Network('1.1.1.0/25'), IPv4Network('1.1.1.128/31'),
219        IPv4Network('1.1.1.130/32')]
220
221    Args:
222        first: the first IPv4Address or IPv6Address in the range.
223        last: the last IPv4Address or IPv6Address in the range.
224
225    Returns:
226        The address range collapsed to a list of IPv4Network's or
227        IPv6Network's.
228
229    Raise:
230        TypeError:
231            If the first and last objects are not IP addresses.
232            If the first and last objects are not the same version.
233        ValueError:
234            If the last object is not greater than the first.
235            If the version is not 4 or 6.
236
237    """
238    if not (isinstance(first, _BaseIP) and isinstance(last, _BaseIP)):
239        raise TypeError('first and last must be IP addresses, not networks')
240    if first.version != last.version:
241        raise TypeError("%s and %s are not of the same version" % (
242                str(first), str(last)))
243    if first > last:
244        raise ValueError('last IP address must be greater than first')
245
246    networks = []
247
248    if first.version == 4:
249        ip = IPv4Network
250    elif first.version == 6:
251        ip = IPv6Network
252    else:
253        raise ValueError('unknown IP version')
254
255    ip_bits = first._max_prefixlen
256    first_int = first._ip
257    last_int = last._ip
258    while first_int <= last_int:
259        nbits = _count_righthand_zero_bits(first_int, ip_bits)
260        current = None
261        while nbits >= 0:
262            addend = 2**nbits - 1
263            current = first_int + addend
264            nbits -= 1
265            if current <= last_int:
266                break
267        prefix = _get_prefix_length(first_int, current, ip_bits)
268        net = ip('%s/%d' % (str(first), prefix))
269        networks.append(net)
270        if current == ip._ALL_ONES:
271            break
272        first_int = current + 1
273        first = IPAddress(first_int, version=first._version)
274    return networks
275
276def _collapse_address_list_recursive(addresses):
277    """Loops through the addresses, collapsing concurrent netblocks.
278
279    Example:
280
281        ip1 = IPv4Network('1.1.0.0/24')
282        ip2 = IPv4Network('1.1.1.0/24')
283        ip3 = IPv4Network('1.1.2.0/24')
284        ip4 = IPv4Network('1.1.3.0/24')
285        ip5 = IPv4Network('1.1.4.0/24')
286        ip6 = IPv4Network('1.1.0.1/22')
287
288        _collapse_address_list_recursive([ip1, ip2, ip3, ip4, ip5, ip6]) ->
289          [IPv4Network('1.1.0.0/22'), IPv4Network('1.1.4.0/24')]
290
291        This shouldn't be called directly; it is called via
292          collapse_address_list([]).
293
294    Args:
295        addresses: A list of IPv4Network's or IPv6Network's
296
297    Returns:
298        A list of IPv4Network's or IPv6Network's depending on what we were
299        passed.
300
301    """
302    ret_array = []
303    optimized = False
304
305    for cur_addr in addresses:
306        if not ret_array:
307            ret_array.append(cur_addr)
308            continue
309        if cur_addr in ret_array[-1]:
310            optimized = True
311        elif cur_addr == ret_array[-1].supernet().subnet()[1]:
312            ret_array.append(ret_array.pop().supernet())
313            optimized = True
314        else:
315            ret_array.append(cur_addr)
316
317    if optimized:
318        return _collapse_address_list_recursive(ret_array)
319
320    return ret_array
321
322
323def collapse_address_list(addresses):
324    """Collapse a list of IP objects.
325
326    Example:
327        collapse_address_list([IPv4('1.1.0.0/24'), IPv4('1.1.1.0/24')]) ->
328          [IPv4('1.1.0.0/23')]
329
330    Args:
331        addresses: A list of IPv4Network or IPv6Network objects.
332
333    Returns:
334        A list of IPv4Network or IPv6Network objects depending on what we
335        were passed.
336
337    Raises:
338        TypeError: If passed a list of mixed version objects.
339
340    """
341    i = 0
342    addrs = []
343    ips = []
344    nets = []
345
346    # split IP addresses and networks
347    for ip in addresses:
348        if isinstance(ip, _BaseIP):
349            if ips and ips[-1]._version != ip._version:
350                raise TypeError("%s and %s are not of the same version" % (
351                        str(ip), str(ips[-1])))
352            ips.append(ip)
353        elif ip._prefixlen == ip._max_prefixlen:
354            if ips and ips[-1]._version != ip._version:
355                raise TypeError("%s and %s are not of the same version" % (
356                        str(ip), str(ips[-1])))
357            ips.append(ip.ip)
358        else:
359            if nets and nets[-1]._version != ip._version:
360                raise TypeError("%s and %s are not of the same version" % (
361                        str(ip), str(nets[-1])))
362            nets.append(ip)
363
364    # sort and dedup
365    ips = sorted(set(ips))
366    nets = sorted(set(nets))
367
368    while i < len(ips):
369        (first, last, last_index) = _find_address_range(ips[i:])
370        i += last_index + 1
371        addrs.extend(summarize_address_range(first, last))
372
373    return _collapse_address_list_recursive(sorted(
374        addrs + nets, key=_BaseNet._get_networks_key))
375
376# backwards compatibility
377CollapseAddrList = collapse_address_list
378
379# We need to distinguish between the string and packed-bytes representations
380# of an IP address.  For example, b'0::1' is the IPv4 address 48.58.58.49,
381# while '0::1' is an IPv6 address.
382#
383# In Python 3, the native 'bytes' type already provides this functionality,
384# so we use it directly.  For earlier implementations where bytes is not a
385# distinct type, we create a subclass of str to serve as a tag.
386#
387# Usage example (Python 2):
388#   ip = ipaddr.IPAddress(ipaddr.Bytes('xxxx'))
389#
390# Usage example (Python 3):
391#   ip = ipaddr.IPAddress(b'xxxx')
392try:
393    if bytes is str:
394        raise TypeError("bytes is not a distinct type")
395    Bytes = bytes
396except (NameError, TypeError):
397    class Bytes(str):
398        def __repr__(self):
399            return 'Bytes(%s)' % str.__repr__(self)
400
401def get_mixed_type_key(obj):
402    """Return a key suitable for sorting between networks and addresses.
403
404    Address and Network objects are not sortable by default; they're
405    fundamentally different so the expression
406
407        IPv4Address('1.1.1.1') <= IPv4Network('1.1.1.1/24')
408
409    doesn't make any sense.  There are some times however, where you may wish
410    to have ipaddr sort these for you anyway. If you need to do this, you
411    can use this function as the key= argument to sorted().
412
413    Args:
414      obj: either a Network or Address object.
415    Returns:
416      appropriate key.
417
418    """
419    if isinstance(obj, _BaseNet):
420        return obj._get_networks_key()
421    elif isinstance(obj, _BaseIP):
422        return obj._get_address_key()
423    return NotImplemented
424
425class _IPAddrBase(object):
426
427    """The mother class."""
428
429    def __index__(self):
430        return self._ip
431
432    def __int__(self):
433        return self._ip
434
435    def __hex__(self):
436        return hex(self._ip)
437
438    @property
439    def exploded(self):
440        """Return the longhand version of the IP address as a string."""
441        return self._explode_shorthand_ip_string()
442
443    @property
444    def compressed(self):
445        """Return the shorthand version of the IP address as a string."""
446        return str(self)
447
448
449class _BaseIP(_IPAddrBase):
450
451    """A generic IP object.
452
453    This IP class contains the version independent methods which are
454    used by single IP addresses.
455
456    """
457
458    def __eq__(self, other):
459        try:
460            return (self._ip == other._ip
461                    and self._version == other._version)
462        except AttributeError:
463            return NotImplemented
464
465    def __ne__(self, other):
466        eq = self.__eq__(other)
467        if eq is NotImplemented:
468            return NotImplemented
469        return not eq
470
471    def __le__(self, other):
472        gt = self.__gt__(other)
473        if gt is NotImplemented:
474            return NotImplemented
475        return not gt
476
477    def __ge__(self, other):
478        lt = self.__lt__(other)
479        if lt is NotImplemented:
480            return NotImplemented
481        return not lt
482
483    def __lt__(self, other):
484        if self._version != other._version:
485            raise TypeError('%s and %s are not of the same version' % (
486                    str(self), str(other)))
487        if not isinstance(other, _BaseIP):
488            raise TypeError('%s and %s are not of the same type' % (
489                    str(self), str(other)))
490        if self._ip != other._ip:
491            return self._ip < other._ip
492        return False
493
494    def __gt__(self, other):
495        if self._version != other._version:
496            raise TypeError('%s and %s are not of the same version' % (
497                    str(self), str(other)))
498        if not isinstance(other, _BaseIP):
499            raise TypeError('%s and %s are not of the same type' % (
500                    str(self), str(other)))
501        if self._ip != other._ip:
502            return self._ip > other._ip
503        return False
504
505    # Shorthand for Integer addition and subtraction. This is not
506    # meant to ever support addition/subtraction of addresses.
507    def __add__(self, other):
508        if not isinstance(other, int):
509            return NotImplemented
510        return IPAddress(int(self) + other, version=self._version)
511
512    def __sub__(self, other):
513        if not isinstance(other, int):
514            return NotImplemented
515        return IPAddress(int(self) - other, version=self._version)
516
517    def __repr__(self):
518        return '%s(%r)' % (self.__class__.__name__, str(self))
519
520    def __str__(self):
521        return  '%s' % self._string_from_ip_int(self._ip)
522
523    def __hash__(self):
524        return hash(hex(long(self._ip)))
525
526    def _get_address_key(self):
527        return (self._version, self)
528
529    @property
530    def version(self):
531        raise NotImplementedError('BaseIP has no version')
532
533
534class _BaseNet(_IPAddrBase):
535
536    """A generic IP object.
537
538    This IP class contains the version independent methods which are
539    used by networks.
540
541    """
542
543    def __init__(self, address):
544        self._cache = {}
545
546    def __repr__(self):
547        return '%s(%r)' % (self.__class__.__name__, str(self))
548
549    def iterhosts(self):
550        """Generate Iterator over usable hosts in a network.
551
552           This is like __iter__ except it doesn't return the network
553           or broadcast addresses.
554
555        """
556        cur = int(self.network) + 1
557        bcast = int(self.broadcast) - 1
558        while cur <= bcast:
559            cur += 1
560            yield IPAddress(cur - 1, version=self._version)
561
562    def __iter__(self):
563        cur = int(self.network)
564        bcast = int(self.broadcast)
565        while cur <= bcast:
566            cur += 1
567            yield IPAddress(cur - 1, version=self._version)
568
569    def __getitem__(self, n):
570        network = int(self.network)
571        broadcast = int(self.broadcast)
572        if n >= 0:
573            if network + n > broadcast:
574                raise IndexError
575            return IPAddress(network + n, version=self._version)
576        else:
577            n += 1
578            if broadcast + n < network:
579                raise IndexError
580            return IPAddress(broadcast + n, version=self._version)
581
582    def __lt__(self, other):
583        if self._version != other._version:
584            raise TypeError('%s and %s are not of the same version' % (
585                    str(self), str(other)))
586        if not isinstance(other, _BaseNet):
587            raise TypeError('%s and %s are not of the same type' % (
588                    str(self), str(other)))
589        if self.network != other.network:
590            return self.network < other.network
591        if self.netmask != other.netmask:
592            return self.netmask < other.netmask
593        return False
594
595    def __gt__(self, other):
596        if self._version != other._version:
597            raise TypeError('%s and %s are not of the same version' % (
598                    str(self), str(other)))
599        if not isinstance(other, _BaseNet):
600            raise TypeError('%s and %s are not of the same type' % (
601                    str(self), str(other)))
602        if self.network != other.network:
603            return self.network > other.network
604        if self.netmask != other.netmask:
605            return self.netmask > other.netmask
606        return False
607
608    def __le__(self, other):
609        gt = self.__gt__(other)
610        if gt is NotImplemented:
611            return NotImplemented
612        return not gt
613
614    def __ge__(self, other):
615        lt = self.__lt__(other)
616        if lt is NotImplemented:
617            return NotImplemented
618        return not lt
619
620    def __eq__(self, other):
621        try:
622            return (self._version == other._version
623                    and self.network == other.network
624                    and int(self.netmask) == int(other.netmask))
625        except AttributeError:
626            if isinstance(other, _BaseIP):
627                return (self._version == other._version
628                        and self._ip == other._ip)
629
630    def __ne__(self, other):
631        eq = self.__eq__(other)
632        if eq is NotImplemented:
633            return NotImplemented
634        return not eq
635
636    def __str__(self):
637        return  '%s/%s' % (str(self.ip),
638                           str(self._prefixlen))
639
640    def __hash__(self):
641        return hash(int(self.network) ^ int(self.netmask))
642
643    def __contains__(self, other):
644        # always false if one is v4 and the other is v6.
645        if self._version != other._version:
646          return False
647        # dealing with another network.
648        if isinstance(other, _BaseNet):
649            return (self.network <= other.network and
650                    self.broadcast >= other.broadcast)
651        # dealing with another address
652        else:
653            return (int(self.network) <= int(other._ip) <=
654                    int(self.broadcast))
655
656    def overlaps(self, other):
657        """Tell if self is partly contained in other."""
658        return self.network in other or self.broadcast in other or (
659            other.network in self or other.broadcast in self)
660
661    @property
662    def network(self):
663        x = self._cache.get('network')
664        if x is None:
665            x = IPAddress(self._ip & int(self.netmask), version=self._version)
666            self._cache['network'] = x
667        return x
668
669    @property
670    def broadcast(self):
671        x = self._cache.get('broadcast')
672        if x is None:
673            x = IPAddress(self._ip | int(self.hostmask), version=self._version)
674            self._cache['broadcast'] = x
675        return x
676
677    @property
678    def hostmask(self):
679        x = self._cache.get('hostmask')
680        if x is None:
681            x = IPAddress(int(self.netmask) ^ self._ALL_ONES,
682                          version=self._version)
683            self._cache['hostmask'] = x
684        return x
685
686    @property
687    def with_prefixlen(self):
688        return '%s/%d' % (str(self.ip), self._prefixlen)
689
690    @property
691    def with_netmask(self):
692        return '%s/%s' % (str(self.ip), str(self.netmask))
693
694    @property
695    def with_hostmask(self):
696        return '%s/%s' % (str(self.ip), str(self.hostmask))
697
698    @property
699    def numhosts(self):
700        """Number of hosts in the current subnet."""
701        return int(self.broadcast) - int(self.network) + 1
702
703    @property
704    def version(self):
705        raise NotImplementedError('BaseNet has no version')
706
707    @property
708    def prefixlen(self):
709        return self._prefixlen
710
711    def address_exclude(self, other):
712        """Remove an address from a larger block.
713
714        For example:
715
716            addr1 = IPNetwork('10.1.1.0/24')
717            addr2 = IPNetwork('10.1.1.0/26')
718            addr1.address_exclude(addr2) =
719                [IPNetwork('10.1.1.64/26'), IPNetwork('10.1.1.128/25')]
720
721        or IPv6:
722
723            addr1 = IPNetwork('::1/32')
724            addr2 = IPNetwork('::1/128')
725            addr1.address_exclude(addr2) = [IPNetwork('::0/128'),
726                IPNetwork('::2/127'),
727                IPNetwork('::4/126'),
728                IPNetwork('::8/125'),
729                ...
730                IPNetwork('0:0:8000::/33')]
731
732        Args:
733            other: An IPvXNetwork object of the same type.
734
735        Returns:
736            A sorted list of IPvXNetwork objects addresses which is self
737            minus other.
738
739        Raises:
740            TypeError: If self and other are of difffering address
741              versions, or if other is not a network object.
742            ValueError: If other is not completely contained by self.
743
744        """
745        if not self._version == other._version:
746            raise TypeError("%s and %s are not of the same version" % (
747                str(self), str(other)))
748
749        if not isinstance(other, _BaseNet):
750            raise TypeError("%s is not a network object" % str(other))
751
752        if other not in self:
753            raise ValueError('%s not contained in %s' % (str(other),
754                                                         str(self)))
755        if other == self:
756            return []
757
758        ret_addrs = []
759
760        # Make sure we're comparing the network of other.
761        other = IPNetwork('%s/%s' % (str(other.network), str(other.prefixlen)),
762                   version=other._version)
763
764        s1, s2 = self.subnet()
765        while s1 != other and s2 != other:
766            if other in s1:
767                ret_addrs.append(s2)
768                s1, s2 = s1.subnet()
769            elif other in s2:
770                ret_addrs.append(s1)
771                s1, s2 = s2.subnet()
772            else:
773                # If we got here, there's a bug somewhere.
774                assert True == False, ('Error performing exclusion: '
775                                       's1: %s s2: %s other: %s' %
776                                       (str(s1), str(s2), str(other)))
777        if s1 == other:
778            ret_addrs.append(s2)
779        elif s2 == other:
780            ret_addrs.append(s1)
781        else:
782            # If we got here, there's a bug somewhere.
783            assert True == False, ('Error performing exclusion: '
784                                   's1: %s s2: %s other: %s' %
785                                   (str(s1), str(s2), str(other)))
786
787        return sorted(ret_addrs, key=_BaseNet._get_networks_key)
788
789    def compare_networks(self, other):
790        """Compare two IP objects.
791
792        This is only concerned about the comparison of the integer
793        representation of the network addresses.  This means that the
794        host bits aren't considered at all in this method.  If you want
795        to compare host bits, you can easily enough do a
796        'HostA._ip < HostB._ip'
797
798        Args:
799            other: An IP object.
800
801        Returns:
802            If the IP versions of self and other are the same, returns:
803
804            -1 if self < other:
805              eg: IPv4('1.1.1.0/24') < IPv4('1.1.2.0/24')
806              IPv6('1080::200C:417A') < IPv6('1080::200B:417B')
807            0 if self == other
808              eg: IPv4('1.1.1.1/24') == IPv4('1.1.1.2/24')
809              IPv6('1080::200C:417A/96') == IPv6('1080::200C:417B/96')
810            1 if self > other
811              eg: IPv4('1.1.1.0/24') > IPv4('1.1.0.0/24')
812              IPv6('1080::1:200C:417A/112') >
813              IPv6('1080::0:200C:417A/112')
814
815            If the IP versions of self and other are different, returns:
816
817            -1 if self._version < other._version
818              eg: IPv4('10.0.0.1/24') < IPv6('::1/128')
819            1 if self._version > other._version
820              eg: IPv6('::1/128') > IPv4('255.255.255.0/24')
821
822        """
823        if self._version < other._version:
824            return -1
825        if self._version > other._version:
826            return 1
827        # self._version == other._version below here:
828        if self.network < other.network:
829            return -1
830        if self.network > other.network:
831            return 1
832        # self.network == other.network below here:
833        if self.netmask < other.netmask:
834            return -1
835        if self.netmask > other.netmask:
836            return 1
837        # self.network == other.network and self.netmask == other.netmask
838        return 0
839
840    def _get_networks_key(self):
841        """Network-only key function.
842
843        Returns an object that identifies this address' network and
844        netmask. This function is a suitable "key" argument for sorted()
845        and list.sort().
846
847        """
848        return (self._version, self.network, self.netmask)
849
850    def _ip_int_from_prefix(self, prefixlen):
851        """Turn the prefix length into a bitwise netmask.
852
853        Args:
854            prefixlen: An integer, the prefix length.
855
856        Returns:
857            An integer.
858
859        """
860        return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen)
861
862    def _prefix_from_ip_int(self, ip_int):
863        """Return prefix length from a bitwise netmask.
864
865        Args:
866            ip_int: An integer, the netmask in expanded bitwise format.
867
868        Returns:
869            An integer, the prefix length.
870
871        Raises:
872            NetmaskValueError: If the input is not a valid netmask.
873
874        """
875        prefixlen = self._max_prefixlen
876        while prefixlen:
877            if ip_int & 1:
878                break
879            ip_int >>= 1
880            prefixlen -= 1
881
882        if ip_int == (1 << prefixlen) - 1:
883            return prefixlen
884        else:
885            raise NetmaskValueError('Bit pattern does not match /1*0*/')
886
887    def _prefix_from_prefix_int(self, prefixlen):
888        """Validate and return a prefix length integer.
889
890        Args:
891            prefixlen: An integer containing the prefix length.
892
893        Returns:
894            The input, possibly converted from long to int.
895
896        Raises:
897            NetmaskValueError: If the input is not an integer, or out of range.
898        """
899        if not isinstance(prefixlen, (int, long)):
900            raise NetmaskValueError('%r is not an integer' % prefixlen)
901        prefixlen = int(prefixlen)
902        if not (0 <= prefixlen <= self._max_prefixlen):
903            raise NetmaskValueError('%d is not a valid prefix length' %
904                                    prefixlen)
905        return prefixlen
906
907    def _prefix_from_prefix_string(self, prefixlen_str):
908        """Turn a prefix length string into an integer.
909
910        Args:
911            prefixlen_str: A decimal string containing the prefix length.
912
913        Returns:
914            The prefix length as an integer.
915
916        Raises:
917            NetmaskValueError: If the input is malformed or out of range.
918
919        """
920        try:
921            if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
922                raise ValueError
923            prefixlen = int(prefixlen_str)
924        except ValueError:
925            raise NetmaskValueError('%s is not a valid prefix length' %
926                                    prefixlen_str)
927        return self._prefix_from_prefix_int(prefixlen)
928
929    def _prefix_from_ip_string(self, ip_str):
930        """Turn a netmask/hostmask string into a prefix length.
931
932        Args:
933            ip_str: A netmask or hostmask, formatted as an IP address.
934
935        Returns:
936            The prefix length as an integer.
937
938        Raises:
939            NetmaskValueError: If the input is not a netmask or hostmask.
940
941        """
942        # Parse the netmask/hostmask like an IP address.
943        try:
944            ip_int = self._ip_int_from_string(ip_str)
945        except AddressValueError:
946            raise NetmaskValueError('%s is not a valid netmask' % ip_str)
947
948        # Try matching a netmask (this would be /1*0*/ as a bitwise regexp).
949        # Note that the two ambiguous cases (all-ones and all-zeroes) are
950        # treated as netmasks.
951        try:
952            return self._prefix_from_ip_int(ip_int)
953        except NetmaskValueError:
954            pass
955
956        # Invert the bits, and try matching a /0+1+/ hostmask instead.
957        ip_int ^= self._ALL_ONES
958        try:
959            return self._prefix_from_ip_int(ip_int)
960        except NetmaskValueError:
961            raise NetmaskValueError('%s is not a valid netmask' % ip_str)
962
963    def iter_subnets(self, prefixlen_diff=1, new_prefix=None):
964        """The subnets which join to make the current subnet.
965
966        In the case that self contains only one IP
967        (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
968        for IPv6), return a list with just ourself.
969
970        Args:
971            prefixlen_diff: An integer, the amount the prefix length
972              should be increased by. This should not be set if
973              new_prefix is also set.
974            new_prefix: The desired new prefix length. This must be a
975              larger number (smaller prefix) than the existing prefix.
976              This should not be set if prefixlen_diff is also set.
977
978        Returns:
979            An iterator of IPv(4|6) objects.
980
981        Raises:
982            ValueError: The prefixlen_diff is too small or too large.
983                OR
984            prefixlen_diff and new_prefix are both set or new_prefix
985              is a smaller number than the current prefix (smaller
986              number means a larger network)
987
988        """
989        if self._prefixlen == self._max_prefixlen:
990            yield self
991            return
992
993        if new_prefix is not None:
994            if new_prefix < self._prefixlen:
995                raise ValueError('new prefix must be longer')
996            if prefixlen_diff != 1:
997                raise ValueError('cannot set prefixlen_diff and new_prefix')
998            prefixlen_diff = new_prefix - self._prefixlen
999
1000        if prefixlen_diff < 0:
1001            raise ValueError('prefix length diff must be > 0')
1002        new_prefixlen = self._prefixlen + prefixlen_diff
1003
1004        if new_prefixlen > self._max_prefixlen:
1005            raise ValueError(
1006                'prefix length diff %d is invalid for netblock %s' % (
1007                    new_prefixlen, str(self)))
1008
1009        first = IPNetwork('%s/%s' % (str(self.network),
1010                                     str(self._prefixlen + prefixlen_diff)),
1011                         version=self._version)
1012
1013        yield first
1014        current = first
1015        while True:
1016            broadcast = current.broadcast
1017            if broadcast == self.broadcast:
1018                return
1019            new_addr = IPAddress(int(broadcast) + 1, version=self._version)
1020            current = IPNetwork('%s/%s' % (str(new_addr), str(new_prefixlen)),
1021                                version=self._version)
1022
1023            yield current
1024
1025    def masked(self):
1026        """Return the network object with the host bits masked out."""
1027        return IPNetwork('%s/%d' % (self.network, self._prefixlen),
1028                         version=self._version)
1029
1030    def subnet(self, prefixlen_diff=1, new_prefix=None):
1031        """Return a list of subnets, rather than an iterator."""
1032        return list(self.iter_subnets(prefixlen_diff, new_prefix))
1033
1034    def supernet(self, prefixlen_diff=1, new_prefix=None):
1035        """The supernet containing the current network.
1036
1037        Args:
1038            prefixlen_diff: An integer, the amount the prefix length of
1039              the network should be decreased by.  For example, given a
1040              /24 network and a prefixlen_diff of 3, a supernet with a
1041              /21 netmask is returned.
1042
1043        Returns:
1044            An IPv4 network object.
1045
1046        Raises:
1047            ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have a
1048              negative prefix length.
1049                OR
1050            If prefixlen_diff and new_prefix are both set or new_prefix is a
1051              larger number than the current prefix (larger number means a
1052              smaller network)
1053
1054        """
1055        if self._prefixlen == 0:
1056            return self
1057
1058        if new_prefix is not None:
1059            if new_prefix > self._prefixlen:
1060                raise ValueError('new prefix must be shorter')
1061            if prefixlen_diff != 1:
1062                raise ValueError('cannot set prefixlen_diff and new_prefix')
1063            prefixlen_diff = self._prefixlen - new_prefix
1064
1065
1066        if self.prefixlen - prefixlen_diff < 0:
1067            raise ValueError(
1068                'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
1069                (self.prefixlen, prefixlen_diff))
1070        return IPNetwork('%s/%s' % (str(self.network),
1071                                    str(self.prefixlen - prefixlen_diff)),
1072                         version=self._version)
1073
1074    # backwards compatibility
1075    Subnet = subnet
1076    Supernet = supernet
1077    AddressExclude = address_exclude
1078    CompareNetworks = compare_networks
1079    Contains = __contains__
1080
1081
1082class _BaseV4(object):
1083
1084    """Base IPv4 object.
1085
1086    The following methods are used by IPv4 objects in both single IP
1087    addresses and networks.
1088
1089    """
1090
1091    # Equivalent to 255.255.255.255 or 32 bits of 1's.
1092    _ALL_ONES = (2**IPV4LENGTH) - 1
1093    _DECIMAL_DIGITS = frozenset('0123456789')
1094
1095    def __init__(self, address):
1096        self._version = 4
1097        self._max_prefixlen = IPV4LENGTH
1098
1099    def _explode_shorthand_ip_string(self):
1100        return str(self)
1101
1102    def _ip_int_from_string(self, ip_str):
1103        """Turn the given IP string into an integer for comparison.
1104
1105        Args:
1106            ip_str: A string, the IP ip_str.
1107
1108        Returns:
1109            The IP ip_str as an integer.
1110
1111        Raises:
1112            AddressValueError: if ip_str isn't a valid IPv4 Address.
1113
1114        """
1115        octets = ip_str.split('.')
1116        if len(octets) != 4:
1117            raise AddressValueError(ip_str)
1118
1119        packed_ip = 0
1120        for oc in octets:
1121            try:
1122                packed_ip = (packed_ip << 8) | self._parse_octet(oc)
1123            except ValueError:
1124                raise AddressValueError(ip_str)
1125        return packed_ip
1126
1127    def _parse_octet(self, octet_str):
1128        """Convert a decimal octet into an integer.
1129
1130        Args:
1131            octet_str: A string, the number to parse.
1132
1133        Returns:
1134            The octet as an integer.
1135
1136        Raises:
1137            ValueError: if the octet isn't strictly a decimal from [0..255].
1138
1139        """
1140        # Whitelist the characters, since int() allows a lot of bizarre stuff.
1141        if not self._DECIMAL_DIGITS.issuperset(octet_str):
1142            raise ValueError
1143        octet_int = int(octet_str, 10)
1144        # Disallow leading zeroes, because no clear standard exists on
1145        # whether these should be interpreted as decimal or octal.
1146        if octet_int > 255 or (octet_str[0] == '0' and len(octet_str) > 1):
1147            raise ValueError
1148        return octet_int
1149
1150    def _string_from_ip_int(self, ip_int):
1151        """Turns a 32-bit integer into dotted decimal notation.
1152
1153        Args:
1154            ip_int: An integer, the IP address.
1155
1156        Returns:
1157            The IP address as a string in dotted decimal notation.
1158
1159        """
1160        octets = []
1161        for _ in xrange(4):
1162            octets.insert(0, str(ip_int & 0xFF))
1163            ip_int >>= 8
1164        return '.'.join(octets)
1165
1166    @property
1167    def max_prefixlen(self):
1168        return self._max_prefixlen
1169
1170    @property
1171    def packed(self):
1172        """The binary representation of this address."""
1173        return v4_int_to_packed(self._ip)
1174
1175    @property
1176    def version(self):
1177        return self._version
1178
1179    @property
1180    def is_reserved(self):
1181       """Test if the address is otherwise IETF reserved.
1182
1183        Returns:
1184            A boolean, True if the address is within the
1185            reserved IPv4 Network range.
1186
1187       """
1188       return self in IPv4Network('240.0.0.0/4')
1189
1190    @property
1191    def is_private(self):
1192        """Test if this address is allocated for private networks.
1193
1194        Returns:
1195            A boolean, True if the address is reserved per RFC 1918.
1196
1197        """
1198        return (self in IPv4Network('10.0.0.0/8') or
1199                self in IPv4Network('172.16.0.0/12') or
1200                self in IPv4Network('192.168.0.0/16'))
1201
1202    @property
1203    def is_multicast(self):
1204        """Test if the address is reserved for multicast use.
1205
1206        Returns:
1207            A boolean, True if the address is multicast.
1208            See RFC 3171 for details.
1209
1210        """
1211        return self in IPv4Network('224.0.0.0/4')
1212
1213    @property
1214    def is_unspecified(self):
1215        """Test if the address is unspecified.
1216
1217        Returns:
1218            A boolean, True if this is the unspecified address as defined in
1219            RFC 5735 3.
1220
1221        """
1222        return self in IPv4Network('0.0.0.0')
1223
1224    @property
1225    def is_loopback(self):
1226        """Test if the address is a loopback address.
1227
1228        Returns:
1229            A boolean, True if the address is a loopback per RFC 3330.
1230
1231        """
1232        return self in IPv4Network('127.0.0.0/8')
1233
1234    @property
1235    def is_link_local(self):
1236        """Test if the address is reserved for link-local.
1237
1238        Returns:
1239            A boolean, True if the address is link-local per RFC 3927.
1240
1241        """
1242        return self in IPv4Network('169.254.0.0/16')
1243
1244
1245class IPv4Address(_BaseV4, _BaseIP):
1246
1247    """Represent and manipulate single IPv4 Addresses."""
1248
1249    def __init__(self, address):
1250
1251        """
1252        Args:
1253            address: A string or integer representing the IP
1254              '192.168.1.1'
1255
1256              Additionally, an integer can be passed, so
1257              IPv4Address('192.168.1.1') == IPv4Address(3232235777).
1258              or, more generally
1259              IPv4Address(int(IPv4Address('192.168.1.1'))) ==
1260                IPv4Address('192.168.1.1')
1261
1262        Raises:
1263            AddressValueError: If ipaddr isn't a valid IPv4 address.
1264
1265        """
1266        _BaseV4.__init__(self, address)
1267
1268        # Efficient copy constructor.
1269        if isinstance(address, IPv4Address):
1270            self._ip = address._ip
1271            return
1272
1273        # Efficient constructor from integer.
1274        if isinstance(address, (int, long)):
1275            self._ip = address
1276            if address < 0 or address > self._ALL_ONES:
1277                raise AddressValueError(address)
1278            return
1279
1280        # Constructing from a packed address
1281        if isinstance(address, Bytes):
1282            try:
1283                self._ip, = struct.unpack('!I', address)
1284            except struct.error:
1285                raise AddressValueError(address)  # Wrong length.
1286            return
1287
1288        # Assume input argument to be string or any object representation
1289        # which converts into a formatted IP string.
1290        addr_str = str(address)
1291        self._ip = self._ip_int_from_string(addr_str)
1292
1293
1294class IPv4Network(_BaseV4, _BaseNet):
1295
1296    """This class represents and manipulates 32-bit IPv4 networks.
1297
1298    Attributes: [examples for IPv4Network('1.2.3.4/27')]
1299        ._ip: 16909060
1300        .ip: IPv4Address('1.2.3.4')
1301        .network: IPv4Address('1.2.3.0')
1302        .hostmask: IPv4Address('0.0.0.31')
1303        .broadcast: IPv4Address('1.2.3.31')
1304        .netmask: IPv4Address('255.255.255.224')
1305        .prefixlen: 27
1306
1307    """
1308
1309    def __init__(self, address, strict=False):
1310        """Instantiate a new IPv4 network object.
1311
1312        Args:
1313            address: The IPv4 network as a string, 2-tuple, or any format
1314              supported by the IPv4Address constructor.
1315
1316              Strings typically use CIDR format, such as '192.0.2.0/24'.
1317              If a dotted-quad is provided after the '/', it is treated as
1318              a netmask if it starts with a nonzero bit (e.g. 255.0.0.0 == /8)
1319              or a hostmask if it starts with a zero bit
1320              (e.g. /0.0.0.255 == /8), with the single exception of an all-zero
1321              mask which is treated as /0.
1322
1323              The 2-tuple format consists of an (ip, prefixlen), where ip is any
1324              format recognized by the IPv4Address constructor, and prefixlen is
1325              an integer from 0 through 32.
1326
1327              A plain IPv4 address (in any format) will be forwarded to the
1328              IPv4Address constructor, with an implied prefixlen of 32.
1329
1330              For example, the following inputs are equivalent:
1331                IPv4Network('192.0.2.1/32')
1332                IPv4Network('192.0.2.1/255.255.255.255')
1333                IPv4Network('192.0.2.1')
1334                IPv4Network(0xc0000201)
1335                IPv4Network(IPv4Address('192.0.2.1'))
1336                IPv4Network(('192.0.2.1', 32))
1337                IPv4Network((0xc0000201, 32))
1338                IPv4Network((IPv4Address('192.0.2.1'), 32))
1339
1340            strict: A boolean. If true, ensure that we have been passed
1341              A true network address, eg, 192.168.1.0/24 and not an
1342              IP address on a network, eg, 192.168.1.1/24.
1343
1344        Raises:
1345            AddressValueError: If ipaddr isn't a valid IPv4 address.
1346            NetmaskValueError: If the netmask isn't valid for
1347              an IPv4 address.
1348            ValueError: If strict was True and a network address was not
1349              supplied.
1350
1351        """
1352        _BaseNet.__init__(self, address)
1353        _BaseV4.__init__(self, address)
1354
1355        # Constructing from a single IP address.
1356        if isinstance(address, (int, long, Bytes, IPv4Address)):
1357            self.ip = IPv4Address(address)
1358            self._ip = self.ip._ip
1359            self._prefixlen = self._max_prefixlen
1360            self.netmask = IPv4Address(self._ALL_ONES)
1361            return
1362
1363        # Constructing from an (ip, prefixlen) tuple.
1364        if isinstance(address, tuple):
1365            try:
1366                ip, prefixlen = address
1367            except ValueError:
1368                raise AddressValueError(address)
1369            self.ip = IPv4Address(ip)
1370            self._ip = self.ip._ip
1371            self._prefixlen = self._prefix_from_prefix_int(prefixlen)
1372
1373        else:
1374            # Assume input argument to be string or any object representation
1375            # which converts into a formatted IP prefix string.
1376            addr = str(address).split('/')
1377
1378            if len(addr) > 2:
1379                raise AddressValueError(address)
1380
1381            self._ip = self._ip_int_from_string(addr[0])
1382            self.ip = IPv4Address(self._ip)
1383
1384            if len(addr) == 2:
1385                try:
1386                    # Check for a netmask in prefix length form.
1387                    self._prefixlen = self._prefix_from_prefix_string(addr[1])
1388                except NetmaskValueError:
1389                    # Check for a netmask or hostmask in dotted-quad form.
1390                    # This may raise NetmaskValueError.
1391                    self._prefixlen = self._prefix_from_ip_string(addr[1])
1392            else:
1393                self._prefixlen = self._max_prefixlen
1394
1395        self.netmask = IPv4Address(self._ip_int_from_prefix(self._prefixlen))
1396
1397        if strict:
1398            if self.ip != self.network:
1399                raise ValueError('%s has host bits set' % self.ip)
1400        if self._prefixlen == (self._max_prefixlen - 1):
1401            self.iterhosts = self.__iter__
1402
1403    # backwards compatibility
1404    IsRFC1918 = lambda self: self.is_private
1405    IsMulticast = lambda self: self.is_multicast
1406    IsLoopback = lambda self: self.is_loopback
1407    IsLinkLocal = lambda self: self.is_link_local
1408
1409
1410class _BaseV6(object):
1411
1412    """Base IPv6 object.
1413
1414    The following methods are used by IPv6 objects in both single IP
1415    addresses and networks.
1416
1417    """
1418
1419    _ALL_ONES = (2**IPV6LENGTH) - 1
1420    _HEXTET_COUNT = 8
1421    _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
1422
1423    def __init__(self, address):
1424        self._version = 6
1425        self._max_prefixlen = IPV6LENGTH
1426
1427    def _ip_int_from_string(self, ip_str):
1428        """Turn an IPv6 ip_str into an integer.
1429
1430        Args:
1431            ip_str: A string, the IPv6 ip_str.
1432
1433        Returns:
1434            A long, the IPv6 ip_str.
1435
1436        Raises:
1437            AddressValueError: if ip_str isn't a valid IPv6 Address.
1438
1439        """
1440        parts = ip_str.split(':')
1441
1442        # An IPv6 address needs at least 2 colons (3 parts).
1443        if len(parts) < 3:
1444            raise AddressValueError(ip_str)
1445
1446        # If the address has an IPv4-style suffix, convert it to hexadecimal.
1447        if '.' in parts[-1]:
1448            ipv4_int = IPv4Address(parts.pop())._ip
1449            parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1450            parts.append('%x' % (ipv4_int & 0xFFFF))
1451
1452        # An IPv6 address can't have more than 8 colons (9 parts).
1453        if len(parts) > self._HEXTET_COUNT + 1:
1454            raise AddressValueError(ip_str)
1455
1456        # Disregarding the endpoints, find '::' with nothing in between.
1457        # This indicates that a run of zeroes has been skipped.
1458        try:
1459            skip_index, = (
1460                [i for i in xrange(1, len(parts) - 1) if not parts[i]] or
1461                [None])
1462        except ValueError:
1463            # Can't have more than one '::'
1464            raise AddressValueError(ip_str)
1465
1466        # parts_hi is the number of parts to copy from above/before the '::'
1467        # parts_lo is the number of parts to copy from below/after the '::'
1468        if skip_index is not None:
1469            # If we found a '::', then check if it also covers the endpoints.
1470            parts_hi = skip_index
1471            parts_lo = len(parts) - skip_index - 1
1472            if not parts[0]:
1473                parts_hi -= 1
1474                if parts_hi:
1475                    raise AddressValueError(ip_str)  # ^: requires ^::
1476            if not parts[-1]:
1477                parts_lo -= 1
1478                if parts_lo:
1479                    raise AddressValueError(ip_str)  # :$ requires ::$
1480            parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo)
1481            if parts_skipped < 1:
1482                raise AddressValueError(ip_str)
1483        else:
1484            # Otherwise, allocate the entire address to parts_hi.  The endpoints
1485            # could still be empty, but _parse_hextet() will check for that.
1486            if len(parts) != self._HEXTET_COUNT:
1487                raise AddressValueError(ip_str)
1488            parts_hi = len(parts)
1489            parts_lo = 0
1490            parts_skipped = 0
1491
1492        try:
1493            # Now, parse the hextets into a 128-bit integer.
1494            ip_int = long(0)
1495            for i in xrange(parts_hi):
1496                ip_int <<= 16
1497                ip_int |= self._parse_hextet(parts[i])
1498            ip_int <<= 16 * parts_skipped
1499            for i in xrange(-parts_lo, 0):
1500                ip_int <<= 16
1501                ip_int |= self._parse_hextet(parts[i])
1502            return ip_int
1503        except ValueError:
1504            raise AddressValueError(ip_str)
1505
1506    def _parse_hextet(self, hextet_str):
1507        """Convert an IPv6 hextet string into an integer.
1508
1509        Args:
1510            hextet_str: A string, the number to parse.
1511
1512        Returns:
1513            The hextet as an integer.
1514
1515        Raises:
1516            ValueError: if the input isn't strictly a hex number from [0..FFFF].
1517
1518        """
1519        # Whitelist the characters, since int() allows a lot of bizarre stuff.
1520        if not self._HEX_DIGITS.issuperset(hextet_str):
1521            raise ValueError
1522        if len(hextet_str) > 4:
1523          raise ValueError
1524        hextet_int = int(hextet_str, 16)
1525        if hextet_int > 0xFFFF:
1526            raise ValueError
1527        return hextet_int
1528
1529    def _compress_hextets(self, hextets):
1530        """Compresses a list of hextets.
1531
1532        Compresses a list of strings, replacing the longest continuous
1533        sequence of "0" in the list with "" and adding empty strings at
1534        the beginning or at the end of the string such that subsequently
1535        calling ":".join(hextets) will produce the compressed version of
1536        the IPv6 address.
1537
1538        Args:
1539            hextets: A list of strings, the hextets to compress.
1540
1541        Returns:
1542            A list of strings.
1543
1544        """
1545        best_doublecolon_start = -1
1546        best_doublecolon_len = 0
1547        doublecolon_start = -1
1548        doublecolon_len = 0
1549        for index in range(len(hextets)):
1550            if hextets[index] == '0':
1551                doublecolon_len += 1
1552                if doublecolon_start == -1:
1553                    # Start of a sequence of zeros.
1554                    doublecolon_start = index
1555                if doublecolon_len > best_doublecolon_len:
1556                    # This is the longest sequence of zeros so far.
1557                    best_doublecolon_len = doublecolon_len
1558                    best_doublecolon_start = doublecolon_start
1559            else:
1560                doublecolon_len = 0
1561                doublecolon_start = -1
1562
1563        if best_doublecolon_len > 1:
1564            best_doublecolon_end = (best_doublecolon_start +
1565                                    best_doublecolon_len)
1566            # For zeros at the end of the address.
1567            if best_doublecolon_end == len(hextets):
1568                hextets += ['']
1569            hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1570            # For zeros at the beginning of the address.
1571            if best_doublecolon_start == 0:
1572                hextets = [''] + hextets
1573
1574        return hextets
1575
1576    def _string_from_ip_int(self, ip_int=None):
1577        """Turns a 128-bit integer into hexadecimal notation.
1578
1579        Args:
1580            ip_int: An integer, the IP address.
1581
1582        Returns:
1583            A string, the hexadecimal representation of the address.
1584
1585        Raises:
1586            ValueError: The address is bigger than 128 bits of all ones.
1587
1588        """
1589        if not ip_int and ip_int != 0:
1590            ip_int = int(self._ip)
1591
1592        if ip_int > self._ALL_ONES:
1593            raise ValueError('IPv6 address is too large')
1594
1595        hex_str = '%032x' % ip_int
1596        hextets = []
1597        for x in range(0, 32, 4):
1598            hextets.append('%x' % int(hex_str[x:x+4], 16))
1599
1600        hextets = self._compress_hextets(hextets)
1601        return ':'.join(hextets)
1602
1603    def _explode_shorthand_ip_string(self):
1604        """Expand a shortened IPv6 address.
1605
1606        Args:
1607            ip_str: A string, the IPv6 address.
1608
1609        Returns:
1610            A string, the expanded IPv6 address.
1611
1612        """
1613        if isinstance(self, _BaseNet):
1614            ip_str = str(self.ip)
1615        else:
1616            ip_str = str(self)
1617
1618        ip_int = self._ip_int_from_string(ip_str)
1619        parts = []
1620        for i in xrange(self._HEXTET_COUNT):
1621            parts.append('%04x' % (ip_int & 0xFFFF))
1622            ip_int >>= 16
1623        parts.reverse()
1624        if isinstance(self, _BaseNet):
1625            return '%s/%d' % (':'.join(parts), self.prefixlen)
1626        return ':'.join(parts)
1627
1628    @property
1629    def max_prefixlen(self):
1630        return self._max_prefixlen
1631
1632    @property
1633    def packed(self):
1634        """The binary representation of this address."""
1635        return v6_int_to_packed(self._ip)
1636
1637    @property
1638    def version(self):
1639        return self._version
1640
1641    @property
1642    def is_multicast(self):
1643        """Test if the address is reserved for multicast use.
1644
1645        Returns:
1646            A boolean, True if the address is a multicast address.
1647            See RFC 2373 2.7 for details.
1648
1649        """
1650        return self in IPv6Network('ff00::/8')
1651
1652    @property
1653    def is_reserved(self):
1654        """Test if the address is otherwise IETF reserved.
1655
1656        Returns:
1657            A boolean, True if the address is within one of the
1658            reserved IPv6 Network ranges.
1659
1660        """
1661        return (self in IPv6Network('::/8') or
1662                self in IPv6Network('100::/8') or
1663                self in IPv6Network('200::/7') or
1664                self in IPv6Network('400::/6') or
1665                self in IPv6Network('800::/5') or
1666                self in IPv6Network('1000::/4') or
1667                self in IPv6Network('4000::/3') or
1668                self in IPv6Network('6000::/3') or
1669                self in IPv6Network('8000::/3') or
1670                self in IPv6Network('A000::/3') or
1671                self in IPv6Network('C000::/3') or
1672                self in IPv6Network('E000::/4') or
1673                self in IPv6Network('F000::/5') or
1674                self in IPv6Network('F800::/6') or
1675                self in IPv6Network('FE00::/9'))
1676
1677    @property
1678    def is_unspecified(self):
1679        """Test if the address is unspecified.
1680
1681        Returns:
1682            A boolean, True if this is the unspecified address as defined in
1683            RFC 2373 2.5.2.
1684
1685        """
1686        return self._ip == 0 and getattr(self, '_prefixlen', 128) == 128
1687
1688    @property
1689    def is_loopback(self):
1690        """Test if the address is a loopback address.
1691
1692        Returns:
1693            A boolean, True if the address is a loopback address as defined in
1694            RFC 2373 2.5.3.
1695
1696        """
1697        return self._ip == 1 and getattr(self, '_prefixlen', 128) == 128
1698
1699    @property
1700    def is_link_local(self):
1701        """Test if the address is reserved for link-local.
1702
1703        Returns:
1704            A boolean, True if the address is reserved per RFC 4291.
1705
1706        """
1707        return self in IPv6Network('fe80::/10')
1708
1709    @property
1710    def is_site_local(self):
1711        """Test if the address is reserved for site-local.
1712
1713        Note that the site-local address space has been deprecated by RFC 3879.
1714        Use is_private to test if this address is in the space of unique local
1715        addresses as defined by RFC 4193.
1716
1717        Returns:
1718            A boolean, True if the address is reserved per RFC 3513 2.5.6.
1719
1720        """
1721        return self in IPv6Network('fec0::/10')
1722
1723    @property
1724    def is_private(self):
1725        """Test if this address is allocated for private networks.
1726
1727        Returns:
1728            A boolean, True if the address is reserved per RFC 4193.
1729
1730        """
1731        return self in IPv6Network('fc00::/7')
1732
1733    @property
1734    def ipv4_mapped(self):
1735        """Return the IPv4 mapped address.
1736
1737        Returns:
1738            If the IPv6 address is a v4 mapped address, return the
1739            IPv4 mapped address. Return None otherwise.
1740
1741        """
1742        if (self._ip >> 32) != 0xFFFF:
1743            return None
1744        return IPv4Address(self._ip & 0xFFFFFFFF)
1745
1746    @property
1747    def teredo(self):
1748        """Tuple of embedded teredo IPs.
1749
1750        Returns:
1751            Tuple of the (server, client) IPs or None if the address
1752            doesn't appear to be a teredo address (doesn't start with
1753            2001::/32)
1754
1755        """
1756        if (self._ip >> 96) != 0x20010000:
1757            return None
1758        return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
1759                IPv4Address(~self._ip & 0xFFFFFFFF))
1760
1761    @property
1762    def sixtofour(self):
1763        """Return the IPv4 6to4 embedded address.
1764
1765        Returns:
1766            The IPv4 6to4-embedded address if present or None if the
1767            address doesn't appear to contain a 6to4 embedded address.
1768
1769        """
1770        if (self._ip >> 112) != 0x2002:
1771            return None
1772        return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
1773
1774
1775class IPv6Address(_BaseV6, _BaseIP):
1776
1777    """Represent and manipulate single IPv6 Addresses.
1778    """
1779
1780    def __init__(self, address):
1781        """Instantiate a new IPv6 address object.
1782
1783        Args:
1784            address: A string or integer representing the IP
1785
1786              Additionally, an integer can be passed, so
1787              IPv6Address('2001:4860::') ==
1788                IPv6Address(42541956101370907050197289607612071936L).
1789              or, more generally
1790              IPv6Address(IPv6Address('2001:4860::')._ip) ==
1791                IPv6Address('2001:4860::')
1792
1793        Raises:
1794            AddressValueError: If address isn't a valid IPv6 address.
1795
1796        """
1797        _BaseV6.__init__(self, address)
1798
1799        # Efficient copy constructor.
1800        if isinstance(address, IPv6Address):
1801            self._ip = address._ip
1802            return
1803
1804        # Efficient constructor from integer.
1805        if isinstance(address, (int, long)):
1806            self._ip = address
1807            if address < 0 or address > self._ALL_ONES:
1808                raise AddressValueError(address)
1809            return
1810
1811        # Constructing from a packed address
1812        if isinstance(address, Bytes):
1813            try:
1814                hi, lo = struct.unpack('!QQ', address)
1815            except struct.error:
1816                raise AddressValueError(address)  # Wrong length.
1817            self._ip = (hi << 64) | lo
1818            return
1819
1820        # Assume input argument to be string or any object representation
1821        # which converts into a formatted IP string.
1822        addr_str = str(address)
1823        self._ip = self._ip_int_from_string(addr_str)
1824
1825
1826class IPv6Network(_BaseV6, _BaseNet):
1827
1828    """This class represents and manipulates 128-bit IPv6 networks.
1829
1830    Attributes: [examples for IPv6('2001:658:22A:CAFE:200::1/64')]
1831        .ip: IPv6Address('2001:658:22a:cafe:200::1')
1832        .network: IPv6Address('2001:658:22a:cafe::')
1833        .hostmask: IPv6Address('::ffff:ffff:ffff:ffff')
1834        .broadcast: IPv6Address('2001:658:22a:cafe:ffff:ffff:ffff:ffff')
1835        .netmask: IPv6Address('ffff:ffff:ffff:ffff::')
1836        .prefixlen: 64
1837
1838    """
1839
1840
1841    def __init__(self, address, strict=False):
1842        """Instantiate a new IPv6 network object.
1843
1844        Args:
1845            address: The IPv6 network as a string, 2-tuple, or any format
1846              supported by the IPv6Address constructor.
1847
1848              Strings should be in CIDR format, such as '2001:db8::/32'.
1849
1850              The 2-tuple format consists of an (ip, prefixlen), where ip is any
1851              format recognized by the IPv6Address constructor, and prefixlen is
1852              an integer from 0 through 128.
1853
1854              A plain IPv6 address (in any format) will be forwarded to the
1855              IPv6Address constructor, with an implied prefixlen of 128.
1856
1857              For example, the following inputs are equivalent:
1858                IPv6Network('2001:db8::/128')
1859                IPv6Network('2001:db8:0:0:0:0:0:0/128')
1860                IPv6Network('2001:db8::')
1861                IPv6Network(0x20010db8 << 96)
1862                IPv6Network(IPv6Address('2001:db8::'))
1863                IPv6Network(('2001:db8::', 128))
1864                IPv6Network((0x20010db8 << 96, 128))
1865                IPv6Network((IPv6Address('2001:db8::'), 128))
1866
1867            strict: A boolean. If true, ensure that we have been passed
1868              A true network address, eg, 2001:db8::/32 and not an
1869              IP address on a network, eg, 2001:db8::1/32.
1870
1871        Raises:
1872            AddressValueError: If address isn't a valid IPv6 address.
1873            NetmaskValueError: If the netmask isn't valid for
1874              an IPv6 address.
1875            ValueError: If strict was True and a network address was not
1876              supplied.
1877
1878        """
1879        _BaseNet.__init__(self, address)
1880        _BaseV6.__init__(self, address)
1881
1882        # Constructing from a single IP address.
1883        if isinstance(address, (int, long, Bytes, IPv6Address)):
1884            self.ip = IPv6Address(address)
1885            self._ip = self.ip._ip
1886            self._prefixlen = self._max_prefixlen
1887            self.netmask = IPv6Address(self._ALL_ONES)
1888            return
1889
1890        # Constructing from an (ip, prefixlen) tuple.
1891        if isinstance(address, tuple):
1892            try:
1893                ip, prefixlen = address
1894            except ValueError:
1895                raise AddressValueError(address)
1896            self.ip = IPv6Address(ip)
1897            self._ip = self.ip._ip
1898            self._prefixlen = self._prefix_from_prefix_int(prefixlen)
1899
1900        else:
1901            # Assume input argument to be string or any object representation
1902            # which converts into a formatted IP prefix string.
1903            addr = str(address).split('/')
1904
1905            if len(addr) > 2:
1906                raise AddressValueError(address)
1907
1908            self._ip = self._ip_int_from_string(addr[0])
1909            self.ip = IPv6Address(self._ip)
1910
1911            if len(addr) == 2:
1912                # This may raise NetmaskValueError
1913                self._prefixlen = self._prefix_from_prefix_string(addr[1])
1914            else:
1915                self._prefixlen = self._max_prefixlen
1916
1917        self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen))
1918
1919        if strict:
1920            if self.ip != self.network:
1921                raise ValueError('%s has host bits set' %
1922                                 self.ip)
1923        if self._prefixlen == (self._max_prefixlen - 1):
1924            self.iterhosts = self.__iter__
1925
1926    @property
1927    def with_netmask(self):
1928        return self.with_prefixlen
1929