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