blob: bf4e01ee1203e2d7b71ea3765852f8ee204be9ac [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
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200581 def __str__(self):
582 return '%s/%d' % (str(self.network_address),
583 self.prefixlen)
584
Nick Coghlandc9b2552012-05-20 21:01:57 +1000585 def hosts(self):
586 """Generate Iterator over usable hosts in a network.
587
Sandro Tosib95c6342012-05-23 23:17:22 +0200588 This is like __iter__ except it doesn't return the network
589 or broadcast addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000590
591 """
592 cur = int(self.network_address) + 1
593 bcast = int(self.broadcast_address) - 1
594 while cur <= bcast:
595 cur += 1
Nick Coghlan51c30672012-05-27 00:25:58 +1000596 yield self._address_class(cur - 1)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000597
598 def __iter__(self):
599 cur = int(self.network_address)
600 bcast = int(self.broadcast_address)
601 while cur <= bcast:
602 cur += 1
Nick Coghlan51c30672012-05-27 00:25:58 +1000603 yield self._address_class(cur - 1)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000604
605 def __getitem__(self, n):
606 network = int(self.network_address)
607 broadcast = int(self.broadcast_address)
608 if n >= 0:
609 if network + n > broadcast:
610 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000611 return self._address_class(network + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000612 else:
613 n += 1
614 if broadcast + n < network:
615 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000616 return self._address_class(broadcast + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000617
618 def __lt__(self, other):
619 if self._version != other._version:
620 raise TypeError('%s and %s are not of the same version' % (
621 str(self), str(other)))
622 if not isinstance(other, _BaseNetwork):
623 raise TypeError('%s and %s are not of the same type' % (
624 str(self), str(other)))
625 if self.network_address != other.network_address:
626 return self.network_address < other.network_address
627 if self.netmask != other.netmask:
628 return self.netmask < other.netmask
629 return False
630
631 def __gt__(self, other):
632 if self._version != other._version:
633 raise TypeError('%s and %s are not of the same version' % (
634 str(self), str(other)))
635 if not isinstance(other, _BaseNetwork):
636 raise TypeError('%s and %s are not of the same type' % (
637 str(self), str(other)))
638 if self.network_address != other.network_address:
639 return self.network_address > other.network_address
640 if self.netmask != other.netmask:
641 return self.netmask > other.netmask
642 return False
643
644 def __le__(self, other):
645 gt = self.__gt__(other)
646 if gt is NotImplemented:
647 return NotImplemented
648 return not gt
649
650 def __ge__(self, other):
651 lt = self.__lt__(other)
652 if lt is NotImplemented:
653 return NotImplemented
654 return not lt
655
656 def __eq__(self, other):
657 if not isinstance(other, _BaseNetwork):
658 raise TypeError('%s and %s are not of the same type' % (
659 str(self), str(other)))
660 return (self._version == other._version and
661 self.network_address == other.network_address and
662 int(self.netmask) == int(other.netmask))
663
664 def __ne__(self, other):
665 eq = self.__eq__(other)
666 if eq is NotImplemented:
667 return NotImplemented
668 return not eq
669
Nick Coghlandc9b2552012-05-20 21:01:57 +1000670 def __hash__(self):
671 return hash(int(self.network_address) ^ int(self.netmask))
672
673 def __contains__(self, other):
674 # always false if one is v4 and the other is v6.
675 if self._version != other._version:
676 return False
677 # dealing with another network.
678 if isinstance(other, _BaseNetwork):
679 return False
680 # dealing with another address
681 else:
682 # address
683 return (int(self.network_address) <= int(other._ip) <=
684 int(self.broadcast_address))
685
686 def overlaps(self, other):
687 """Tell if self is partly contained in other."""
688 return self.network_address in other or (
689 self.broadcast_address in other or (
690 other.network_address in self or (
691 other.broadcast_address in self)))
692
693 @property
694 def broadcast_address(self):
695 x = self._cache.get('broadcast_address')
696 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000697 x = self._address_class(int(self.network_address) |
698 int(self.hostmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000699 self._cache['broadcast_address'] = x
700 return x
701
702 @property
703 def hostmask(self):
704 x = self._cache.get('hostmask')
705 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000706 x = self._address_class(int(self.netmask) ^ self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000707 self._cache['hostmask'] = x
708 return x
709
710 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000711 def with_prefixlen(self):
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200712 return '%s/%d' % (str(self.network_address), self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000713
714 @property
715 def with_netmask(self):
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200716 return '%s/%s' % (str(self.network_address), str(self.netmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000717
718 @property
719 def with_hostmask(self):
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200720 return '%s/%s' % (str(self.network_address), str(self.hostmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000721
722 @property
723 def num_addresses(self):
724 """Number of hosts in the current subnet."""
725 return int(self.broadcast_address) - int(self.network_address) + 1
726
727 @property
728 def version(self):
729 raise NotImplementedError('BaseNet has no version')
730
731 @property
Nick Coghlan51c30672012-05-27 00:25:58 +1000732 def _address_class(self):
733 raise NotImplementedError('BaseNet has no associated address class')
734
735 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000736 def prefixlen(self):
737 return self._prefixlen
738
739 def address_exclude(self, other):
740 """Remove an address from a larger block.
741
742 For example:
743
744 addr1 = ip_network('192.0.2.0/28')
745 addr2 = ip_network('192.0.2.1/32')
746 addr1.address_exclude(addr2) =
747 [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
748 IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
749
750 or IPv6:
751
752 addr1 = ip_network('2001:db8::1/32')
753 addr2 = ip_network('2001:db8::1/128')
754 addr1.address_exclude(addr2) =
755 [ip_network('2001:db8::1/128'),
756 ip_network('2001:db8::2/127'),
757 ip_network('2001:db8::4/126'),
758 ip_network('2001:db8::8/125'),
759 ...
760 ip_network('2001:db8:8000::/33')]
761
762 Args:
763 other: An IPv4Network or IPv6Network object of the same type.
764
765 Returns:
766 An iterator of the the IPv(4|6)Network objects which is self
767 minus other.
768
769 Raises:
770 TypeError: If self and other are of difffering address
771 versions, or if other is not a network object.
772 ValueError: If other is not completely contained by self.
773
774 """
775 if not self._version == other._version:
776 raise TypeError("%s and %s are not of the same version" % (
777 str(self), str(other)))
778
779 if not isinstance(other, _BaseNetwork):
780 raise TypeError("%s is not a network object" % str(other))
781
782 if not (other.network_address >= self.network_address and
783 other.broadcast_address <= self.broadcast_address):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200784 raise ValueError('%s not contained in %s' % (other, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000785 if other == self:
786 raise StopIteration
787
Nick Coghlandc9b2552012-05-20 21:01:57 +1000788 # Make sure we're comparing the network of other.
Nick Coghlan51c30672012-05-27 00:25:58 +1000789 other = other.__class__('%s/%s' % (str(other.network_address),
790 str(other.prefixlen)))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000791
792 s1, s2 = self.subnets()
793 while s1 != other and s2 != other:
794 if (other.network_address >= s1.network_address and
795 other.broadcast_address <= s1.broadcast_address):
796 yield s2
797 s1, s2 = s1.subnets()
798 elif (other.network_address >= s2.network_address and
799 other.broadcast_address <= s2.broadcast_address):
800 yield s1
801 s1, s2 = s2.subnets()
802 else:
803 # If we got here, there's a bug somewhere.
804 raise AssertionError('Error performing exclusion: '
805 's1: %s s2: %s other: %s' %
806 (str(s1), str(s2), str(other)))
807 if s1 == other:
808 yield s2
809 elif s2 == other:
810 yield s1
811 else:
812 # If we got here, there's a bug somewhere.
813 raise AssertionError('Error performing exclusion: '
814 's1: %s s2: %s other: %s' %
815 (str(s1), str(s2), str(other)))
816
817 def compare_networks(self, other):
818 """Compare two IP objects.
819
820 This is only concerned about the comparison of the integer
821 representation of the network addresses. This means that the
822 host bits aren't considered at all in this method. If you want
823 to compare host bits, you can easily enough do a
824 'HostA._ip < HostB._ip'
825
826 Args:
827 other: An IP object.
828
829 Returns:
830 If the IP versions of self and other are the same, returns:
831
832 -1 if self < other:
833 eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
834 IPv6Network('2001:db8::1000/124') <
835 IPv6Network('2001:db8::2000/124')
836 0 if self == other
837 eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
838 IPv6Network('2001:db8::1000/124') ==
839 IPv6Network('2001:db8::1000/124')
840 1 if self > other
841 eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
842 IPv6Network('2001:db8::2000/124') >
843 IPv6Network('2001:db8::1000/124')
844
845 Raises:
846 TypeError if the IP versions are different.
847
848 """
849 # does this need to raise a ValueError?
850 if self._version != other._version:
851 raise TypeError('%s and %s are not of the same type' % (
852 str(self), str(other)))
853 # self._version == other._version below here:
854 if self.network_address < other.network_address:
855 return -1
856 if self.network_address > other.network_address:
857 return 1
858 # self.network_address == other.network_address below here:
859 if self.netmask < other.netmask:
860 return -1
861 if self.netmask > other.netmask:
862 return 1
863 return 0
864
865 def _get_networks_key(self):
866 """Network-only key function.
867
868 Returns an object that identifies this address' network and
869 netmask. This function is a suitable "key" argument for sorted()
870 and list.sort().
871
872 """
873 return (self._version, self.network_address, self.netmask)
874
875 def subnets(self, prefixlen_diff=1, new_prefix=None):
876 """The subnets which join to make the current subnet.
877
878 In the case that self contains only one IP
879 (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
880 for IPv6), yield an iterator with just ourself.
881
882 Args:
883 prefixlen_diff: An integer, the amount the prefix length
884 should be increased by. This should not be set if
885 new_prefix is also set.
886 new_prefix: The desired new prefix length. This must be a
887 larger number (smaller prefix) than the existing prefix.
888 This should not be set if prefixlen_diff is also set.
889
890 Returns:
891 An iterator of IPv(4|6) objects.
892
893 Raises:
894 ValueError: The prefixlen_diff is too small or too large.
895 OR
896 prefixlen_diff and new_prefix are both set or new_prefix
897 is a smaller number than the current prefix (smaller
898 number means a larger network)
899
900 """
901 if self._prefixlen == self._max_prefixlen:
902 yield self
903 return
904
905 if new_prefix is not None:
906 if new_prefix < self._prefixlen:
907 raise ValueError('new prefix must be longer')
908 if prefixlen_diff != 1:
909 raise ValueError('cannot set prefixlen_diff and new_prefix')
910 prefixlen_diff = new_prefix - self._prefixlen
911
912 if prefixlen_diff < 0:
913 raise ValueError('prefix length diff must be > 0')
914 new_prefixlen = self._prefixlen + prefixlen_diff
915
916 if not self._is_valid_netmask(str(new_prefixlen)):
917 raise ValueError(
918 'prefix length diff %d is invalid for netblock %s' % (
919 new_prefixlen, str(self)))
920
Nick Coghlan51c30672012-05-27 00:25:58 +1000921 first = self.__class__('%s/%s' %
922 (str(self.network_address),
923 str(self._prefixlen + prefixlen_diff)))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000924
925 yield first
926 current = first
927 while True:
928 broadcast = current.broadcast_address
929 if broadcast == self.broadcast_address:
930 return
Nick Coghlan51c30672012-05-27 00:25:58 +1000931 new_addr = self._address_class(int(broadcast) + 1)
932 current = self.__class__('%s/%s' % (str(new_addr),
933 str(new_prefixlen)))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000934
935 yield current
936
Nick Coghlandc9b2552012-05-20 21:01:57 +1000937 def supernet(self, prefixlen_diff=1, new_prefix=None):
938 """The supernet containing the current network.
939
940 Args:
941 prefixlen_diff: An integer, the amount the prefix length of
942 the network should be decreased by. For example, given a
943 /24 network and a prefixlen_diff of 3, a supernet with a
944 /21 netmask is returned.
945
946 Returns:
947 An IPv4 network object.
948
949 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200950 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
951 a negative prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000952 OR
953 If prefixlen_diff and new_prefix are both set or new_prefix is a
954 larger number than the current prefix (larger number means a
955 smaller network)
956
957 """
958 if self._prefixlen == 0:
959 return self
960
961 if new_prefix is not None:
962 if new_prefix > self._prefixlen:
963 raise ValueError('new prefix must be shorter')
964 if prefixlen_diff != 1:
965 raise ValueError('cannot set prefixlen_diff and new_prefix')
966 prefixlen_diff = self._prefixlen - new_prefix
967
Nick Coghlandc9b2552012-05-20 21:01:57 +1000968 if self.prefixlen - prefixlen_diff < 0:
969 raise ValueError(
970 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
971 (self.prefixlen, prefixlen_diff))
972 # TODO (pmoody): optimize this.
Nick Coghlan51c30672012-05-27 00:25:58 +1000973 t = self.__class__('%s/%d' % (str(self.network_address),
974 self.prefixlen - prefixlen_diff),
975 strict=False)
976 return t.__class__('%s/%d' % (str(t.network_address), t.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000977
978
Hynek Schlawackc4b78a32012-06-01 11:48:32 +0200979class _BaseV4:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000980
981 """Base IPv4 object.
982
983 The following methods are used by IPv4 objects in both single IP
984 addresses and networks.
985
986 """
987
988 # Equivalent to 255.255.255.255 or 32 bits of 1's.
989 _ALL_ONES = (2**IPV4LENGTH) - 1
990 _DECIMAL_DIGITS = frozenset('0123456789')
991
992 def __init__(self, address):
993 self._version = 4
994 self._max_prefixlen = IPV4LENGTH
995
996 def _explode_shorthand_ip_string(self):
997 return str(self)
998
999 def _ip_int_from_string(self, ip_str):
1000 """Turn the given IP string into an integer for comparison.
1001
1002 Args:
1003 ip_str: A string, the IP ip_str.
1004
1005 Returns:
1006 The IP ip_str as an integer.
1007
1008 Raises:
1009 AddressValueError: if ip_str isn't a valid IPv4 Address.
1010
1011 """
1012 octets = ip_str.split('.')
1013 if len(octets) != 4:
1014 raise AddressValueError(ip_str)
1015
1016 packed_ip = 0
1017 for oc in octets:
1018 try:
1019 packed_ip = (packed_ip << 8) | self._parse_octet(oc)
1020 except ValueError:
1021 raise AddressValueError(ip_str)
1022 return packed_ip
1023
1024 def _parse_octet(self, octet_str):
1025 """Convert a decimal octet into an integer.
1026
1027 Args:
1028 octet_str: A string, the number to parse.
1029
1030 Returns:
1031 The octet as an integer.
1032
1033 Raises:
1034 ValueError: if the octet isn't strictly a decimal from [0..255].
1035
1036 """
1037 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1038 if not self._DECIMAL_DIGITS.issuperset(octet_str):
1039 raise ValueError
1040 octet_int = int(octet_str, 10)
1041 # Disallow leading zeroes, because no clear standard exists on
1042 # whether these should be interpreted as decimal or octal.
1043 if octet_int > 255 or (octet_str[0] == '0' and len(octet_str) > 1):
1044 raise ValueError
1045 return octet_int
1046
1047 def _string_from_ip_int(self, ip_int):
1048 """Turns a 32-bit integer into dotted decimal notation.
1049
1050 Args:
1051 ip_int: An integer, the IP address.
1052
1053 Returns:
1054 The IP address as a string in dotted decimal notation.
1055
1056 """
1057 octets = []
1058 for _ in range(4):
1059 octets.insert(0, str(ip_int & 0xFF))
1060 ip_int >>= 8
1061 return '.'.join(octets)
1062
1063 @property
1064 def max_prefixlen(self):
1065 return self._max_prefixlen
1066
1067 @property
1068 def version(self):
1069 return self._version
1070
1071 @property
1072 def is_reserved(self):
1073 """Test if the address is otherwise IETF reserved.
1074
1075 Returns:
1076 A boolean, True if the address is within the
1077 reserved IPv4 Network range.
1078
1079 """
1080 reserved_network = IPv4Network('240.0.0.0/4')
1081 if isinstance(self, _BaseAddress):
1082 return self in reserved_network
1083 return (self.network_address in reserved_network and
1084 self.broadcast_address in reserved_network)
1085
1086 @property
1087 def is_private(self):
1088 """Test if this address is allocated for private networks.
1089
1090 Returns:
1091 A boolean, True if the address is reserved per RFC 1918.
1092
1093 """
1094 private_10 = IPv4Network('10.0.0.0/8')
1095 private_172 = IPv4Network('172.16.0.0/12')
1096 private_192 = IPv4Network('192.168.0.0/16')
1097 if isinstance(self, _BaseAddress):
1098 return (self in private_10 or self in private_172 or
1099 self in private_192)
1100 else:
1101 return ((self.network_address in private_10 and
1102 self.broadcast_address in private_10) or
1103 (self.network_address in private_172 and
1104 self.broadcast_address in private_172) or
1105 (self.network_address in private_192 and
1106 self.broadcast_address in private_192))
1107
1108 @property
1109 def is_multicast(self):
1110 """Test if the address is reserved for multicast use.
1111
1112 Returns:
1113 A boolean, True if the address is multicast.
1114 See RFC 3171 for details.
1115
1116 """
1117 multicast_network = IPv4Network('224.0.0.0/4')
1118 if isinstance(self, _BaseAddress):
1119 return self in IPv4Network('224.0.0.0/4')
1120 return (self.network_address in multicast_network and
1121 self.broadcast_address in multicast_network)
1122
1123 @property
1124 def is_unspecified(self):
1125 """Test if the address is unspecified.
1126
1127 Returns:
1128 A boolean, True if this is the unspecified address as defined in
1129 RFC 5735 3.
1130
1131 """
1132 unspecified_address = IPv4Address('0.0.0.0')
1133 if isinstance(self, _BaseAddress):
Hynek Schlawackbcd30442012-06-04 14:19:39 +02001134 return self == unspecified_address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001135 return (self.network_address == self.broadcast_address ==
1136 unspecified_address)
1137
1138 @property
1139 def is_loopback(self):
1140 """Test if the address is a loopback address.
1141
1142 Returns:
1143 A boolean, True if the address is a loopback per RFC 3330.
1144
1145 """
1146 loopback_address = IPv4Network('127.0.0.0/8')
1147 if isinstance(self, _BaseAddress):
1148 return self in loopback_address
1149
1150 return (self.network_address in loopback_address and
1151 self.broadcast_address in loopback_address)
1152
1153 @property
1154 def is_link_local(self):
1155 """Test if the address is reserved for link-local.
1156
1157 Returns:
1158 A boolean, True if the address is link-local per RFC 3927.
1159
1160 """
1161 linklocal_network = IPv4Network('169.254.0.0/16')
1162 if isinstance(self, _BaseAddress):
1163 return self in linklocal_network
1164 return (self.network_address in linklocal_network and
1165 self.broadcast_address in linklocal_network)
1166
1167
1168class IPv4Address(_BaseV4, _BaseAddress):
1169
1170 """Represent and manipulate single IPv4 Addresses."""
1171
1172 def __init__(self, address):
1173
1174 """
1175 Args:
1176 address: A string or integer representing the IP
1177
1178 Additionally, an integer can be passed, so
1179 IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1180 or, more generally
1181 IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1182 IPv4Address('192.0.2.1')
1183
1184 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001185 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001186
1187 """
1188 _BaseAddress.__init__(self, address)
1189 _BaseV4.__init__(self, address)
1190
1191 # Efficient constructor from integer.
1192 if isinstance(address, int):
1193 self._ip = address
1194 if address < 0 or address > self._ALL_ONES:
1195 raise AddressValueError(address)
1196 return
1197
1198 # Constructing from a packed address
1199 if isinstance(address, bytes) and len(address) == 4:
1200 self._ip = struct.unpack('!I', address)[0]
1201 return
1202
1203 # Assume input argument to be string or any object representation
1204 # which converts into a formatted IP string.
1205 addr_str = str(address)
1206 self._ip = self._ip_int_from_string(addr_str)
1207
1208 @property
1209 def packed(self):
1210 """The binary representation of this address."""
1211 return v4_int_to_packed(self._ip)
1212
1213
1214class IPv4Interface(IPv4Address):
1215
1216 # the valid octets for host and netmasks. only useful for IPv4.
1217 _valid_mask_octets = set((255, 254, 252, 248, 240, 224, 192, 128, 0))
1218
1219 def __init__(self, address):
1220 if isinstance(address, (bytes, int)):
1221 IPv4Address.__init__(self, address)
1222 self.network = IPv4Network(self._ip)
1223 self._prefixlen = self._max_prefixlen
1224 return
1225
1226 addr = str(address).split('/')
1227 if len(addr) > 2:
1228 raise AddressValueError(address)
1229 IPv4Address.__init__(self, addr[0])
1230
1231 self.network = IPv4Network(address, strict=False)
1232 self._prefixlen = self.network._prefixlen
1233
1234 self.netmask = self.network.netmask
1235 self.hostmask = self.network.hostmask
1236
Nick Coghlandc9b2552012-05-20 21:01:57 +10001237 def __str__(self):
1238 return '%s/%d' % (self._string_from_ip_int(self._ip),
1239 self.network.prefixlen)
1240
1241 def __eq__(self, other):
1242 try:
1243 return (IPv4Address.__eq__(self, other) and
1244 self.network == other.network)
1245 except AttributeError:
1246 return NotImplemented
1247
1248 def __hash__(self):
1249 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1250
1251 def _is_valid_netmask(self, netmask):
1252 """Verify that the netmask is valid.
1253
1254 Args:
1255 netmask: A string, either a prefix or dotted decimal
1256 netmask.
1257
1258 Returns:
1259 A boolean, True if the prefix represents a valid IPv4
1260 netmask.
1261
1262 """
1263 mask = netmask.split('.')
1264 if len(mask) == 4:
1265 if [x for x in mask if int(x) not in self._valid_mask_octets]:
1266 return False
1267 if [y for idx, y in enumerate(mask) if idx > 0 and
1268 y > mask[idx - 1]]:
1269 return False
1270 return True
1271 try:
1272 netmask = int(netmask)
1273 except ValueError:
1274 return False
1275 return 0 <= netmask <= self._max_prefixlen
1276
1277 def _is_hostmask(self, ip_str):
1278 """Test if the IP string is a hostmask (rather than a netmask).
1279
1280 Args:
1281 ip_str: A string, the potential hostmask.
1282
1283 Returns:
1284 A boolean, True if the IP string is a hostmask.
1285
1286 """
1287 bits = ip_str.split('.')
1288 try:
1289 parts = [int(x) for x in bits if int(x) in self._valid_mask_octets]
1290 except ValueError:
1291 return False
1292 if len(parts) != len(bits):
1293 return False
1294 if parts[0] < parts[-1]:
1295 return True
1296 return False
1297
Nick Coghlandc9b2552012-05-20 21:01:57 +10001298 @property
1299 def prefixlen(self):
1300 return self._prefixlen
1301
1302 @property
1303 def ip(self):
1304 return IPv4Address(self._ip)
1305
1306 @property
1307 def with_prefixlen(self):
1308 return self
1309
1310 @property
1311 def with_netmask(self):
1312 return '%s/%s' % (self._string_from_ip_int(self._ip),
1313 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001314
Nick Coghlandc9b2552012-05-20 21:01:57 +10001315 @property
1316 def with_hostmask(self):
1317 return '%s/%s' % (self._string_from_ip_int(self._ip),
1318 self.hostmask)
1319
1320
1321class IPv4Network(_BaseV4, _BaseNetwork):
1322
1323 """This class represents and manipulates 32-bit IPv4 network + addresses..
1324
1325 Attributes: [examples for IPv4Network('192.0.2.0/27')]
1326 .network_address: IPv4Address('192.0.2.0')
1327 .hostmask: IPv4Address('0.0.0.31')
1328 .broadcast_address: IPv4Address('192.0.2.32')
1329 .netmask: IPv4Address('255.255.255.224')
1330 .prefixlen: 27
1331
1332 """
Nick Coghlan51c30672012-05-27 00:25:58 +10001333 # Class to use when creating address objects
1334 # TODO (ncoghlan): Investigate using IPv4Interface instead
1335 _address_class = IPv4Address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001336
1337 # the valid octets for host and netmasks. only useful for IPv4.
1338 _valid_mask_octets = set((255, 254, 252, 248, 240, 224, 192, 128, 0))
1339
1340 def __init__(self, address, strict=True):
1341
1342 """Instantiate a new IPv4 network object.
1343
1344 Args:
1345 address: A string or integer representing the IP [& network].
1346 '192.0.2.0/24'
1347 '192.0.2.0/255.255.255.0'
1348 '192.0.0.2/0.0.0.255'
1349 are all functionally the same in IPv4. Similarly,
1350 '192.0.2.1'
1351 '192.0.2.1/255.255.255.255'
1352 '192.0.2.1/32'
1353 are also functionaly equivalent. That is to say, failing to
1354 provide a subnetmask will create an object with a mask of /32.
1355
1356 If the mask (portion after the / in the argument) is given in
1357 dotted quad form, it is treated as a netmask if it starts with a
1358 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1359 starts with a zero field (e.g. 0.255.255.255 == /8), with the
1360 single exception of an all-zero mask which is treated as a
1361 netmask == /0. If no mask is given, a default of /32 is used.
1362
1363 Additionally, an integer can be passed, so
1364 IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1365 or, more generally
1366 IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1367 IPv4Interface('192.0.2.1')
1368
1369 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001370 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001371 NetmaskValueError: If the netmask isn't valid for
1372 an IPv4 address.
Sandro Tosib4386d32012-06-02 17:14:22 +02001373 ValueError: If strict is True and a network address is not
Nick Coghlandc9b2552012-05-20 21:01:57 +10001374 supplied.
1375
1376 """
1377
1378 _BaseV4.__init__(self, address)
1379 _BaseNetwork.__init__(self, address)
1380
1381 # Constructing from a packed address
1382 if isinstance(address, bytes) and len(address) == 4:
1383 self.network_address = IPv4Address(
1384 struct.unpack('!I', address)[0])
1385 self._prefixlen = self._max_prefixlen
1386 self.netmask = IPv4Address(self._ALL_ONES)
1387 #fixme: address/network test here
1388 return
1389
1390 # Efficient constructor from integer.
1391 if isinstance(address, int):
1392 self._prefixlen = self._max_prefixlen
1393 self.netmask = IPv4Address(self._ALL_ONES)
1394 if address < 0 or address > self._ALL_ONES:
1395 raise AddressValueError(address)
1396 self.network_address = IPv4Address(address)
1397 #fixme: address/network test here.
1398 return
1399
1400 # Assume input argument to be string or any object representation
1401 # which converts into a formatted IP prefix string.
1402 addr = str(address).split('/')
1403 self.network_address = IPv4Address(self._ip_int_from_string(addr[0]))
1404
1405 if len(addr) > 2:
1406 raise AddressValueError(address)
1407
1408 if len(addr) == 2:
1409 mask = addr[1].split('.')
1410
1411 if len(mask) == 4:
1412 # We have dotted decimal netmask.
1413 if self._is_valid_netmask(addr[1]):
1414 self.netmask = IPv4Address(self._ip_int_from_string(
1415 addr[1]))
1416 elif self._is_hostmask(addr[1]):
1417 self.netmask = IPv4Address(
1418 self._ip_int_from_string(addr[1]) ^ self._ALL_ONES)
1419 else:
1420 raise NetmaskValueError('%s is not a valid netmask'
1421 % addr[1])
1422
1423 self._prefixlen = self._prefix_from_ip_int(int(self.netmask))
1424 else:
1425 # We have a netmask in prefix length form.
1426 if not self._is_valid_netmask(addr[1]):
1427 raise NetmaskValueError(addr[1])
1428 self._prefixlen = int(addr[1])
1429 self.netmask = IPv4Address(self._ip_int_from_prefix(
1430 self._prefixlen))
1431 else:
1432 self._prefixlen = self._max_prefixlen
1433 self.netmask = IPv4Address(self._ip_int_from_prefix(
1434 self._prefixlen))
1435
1436 if strict:
1437 if (IPv4Address(int(self.network_address) & int(self.netmask)) !=
1438 self.network_address):
1439 raise ValueError('%s has host bits set' % self)
1440 self.network_address = IPv4Address(int(self.network_address) &
1441 int(self.netmask))
1442
1443 if self._prefixlen == (self._max_prefixlen - 1):
1444 self.hosts = self.__iter__
1445
1446 @property
1447 def packed(self):
1448 """The binary representation of this address."""
1449 return v4_int_to_packed(self.network_address)
1450
Nick Coghlandc9b2552012-05-20 21:01:57 +10001451 def _is_valid_netmask(self, netmask):
1452 """Verify that the netmask is valid.
1453
1454 Args:
1455 netmask: A string, either a prefix or dotted decimal
1456 netmask.
1457
1458 Returns:
1459 A boolean, True if the prefix represents a valid IPv4
1460 netmask.
1461
1462 """
1463 mask = netmask.split('.')
1464 if len(mask) == 4:
1465 if [x for x in mask if int(x) not in self._valid_mask_octets]:
1466 return False
1467 if [y for idx, y in enumerate(mask) if idx > 0 and
1468 y > mask[idx - 1]]:
1469 return False
1470 return True
1471 try:
1472 netmask = int(netmask)
1473 except ValueError:
1474 return False
1475 return 0 <= netmask <= self._max_prefixlen
1476
1477 def _is_hostmask(self, ip_str):
1478 """Test if the IP string is a hostmask (rather than a netmask).
1479
1480 Args:
1481 ip_str: A string, the potential hostmask.
1482
1483 Returns:
1484 A boolean, True if the IP string is a hostmask.
1485
1486 """
1487 bits = ip_str.split('.')
1488 try:
1489 parts = [int(x) for x in bits if int(x) in self._valid_mask_octets]
1490 except ValueError:
1491 return False
1492 if len(parts) != len(bits):
1493 return False
1494 if parts[0] < parts[-1]:
1495 return True
1496 return False
1497
Nick Coghlandc9b2552012-05-20 21:01:57 +10001498
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001499class _BaseV6:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001500
1501 """Base IPv6 object.
1502
1503 The following methods are used by IPv6 objects in both single IP
1504 addresses and networks.
1505
1506 """
1507
1508 _ALL_ONES = (2**IPV6LENGTH) - 1
1509 _HEXTET_COUNT = 8
1510 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
1511
1512 def __init__(self, address):
1513 self._version = 6
1514 self._max_prefixlen = IPV6LENGTH
1515
1516 def _ip_int_from_string(self, ip_str):
1517 """Turn an IPv6 ip_str into an integer.
1518
1519 Args:
1520 ip_str: A string, the IPv6 ip_str.
1521
1522 Returns:
1523 An int, the IPv6 address
1524
1525 Raises:
1526 AddressValueError: if ip_str isn't a valid IPv6 Address.
1527
1528 """
1529 parts = ip_str.split(':')
1530
1531 # An IPv6 address needs at least 2 colons (3 parts).
1532 if len(parts) < 3:
1533 raise AddressValueError(ip_str)
1534
1535 # If the address has an IPv4-style suffix, convert it to hexadecimal.
1536 if '.' in parts[-1]:
1537 ipv4_int = IPv4Address(parts.pop())._ip
1538 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1539 parts.append('%x' % (ipv4_int & 0xFFFF))
1540
1541 # An IPv6 address can't have more than 8 colons (9 parts).
1542 if len(parts) > self._HEXTET_COUNT + 1:
1543 raise AddressValueError(ip_str)
1544
1545 # Disregarding the endpoints, find '::' with nothing in between.
1546 # This indicates that a run of zeroes has been skipped.
1547 try:
1548 skip_index, = (
1549 [i for i in range(1, len(parts) - 1) if not parts[i]] or
1550 [None])
1551 except ValueError:
1552 # Can't have more than one '::'
1553 raise AddressValueError(ip_str)
1554
1555 # parts_hi is the number of parts to copy from above/before the '::'
1556 # parts_lo is the number of parts to copy from below/after the '::'
1557 if skip_index is not None:
1558 # If we found a '::', then check if it also covers the endpoints.
1559 parts_hi = skip_index
1560 parts_lo = len(parts) - skip_index - 1
1561 if not parts[0]:
1562 parts_hi -= 1
1563 if parts_hi:
1564 raise AddressValueError(ip_str) # ^: requires ^::
1565 if not parts[-1]:
1566 parts_lo -= 1
1567 if parts_lo:
1568 raise AddressValueError(ip_str) # :$ requires ::$
1569 parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo)
1570 if parts_skipped < 1:
1571 raise AddressValueError(ip_str)
1572 else:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001573 # Otherwise, allocate the entire address to parts_hi. The
1574 # endpoints could still be empty, but _parse_hextet() will check
1575 # for that.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001576 if len(parts) != self._HEXTET_COUNT:
1577 raise AddressValueError(ip_str)
1578 parts_hi = len(parts)
1579 parts_lo = 0
1580 parts_skipped = 0
1581
1582 try:
1583 # Now, parse the hextets into a 128-bit integer.
1584 ip_int = 0
1585 for i in range(parts_hi):
1586 ip_int <<= 16
1587 ip_int |= self._parse_hextet(parts[i])
1588 ip_int <<= 16 * parts_skipped
1589 for i in range(-parts_lo, 0):
1590 ip_int <<= 16
1591 ip_int |= self._parse_hextet(parts[i])
1592 return ip_int
1593 except ValueError:
1594 raise AddressValueError(ip_str)
1595
1596 def _parse_hextet(self, hextet_str):
1597 """Convert an IPv6 hextet string into an integer.
1598
1599 Args:
1600 hextet_str: A string, the number to parse.
1601
1602 Returns:
1603 The hextet as an integer.
1604
1605 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001606 ValueError: if the input isn't strictly a hex number from
1607 [0..FFFF].
Nick Coghlandc9b2552012-05-20 21:01:57 +10001608
1609 """
1610 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1611 if not self._HEX_DIGITS.issuperset(hextet_str):
1612 raise ValueError
1613 hextet_int = int(hextet_str, 16)
1614 if hextet_int > 0xFFFF:
1615 raise ValueError
1616 return hextet_int
1617
1618 def _compress_hextets(self, hextets):
1619 """Compresses a list of hextets.
1620
1621 Compresses a list of strings, replacing the longest continuous
1622 sequence of "0" in the list with "" and adding empty strings at
1623 the beginning or at the end of the string such that subsequently
1624 calling ":".join(hextets) will produce the compressed version of
1625 the IPv6 address.
1626
1627 Args:
1628 hextets: A list of strings, the hextets to compress.
1629
1630 Returns:
1631 A list of strings.
1632
1633 """
1634 best_doublecolon_start = -1
1635 best_doublecolon_len = 0
1636 doublecolon_start = -1
1637 doublecolon_len = 0
1638 for index in range(len(hextets)):
1639 if hextets[index] == '0':
1640 doublecolon_len += 1
1641 if doublecolon_start == -1:
1642 # Start of a sequence of zeros.
1643 doublecolon_start = index
1644 if doublecolon_len > best_doublecolon_len:
1645 # This is the longest sequence of zeros so far.
1646 best_doublecolon_len = doublecolon_len
1647 best_doublecolon_start = doublecolon_start
1648 else:
1649 doublecolon_len = 0
1650 doublecolon_start = -1
1651
1652 if best_doublecolon_len > 1:
1653 best_doublecolon_end = (best_doublecolon_start +
1654 best_doublecolon_len)
1655 # For zeros at the end of the address.
1656 if best_doublecolon_end == len(hextets):
1657 hextets += ['']
1658 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1659 # For zeros at the beginning of the address.
1660 if best_doublecolon_start == 0:
1661 hextets = [''] + hextets
1662
1663 return hextets
1664
1665 def _string_from_ip_int(self, ip_int=None):
1666 """Turns a 128-bit integer into hexadecimal notation.
1667
1668 Args:
1669 ip_int: An integer, the IP address.
1670
1671 Returns:
1672 A string, the hexadecimal representation of the address.
1673
1674 Raises:
1675 ValueError: The address is bigger than 128 bits of all ones.
1676
1677 """
1678 if not ip_int and ip_int != 0:
1679 ip_int = int(self._ip)
1680
1681 if ip_int > self._ALL_ONES:
1682 raise ValueError('IPv6 address is too large')
1683
1684 hex_str = '%032x' % ip_int
1685 hextets = []
1686 for x in range(0, 32, 4):
1687 hextets.append('%x' % int(hex_str[x:x+4], 16))
1688
1689 hextets = self._compress_hextets(hextets)
1690 return ':'.join(hextets)
1691
1692 def _explode_shorthand_ip_string(self):
1693 """Expand a shortened IPv6 address.
1694
1695 Args:
1696 ip_str: A string, the IPv6 address.
1697
1698 Returns:
1699 A string, the expanded IPv6 address.
1700
1701 """
1702 if isinstance(self, IPv6Network):
1703 ip_str = str(self.network_address)
1704 elif isinstance(self, IPv6Interface):
1705 ip_str = str(self.ip)
1706 else:
1707 ip_str = str(self)
1708
1709 ip_int = self._ip_int_from_string(ip_str)
1710 parts = []
1711 for i in range(self._HEXTET_COUNT):
1712 parts.append('%04x' % (ip_int & 0xFFFF))
1713 ip_int >>= 16
1714 parts.reverse()
1715 if isinstance(self, (_BaseNetwork, IPv6Interface)):
1716 return '%s/%d' % (':'.join(parts), self.prefixlen)
1717 return ':'.join(parts)
1718
1719 @property
1720 def max_prefixlen(self):
1721 return self._max_prefixlen
1722
1723 @property
1724 def packed(self):
1725 """The binary representation of this address."""
1726 return v6_int_to_packed(self._ip)
1727
1728 @property
1729 def version(self):
1730 return self._version
1731
1732 @property
1733 def is_multicast(self):
1734 """Test if the address is reserved for multicast use.
1735
1736 Returns:
1737 A boolean, True if the address is a multicast address.
1738 See RFC 2373 2.7 for details.
1739
1740 """
1741 multicast_network = IPv6Network('ff00::/8')
1742 if isinstance(self, _BaseAddress):
1743 return self in multicast_network
1744 return (self.network_address in multicast_network and
1745 self.broadcast_address in multicast_network)
1746
1747 @property
1748 def is_reserved(self):
1749 """Test if the address is otherwise IETF reserved.
1750
1751 Returns:
1752 A boolean, True if the address is within one of the
1753 reserved IPv6 Network ranges.
1754
1755 """
1756 reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'),
1757 IPv6Network('200::/7'), IPv6Network('400::/6'),
1758 IPv6Network('800::/5'), IPv6Network('1000::/4'),
1759 IPv6Network('4000::/3'), IPv6Network('6000::/3'),
1760 IPv6Network('8000::/3'), IPv6Network('A000::/3'),
1761 IPv6Network('C000::/3'), IPv6Network('E000::/4'),
1762 IPv6Network('F000::/5'), IPv6Network('F800::/6'),
1763 IPv6Network('FE00::/9')]
1764
1765 if isinstance(self, _BaseAddress):
1766 return len([x for x in reserved_networks if self in x]) > 0
1767 return len([x for x in reserved_networks if self.network_address in x
1768 and self.broadcast_address in x]) > 0
1769
1770 @property
1771 def is_link_local(self):
1772 """Test if the address is reserved for link-local.
1773
1774 Returns:
1775 A boolean, True if the address is reserved per RFC 4291.
1776
1777 """
1778 linklocal_network = IPv6Network('fe80::/10')
1779 if isinstance(self, _BaseAddress):
1780 return self in linklocal_network
1781 return (self.network_address in linklocal_network and
1782 self.broadcast_address in linklocal_network)
1783
1784 @property
1785 def is_site_local(self):
1786 """Test if the address is reserved for site-local.
1787
1788 Note that the site-local address space has been deprecated by RFC 3879.
1789 Use is_private to test if this address is in the space of unique local
1790 addresses as defined by RFC 4193.
1791
1792 Returns:
1793 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1794
1795 """
1796 sitelocal_network = IPv6Network('fec0::/10')
1797 if isinstance(self, _BaseAddress):
1798 return self in sitelocal_network
1799 return (self.network_address in sitelocal_network and
1800 self.broadcast_address in sitelocal_network)
1801
1802 @property
1803 def is_private(self):
1804 """Test if this address is allocated for private networks.
1805
1806 Returns:
1807 A boolean, True if the address is reserved per RFC 4193.
1808
1809 """
1810 private_network = IPv6Network('fc00::/7')
1811 if isinstance(self, _BaseAddress):
1812 return self in private_network
1813 return (self.network_address in private_network and
1814 self.broadcast_address in private_network)
1815
Nick Coghlandc9b2552012-05-20 21:01:57 +10001816 @property
1817 def ipv4_mapped(self):
1818 """Return the IPv4 mapped address.
1819
1820 Returns:
1821 If the IPv6 address is a v4 mapped address, return the
1822 IPv4 mapped address. Return None otherwise.
1823
1824 """
1825 if (self._ip >> 32) != 0xFFFF:
1826 return None
1827 return IPv4Address(self._ip & 0xFFFFFFFF)
1828
1829 @property
1830 def teredo(self):
1831 """Tuple of embedded teredo IPs.
1832
1833 Returns:
1834 Tuple of the (server, client) IPs or None if the address
1835 doesn't appear to be a teredo address (doesn't start with
1836 2001::/32)
1837
1838 """
1839 if (self._ip >> 96) != 0x20010000:
1840 return None
1841 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
1842 IPv4Address(~self._ip & 0xFFFFFFFF))
1843
1844 @property
1845 def sixtofour(self):
1846 """Return the IPv4 6to4 embedded address.
1847
1848 Returns:
1849 The IPv4 6to4-embedded address if present or None if the
1850 address doesn't appear to contain a 6to4 embedded address.
1851
1852 """
1853 if (self._ip >> 112) != 0x2002:
1854 return None
1855 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
1856
1857 @property
1858 def is_unspecified(self):
1859 """Test if the address is unspecified.
1860
1861 Returns:
1862 A boolean, True if this is the unspecified address as defined in
1863 RFC 2373 2.5.2.
1864
1865 """
1866 if isinstance(self, (IPv6Network, IPv6Interface)):
1867 return int(self.network_address) == 0 and getattr(
1868 self, '_prefixlen', 128) == 128
1869 return self._ip == 0
1870
1871 @property
1872 def is_loopback(self):
1873 """Test if the address is a loopback address.
1874
1875 Returns:
1876 A boolean, True if the address is a loopback address as defined in
1877 RFC 2373 2.5.3.
1878
1879 """
1880 if isinstance(self, IPv6Network):
Nick Coghlan2c589102012-05-27 01:03:25 +10001881 return int(self) == 1 and getattr(
Nick Coghlandc9b2552012-05-20 21:01:57 +10001882 self, '_prefixlen', 128) == 128
1883 elif isinstance(self, IPv6Interface):
1884 return int(self.network.network_address) == 1 and getattr(
1885 self, '_prefixlen', 128) == 128
1886 return self._ip == 1
1887
1888
1889class IPv6Address(_BaseV6, _BaseAddress):
1890
Sandro Tosib95c6342012-05-23 23:17:22 +02001891 """Represent and manipulate single IPv6 Addresses."""
Nick Coghlandc9b2552012-05-20 21:01:57 +10001892
1893 def __init__(self, address):
1894 """Instantiate a new IPv6 address object.
1895
1896 Args:
1897 address: A string or integer representing the IP
1898
1899 Additionally, an integer can be passed, so
1900 IPv6Address('2001:db8::') ==
1901 IPv6Address(42540766411282592856903984951653826560)
1902 or, more generally
1903 IPv6Address(int(IPv6Address('2001:db8::'))) ==
1904 IPv6Address('2001:db8::')
1905
1906 Raises:
1907 AddressValueError: If address isn't a valid IPv6 address.
1908
1909 """
1910 _BaseAddress.__init__(self, address)
1911 _BaseV6.__init__(self, address)
1912
1913 # Efficient constructor from integer.
1914 if isinstance(address, int):
1915 self._ip = address
1916 if address < 0 or address > self._ALL_ONES:
1917 raise AddressValueError(address)
1918 return
1919
1920 # Constructing from a packed address
1921 if isinstance(address, bytes) and len(address) == 16:
1922 tmp = struct.unpack('!QQ', address)
1923 self._ip = (tmp[0] << 64) | tmp[1]
1924 return
1925
1926 # Assume input argument to be string or any object representation
1927 # which converts into a formatted IP string.
1928 addr_str = str(address)
1929 if not addr_str:
1930 raise AddressValueError('')
1931
1932 self._ip = self._ip_int_from_string(addr_str)
1933
1934
1935class IPv6Interface(IPv6Address):
1936
1937 def __init__(self, address):
1938 if isinstance(address, (bytes, int)):
1939 IPv6Address.__init__(self, address)
1940 self.network = IPv6Network(self._ip)
1941 self._prefixlen = self._max_prefixlen
1942 return
1943
1944 addr = str(address).split('/')
1945 IPv6Address.__init__(self, addr[0])
1946 self.network = IPv6Network(address, strict=False)
1947 self.netmask = self.network.netmask
1948 self._prefixlen = self.network._prefixlen
1949 self.hostmask = self.network.hostmask
1950
Nick Coghlandc9b2552012-05-20 21:01:57 +10001951 def __str__(self):
1952 return '%s/%d' % (self._string_from_ip_int(self._ip),
1953 self.network.prefixlen)
1954
1955 def __eq__(self, other):
1956 try:
1957 return (IPv6Address.__eq__(self, other) and
1958 self.network == other.network)
1959 except AttributeError:
1960 return NotImplemented
1961
1962 def __hash__(self):
1963 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1964
1965 @property
1966 def prefixlen(self):
1967 return self._prefixlen
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001968
Nick Coghlandc9b2552012-05-20 21:01:57 +10001969 @property
1970 def ip(self):
1971 return IPv6Address(self._ip)
1972
1973 @property
1974 def with_prefixlen(self):
1975 return self
1976
1977 @property
1978 def with_netmask(self):
1979 return self.with_prefixlen
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001980
Nick Coghlandc9b2552012-05-20 21:01:57 +10001981 @property
1982 def with_hostmask(self):
1983 return '%s/%s' % (self._string_from_ip_int(self._ip),
1984 self.hostmask)
1985
1986
1987class IPv6Network(_BaseV6, _BaseNetwork):
1988
1989 """This class represents and manipulates 128-bit IPv6 networks.
1990
1991 Attributes: [examples for IPv6('2001:db8::1000/124')]
1992 .network_address: IPv6Address('2001:db8::1000')
1993 .hostmask: IPv6Address('::f')
1994 .broadcast_address: IPv6Address('2001:db8::100f')
1995 .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
1996 .prefixlen: 124
1997
1998 """
1999
Nick Coghlan51c30672012-05-27 00:25:58 +10002000 # Class to use when creating address objects
2001 # TODO (ncoghlan): Investigate using IPv6Interface instead
2002 _address_class = IPv6Address
2003
Nick Coghlandc9b2552012-05-20 21:01:57 +10002004 def __init__(self, address, strict=True):
2005 """Instantiate a new IPv6 Network object.
2006
2007 Args:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02002008 address: A string or integer representing the IPv6 network or the
2009 IP and prefix/netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +10002010 '2001:db8::/128'
2011 '2001:db8:0000:0000:0000:0000:0000:0000/128'
2012 '2001:db8::'
2013 are all functionally the same in IPv6. That is to say,
2014 failing to provide a subnetmask will create an object with
2015 a mask of /128.
2016
2017 Additionally, an integer can be passed, so
2018 IPv6Network('2001:db8::') ==
2019 IPv6Network(42540766411282592856903984951653826560)
2020 or, more generally
2021 IPv6Network(int(IPv6Network('2001:db8::'))) ==
2022 IPv6Network('2001:db8::')
2023
2024 strict: A boolean. If true, ensure that we have been passed
2025 A true network address, eg, 2001:db8::1000/124 and not an
2026 IP address on a network, eg, 2001:db8::1/124.
2027
2028 Raises:
2029 AddressValueError: If address isn't a valid IPv6 address.
2030 NetmaskValueError: If the netmask isn't valid for
2031 an IPv6 address.
2032 ValueError: If strict was True and a network address was not
2033 supplied.
2034
2035 """
2036 _BaseV6.__init__(self, address)
2037 _BaseNetwork.__init__(self, address)
2038
2039 # Efficient constructor from integer.
2040 if isinstance(address, int):
2041 if address < 0 or address > self._ALL_ONES:
2042 raise AddressValueError(address)
2043 self.network_address = IPv6Address(address)
2044 self._prefixlen = self._max_prefixlen
2045 self.netmask = IPv6Address(self._ALL_ONES)
2046 if strict:
2047 if (IPv6Address(int(self.network_address) &
2048 int(self.netmask)) != self.network_address):
2049 raise ValueError('%s has host bits set' % str(self))
2050 self.network_address = IPv6Address(int(self.network_address) &
2051 int(self.netmask))
2052 return
2053
2054 # Constructing from a packed address
2055 if isinstance(address, bytes) and len(address) == 16:
2056 tmp = struct.unpack('!QQ', address)
2057 self.network_address = IPv6Address((tmp[0] << 64) | tmp[1])
2058 self._prefixlen = self._max_prefixlen
2059 self.netmask = IPv6Address(self._ALL_ONES)
2060 if strict:
2061 if (IPv6Address(int(self.network_address) &
2062 int(self.netmask)) != self.network_address):
2063 raise ValueError('%s has host bits set' % str(self))
2064 self.network_address = IPv6Address(int(self.network_address) &
2065 int(self.netmask))
2066 return
2067
2068 # Assume input argument to be string or any object representation
2069 # which converts into a formatted IP prefix string.
2070 addr = str(address).split('/')
2071
2072 if len(addr) > 2:
2073 raise AddressValueError(address)
2074
2075 self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))
2076
2077 if len(addr) == 2:
2078 if self._is_valid_netmask(addr[1]):
2079 self._prefixlen = int(addr[1])
2080 else:
2081 raise NetmaskValueError(addr[1])
2082 else:
2083 self._prefixlen = self._max_prefixlen
2084
2085 self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen))
2086 if strict:
2087 if (IPv6Address(int(self.network_address) & int(self.netmask)) !=
2088 self.network_address):
2089 raise ValueError('%s has host bits set' % str(self))
2090 self.network_address = IPv6Address(int(self.network_address) &
2091 int(self.netmask))
2092
2093 if self._prefixlen == (self._max_prefixlen - 1):
2094 self.hosts = self.__iter__
2095
Nick Coghlandc9b2552012-05-20 21:01:57 +10002096 def _is_valid_netmask(self, prefixlen):
2097 """Verify that the netmask/prefixlen is valid.
2098
2099 Args:
2100 prefixlen: A string, the netmask in prefix length format.
2101
2102 Returns:
2103 A boolean, True if the prefix represents a valid IPv6
2104 netmask.
2105
2106 """
2107 try:
2108 prefixlen = int(prefixlen)
2109 except ValueError:
2110 return False
2111 return 0 <= prefixlen <= self._max_prefixlen