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