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