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