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