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