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