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