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