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