blob: 6daa9559c8d90e731cd737834ad7bc8d48b9b0d2 [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
Nick Coghlandc9b2552012-05-20 21:01:57 +100020class AddressValueError(ValueError):
21 """A Value Error related to the address."""
22
23
24class NetmaskValueError(ValueError):
25 """A Value Error related to the netmask."""
26
27
Nick Coghlan51c30672012-05-27 00:25:58 +100028def ip_address(address):
Nick Coghlandc9b2552012-05-20 21:01:57 +100029 """Take an IP string/int and return an object of the correct type.
30
31 Args:
32 address: A string or integer, the IP address. Either IPv4 or
33 IPv6 addresses may be supplied; integers less than 2**32 will
34 be considered to be IPv4 by default.
Nick Coghlandc9b2552012-05-20 21:01:57 +100035
36 Returns:
37 An IPv4Address or IPv6Address object.
38
39 Raises:
Sandro Tosi876ecad2012-05-23 22:26:55 +020040 ValueError: if the *address* passed isn't either a v4 or a v6
Nick Coghlan51c30672012-05-27 00:25:58 +100041 address
Nick Coghlandc9b2552012-05-20 21:01:57 +100042
43 """
Nick Coghlandc9b2552012-05-20 21:01:57 +100044 try:
45 return IPv4Address(address)
46 except (AddressValueError, NetmaskValueError):
47 pass
48
49 try:
50 return IPv6Address(address)
51 except (AddressValueError, NetmaskValueError):
52 pass
53
54 raise ValueError('%r does not appear to be an IPv4 or IPv6 address' %
55 address)
56
57
Nick Coghlan51c30672012-05-27 00:25:58 +100058def ip_network(address, strict=True):
Nick Coghlandc9b2552012-05-20 21:01:57 +100059 """Take an IP string/int and return an object of the correct type.
60
61 Args:
62 address: A string or integer, the IP network. Either IPv4 or
63 IPv6 networks may be supplied; integers less than 2**32 will
64 be considered to be IPv4 by default.
Nick Coghlandc9b2552012-05-20 21:01:57 +100065
66 Returns:
67 An IPv4Network or IPv6Network object.
68
69 Raises:
70 ValueError: if the string passed isn't either a v4 or a v6
Nick Coghlan51c30672012-05-27 00:25:58 +100071 address. Or if the network has host bits set.
Nick Coghlandc9b2552012-05-20 21:01:57 +100072
73 """
Nick Coghlandc9b2552012-05-20 21:01:57 +100074 try:
75 return IPv4Network(address, strict)
76 except (AddressValueError, NetmaskValueError):
77 pass
78
79 try:
80 return IPv6Network(address, strict)
81 except (AddressValueError, NetmaskValueError):
82 pass
83
84 raise ValueError('%r does not appear to be an IPv4 or IPv6 network' %
85 address)
86
87
Nick Coghlan51c30672012-05-27 00:25:58 +100088def ip_interface(address):
Nick Coghlandc9b2552012-05-20 21:01:57 +100089 """Take an IP string/int and return an object of the correct type.
90
91 Args:
92 address: A string or integer, the IP address. Either IPv4 or
93 IPv6 addresses may be supplied; integers less than 2**32 will
94 be considered to be IPv4 by default.
Nick Coghlandc9b2552012-05-20 21:01:57 +100095
96 Returns:
Sandro Tosi876ecad2012-05-23 22:26:55 +020097 An IPv4Interface or IPv6Interface object.
Nick Coghlandc9b2552012-05-20 21:01:57 +100098
99 Raises:
100 ValueError: if the string passed isn't either a v4 or a v6
Nick Coghlan51c30672012-05-27 00:25:58 +1000101 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000102
103 Notes:
104 The IPv?Interface classes describe an Address on a particular
105 Network, so they're basically a combination of both the Address
106 and Network classes.
Sandro Tosib95c6342012-05-23 23:17:22 +0200107
Nick Coghlandc9b2552012-05-20 21:01:57 +1000108 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000109 try:
110 return IPv4Interface(address)
111 except (AddressValueError, NetmaskValueError):
112 pass
113
114 try:
115 return IPv6Interface(address)
116 except (AddressValueError, NetmaskValueError):
117 pass
118
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000119 raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' %
Nick Coghlandc9b2552012-05-20 21:01:57 +1000120 address)
121
122
123def v4_int_to_packed(address):
Sandro Tosi876ecad2012-05-23 22:26:55 +0200124 """Represent an address as 4 packed bytes in network (big-endian) order.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000125
126 Args:
127 address: An integer representation of an IPv4 IP address.
128
129 Returns:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200130 The integer address packed as 4 bytes in network (big-endian) order.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000131
132 Raises:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200133 ValueError: If the integer is negative or too large to be an
134 IPv4 IP address.
Sandro Tosib95c6342012-05-23 23:17:22 +0200135
Nick Coghlandc9b2552012-05-20 21:01:57 +1000136 """
Sandro Tosi876ecad2012-05-23 22:26:55 +0200137 try:
138 return struct.pack('!I', address)
139 except:
140 raise ValueError("Address negative or too large for IPv4")
Nick Coghlandc9b2552012-05-20 21:01:57 +1000141
142
143def v6_int_to_packed(address):
Sandro Tosi876ecad2012-05-23 22:26:55 +0200144 """Represent an address as 16 packed bytes in network (big-endian) order.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000145
146 Args:
Sandro Tosib4386d32012-06-02 17:14:22 +0200147 address: An integer representation of an IPv6 IP address.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000148
149 Returns:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200150 The integer address packed as 16 bytes in network (big-endian) order.
Sandro Tosib95c6342012-05-23 23:17:22 +0200151
Nick Coghlandc9b2552012-05-20 21:01:57 +1000152 """
Sandro Tosi876ecad2012-05-23 22:26:55 +0200153 try:
154 return struct.pack('!QQ', address >> 64, address & (2**64 - 1))
155 except:
156 raise ValueError("Address negative or too large for IPv6")
Nick Coghlandc9b2552012-05-20 21:01:57 +1000157
158
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000159def _split_optional_netmask(address):
160 """Helper to split the netmask and raise AddressValueError if needed"""
161 addr = str(address).split('/')
162 if len(addr) > 2:
163 raise AddressValueError("Only one '/' permitted in %r" % address)
164 return addr
165
Nick Coghlandc9b2552012-05-20 21:01:57 +1000166def _find_address_range(addresses):
Sandro Tosi876ecad2012-05-23 22:26:55 +0200167 """Find a sequence of IPv#Address.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000168
169 Args:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200170 addresses: a list of IPv#Address objects.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000171
172 Returns:
173 A tuple containing the first and last IP addresses in the sequence.
174
175 """
176 first = last = addresses[0]
177 for ip in addresses[1:]:
178 if ip._ip == last._ip + 1:
179 last = ip
180 else:
181 break
182 return (first, last)
183
Sandro Tosib95c6342012-05-23 23:17:22 +0200184
Nick Coghlandc9b2552012-05-20 21:01:57 +1000185def _get_prefix_length(number1, number2, bits):
186 """Get the number of leading bits that are same for two numbers.
187
188 Args:
189 number1: an integer.
190 number2: another integer.
191 bits: the maximum number of bits to compare.
192
193 Returns:
194 The number of leading bits that are the same for two numbers.
195
196 """
197 for i in range(bits):
198 if number1 >> i == number2 >> i:
199 return bits - i
200 return 0
201
Sandro Tosib95c6342012-05-23 23:17:22 +0200202
Nick Coghlandc9b2552012-05-20 21:01:57 +1000203def _count_righthand_zero_bits(number, bits):
204 """Count the number of zero bits on the right hand side.
205
206 Args:
207 number: an integer.
208 bits: maximum number of bits to count.
209
210 Returns:
211 The number of zero bits on the right hand side of the number.
212
213 """
214 if number == 0:
215 return bits
216 for i in range(bits):
217 if (number >> i) % 2:
218 return i
219
220
221def summarize_address_range(first, last):
222 """Summarize a network range given the first and last IP addresses.
223
224 Example:
225 >>> summarize_address_range(IPv4Address('192.0.2.0'),
226 IPv4Address('192.0.2.130'))
227 [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'),
228 IPv4Network('192.0.2.130/32')]
229
230 Args:
231 first: the first IPv4Address or IPv6Address in the range.
232 last: the last IPv4Address or IPv6Address in the range.
233
234 Returns:
235 An iterator of the summarized IPv(4|6) network objects.
236
237 Raise:
238 TypeError:
239 If the first and last objects are not IP addresses.
240 If the first and last objects are not the same version.
241 ValueError:
242 If the last object is not greater than the first.
Nick Coghlan51c30672012-05-27 00:25:58 +1000243 If the version of the first address is not 4 or 6.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000244
245 """
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200246 if (not (isinstance(first, _BaseAddress) and
247 isinstance(last, _BaseAddress))):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000248 raise TypeError('first and last must be IP addresses, not networks')
249 if first.version != last.version:
250 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000251 first, last))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000252 if first > last:
253 raise ValueError('last IP address must be greater than first')
254
Nick Coghlandc9b2552012-05-20 21:01:57 +1000255 if first.version == 4:
256 ip = IPv4Network
257 elif first.version == 6:
258 ip = IPv6Network
259 else:
260 raise ValueError('unknown IP version')
261
262 ip_bits = first._max_prefixlen
263 first_int = first._ip
264 last_int = last._ip
265 while first_int <= last_int:
266 nbits = _count_righthand_zero_bits(first_int, ip_bits)
267 current = None
268 while nbits >= 0:
269 addend = 2**nbits - 1
270 current = first_int + addend
271 nbits -= 1
272 if current <= last_int:
273 break
274 prefix = _get_prefix_length(first_int, current, ip_bits)
Nick Coghlan912238e2012-07-07 13:34:50 +1000275 net = ip('%s/%d' % (first, prefix))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000276 yield net
Nick Coghlandc9b2552012-05-20 21:01:57 +1000277 if current == ip._ALL_ONES:
278 break
279 first_int = current + 1
Nick Coghlan51c30672012-05-27 00:25:58 +1000280 first = first.__class__(first_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000281
Sandro Tosib95c6342012-05-23 23:17:22 +0200282
Nick Coghlandc9b2552012-05-20 21:01:57 +1000283def _collapse_addresses_recursive(addresses):
284 """Loops through the addresses, collapsing concurrent netblocks.
285
286 Example:
287
288 ip1 = IPv4Network('192.0.2.0/26')
289 ip2 = IPv4Network('192.0.2.64/26')
290 ip3 = IPv4Network('192.0.2.128/26')
291 ip4 = IPv4Network('192.0.2.192/26')
292
293 _collapse_addresses_recursive([ip1, ip2, ip3, ip4]) ->
294 [IPv4Network('192.0.2.0/24')]
295
296 This shouldn't be called directly; it is called via
297 collapse_addresses([]).
298
299 Args:
300 addresses: A list of IPv4Network's or IPv6Network's
301
302 Returns:
303 A list of IPv4Network's or IPv6Network's depending on what we were
304 passed.
305
306 """
307 ret_array = []
308 optimized = False
309
310 for cur_addr in addresses:
311 if not ret_array:
312 ret_array.append(cur_addr)
313 continue
314 if (cur_addr.network_address >= ret_array[-1].network_address and
315 cur_addr.broadcast_address <= ret_array[-1].broadcast_address):
316 optimized = True
317 elif cur_addr == list(ret_array[-1].supernet().subnets())[1]:
318 ret_array.append(ret_array.pop().supernet())
319 optimized = True
320 else:
321 ret_array.append(cur_addr)
322
323 if optimized:
324 return _collapse_addresses_recursive(ret_array)
325
326 return ret_array
327
328
329def collapse_addresses(addresses):
330 """Collapse a list of IP objects.
331
332 Example:
333 collapse_addresses([IPv4Network('192.0.2.0/25'),
334 IPv4Network('192.0.2.128/25')]) ->
335 [IPv4Network('192.0.2.0/24')]
336
337 Args:
338 addresses: An iterator of IPv4Network or IPv6Network objects.
339
340 Returns:
341 An iterator of the collapsed IPv(4|6)Network objects.
342
343 Raises:
344 TypeError: If passed a list of mixed version objects.
345
346 """
347 i = 0
348 addrs = []
349 ips = []
350 nets = []
351
352 # split IP addresses and networks
353 for ip in addresses:
354 if isinstance(ip, _BaseAddress):
355 if ips and ips[-1]._version != ip._version:
356 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000357 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000358 ips.append(ip)
359 elif ip._prefixlen == ip._max_prefixlen:
360 if ips and ips[-1]._version != ip._version:
361 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000362 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000363 try:
364 ips.append(ip.ip)
365 except AttributeError:
366 ips.append(ip.network_address)
367 else:
368 if nets and nets[-1]._version != ip._version:
369 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000370 ip, nets[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000371 nets.append(ip)
372
373 # sort and dedup
374 ips = sorted(set(ips))
375 nets = sorted(set(nets))
376
377 while i < len(ips):
378 (first, last) = _find_address_range(ips[i:])
379 i = ips.index(last) + 1
380 addrs.extend(summarize_address_range(first, last))
381
382 return iter(_collapse_addresses_recursive(sorted(
383 addrs + nets, key=_BaseNetwork._get_networks_key)))
384
385
386def get_mixed_type_key(obj):
387 """Return a key suitable for sorting between networks and addresses.
388
389 Address and Network objects are not sortable by default; they're
390 fundamentally different so the expression
391
392 IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
393
394 doesn't make any sense. There are some times however, where you may wish
395 to have ipaddress sort these for you anyway. If you need to do this, you
396 can use this function as the key= argument to sorted().
397
398 Args:
399 obj: either a Network or Address object.
400 Returns:
401 appropriate key.
402
403 """
404 if isinstance(obj, _BaseNetwork):
405 return obj._get_networks_key()
406 elif isinstance(obj, _BaseAddress):
407 return obj._get_address_key()
408 return NotImplemented
409
410
Hynek Schlawackc4b78a32012-06-01 11:48:32 +0200411class _IPAddressBase:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000412
413 """The mother class."""
414
415 @property
416 def exploded(self):
417 """Return the longhand version of the IP address as a string."""
418 return self._explode_shorthand_ip_string()
419
420 @property
421 def compressed(self):
422 """Return the shorthand version of the IP address as a string."""
423 return str(self)
424
Nick Coghland9722652012-06-17 16:33:00 +1000425 @property
426 def version(self):
427 msg = '%200s has no version specified' % (type(self),)
428 raise NotImplementedError(msg)
429
Nick Coghlandc9b2552012-05-20 21:01:57 +1000430 def _ip_int_from_prefix(self, prefixlen=None):
431 """Turn the prefix length netmask into a int for comparison.
432
433 Args:
434 prefixlen: An integer, the prefix length.
435
436 Returns:
437 An integer.
438
439 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +0200440 if prefixlen is None:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000441 prefixlen = self._prefixlen
442 return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen)
443
444 def _prefix_from_ip_int(self, ip_int, mask=32):
445 """Return prefix length from the decimal netmask.
446
447 Args:
448 ip_int: An integer, the IP address.
449 mask: The netmask. Defaults to 32.
450
451 Returns:
452 An integer, the prefix length.
453
454 """
455 while mask:
456 if ip_int & 1 == 1:
457 break
458 ip_int >>= 1
459 mask -= 1
460
461 return mask
462
463 def _ip_string_from_prefix(self, prefixlen=None):
464 """Turn a prefix length into a dotted decimal string.
465
466 Args:
467 prefixlen: An integer, the netmask prefix length.
468
469 Returns:
470 A string, the dotted decimal netmask string.
471
472 """
473 if not prefixlen:
474 prefixlen = self._prefixlen
475 return self._string_from_ip_int(self._ip_int_from_prefix(prefixlen))
476
477
478class _BaseAddress(_IPAddressBase):
479
480 """A generic IP object.
481
482 This IP class contains the version independent methods which are
483 used by single IP addresses.
484
485 """
486
487 def __init__(self, address):
488 if (not isinstance(address, bytes)
489 and '/' in str(address)):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000490 raise AddressValueError("Unexpected '/' in %r" % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000491
492 def __index__(self):
493 return self._ip
494
495 def __int__(self):
496 return self._ip
497
Nick Coghlandc9b2552012-05-20 21:01:57 +1000498 def __eq__(self, other):
499 try:
500 return (self._ip == other._ip
501 and self._version == other._version)
502 except AttributeError:
503 return NotImplemented
504
505 def __ne__(self, other):
506 eq = self.__eq__(other)
507 if eq is NotImplemented:
508 return NotImplemented
509 return not eq
510
511 def __le__(self, other):
512 gt = self.__gt__(other)
513 if gt is NotImplemented:
514 return NotImplemented
515 return not gt
516
517 def __ge__(self, other):
518 lt = self.__lt__(other)
519 if lt is NotImplemented:
520 return NotImplemented
521 return not lt
522
523 def __lt__(self, other):
524 if self._version != other._version:
525 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000526 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000527 if not isinstance(other, _BaseAddress):
528 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000529 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000530 if self._ip != other._ip:
531 return self._ip < other._ip
532 return False
533
534 def __gt__(self, other):
535 if self._version != other._version:
536 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000537 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000538 if not isinstance(other, _BaseAddress):
539 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000540 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000541 if self._ip != other._ip:
542 return self._ip > other._ip
543 return False
544
545 # Shorthand for Integer addition and subtraction. This is not
546 # meant to ever support addition/subtraction of addresses.
547 def __add__(self, other):
548 if not isinstance(other, int):
549 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000550 return self.__class__(int(self) + other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000551
552 def __sub__(self, other):
553 if not isinstance(other, int):
554 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000555 return self.__class__(int(self) - other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000556
557 def __repr__(self):
558 return '%s(%r)' % (self.__class__.__name__, str(self))
559
560 def __str__(self):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200561 return str(self._string_from_ip_int(self._ip))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000562
563 def __hash__(self):
564 return hash(hex(int(self._ip)))
565
566 def _get_address_key(self):
567 return (self._version, self)
568
Nick Coghlandc9b2552012-05-20 21:01:57 +1000569
570class _BaseNetwork(_IPAddressBase):
571
Nick Coghlan51c30672012-05-27 00:25:58 +1000572 """A generic IP network object.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000573
574 This IP class contains the version independent methods which are
575 used by networks.
576
577 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000578 def __init__(self, address):
579 self._cache = {}
580
581 def __index__(self):
582 return int(self.network_address) ^ self.prefixlen
583
584 def __int__(self):
585 return int(self.network_address)
586
587 def __repr__(self):
588 return '%s(%r)' % (self.__class__.__name__, str(self))
589
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200590 def __str__(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000591 return '%s/%d' % (self.network_address, self.prefixlen)
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200592
Nick Coghlandc9b2552012-05-20 21:01:57 +1000593 def hosts(self):
594 """Generate Iterator over usable hosts in a network.
595
Sandro Tosib95c6342012-05-23 23:17:22 +0200596 This is like __iter__ except it doesn't return the network
597 or broadcast addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000598
599 """
600 cur = int(self.network_address) + 1
601 bcast = int(self.broadcast_address) - 1
602 while cur <= bcast:
603 cur += 1
Nick Coghlan51c30672012-05-27 00:25:58 +1000604 yield self._address_class(cur - 1)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000605
606 def __iter__(self):
607 cur = int(self.network_address)
608 bcast = int(self.broadcast_address)
609 while cur <= bcast:
610 cur += 1
Nick Coghlan51c30672012-05-27 00:25:58 +1000611 yield self._address_class(cur - 1)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000612
613 def __getitem__(self, n):
614 network = int(self.network_address)
615 broadcast = int(self.broadcast_address)
616 if n >= 0:
617 if network + n > broadcast:
618 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000619 return self._address_class(network + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000620 else:
621 n += 1
622 if broadcast + n < network:
623 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000624 return self._address_class(broadcast + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000625
626 def __lt__(self, other):
627 if self._version != other._version:
628 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000629 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000630 if not isinstance(other, _BaseNetwork):
631 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000632 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000633 if self.network_address != other.network_address:
634 return self.network_address < other.network_address
635 if self.netmask != other.netmask:
636 return self.netmask < other.netmask
637 return False
638
639 def __gt__(self, other):
640 if self._version != other._version:
641 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000642 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000643 if not isinstance(other, _BaseNetwork):
644 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000645 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000646 if self.network_address != other.network_address:
647 return self.network_address > other.network_address
648 if self.netmask != other.netmask:
649 return self.netmask > other.netmask
650 return False
651
652 def __le__(self, other):
653 gt = self.__gt__(other)
654 if gt is NotImplemented:
655 return NotImplemented
656 return not gt
657
658 def __ge__(self, other):
659 lt = self.__lt__(other)
660 if lt is NotImplemented:
661 return NotImplemented
662 return not lt
663
664 def __eq__(self, other):
665 if not isinstance(other, _BaseNetwork):
666 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000667 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000668 return (self._version == other._version and
669 self.network_address == other.network_address and
670 int(self.netmask) == int(other.netmask))
671
672 def __ne__(self, other):
673 eq = self.__eq__(other)
674 if eq is NotImplemented:
675 return NotImplemented
676 return not eq
677
Nick Coghlandc9b2552012-05-20 21:01:57 +1000678 def __hash__(self):
679 return hash(int(self.network_address) ^ int(self.netmask))
680
681 def __contains__(self, other):
682 # always false if one is v4 and the other is v6.
683 if self._version != other._version:
684 return False
685 # dealing with another network.
686 if isinstance(other, _BaseNetwork):
687 return False
688 # dealing with another address
689 else:
690 # address
691 return (int(self.network_address) <= int(other._ip) <=
692 int(self.broadcast_address))
693
694 def overlaps(self, other):
695 """Tell if self is partly contained in other."""
696 return self.network_address in other or (
697 self.broadcast_address in other or (
698 other.network_address in self or (
699 other.broadcast_address in self)))
700
701 @property
702 def broadcast_address(self):
703 x = self._cache.get('broadcast_address')
704 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000705 x = self._address_class(int(self.network_address) |
706 int(self.hostmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000707 self._cache['broadcast_address'] = x
708 return x
709
710 @property
711 def hostmask(self):
712 x = self._cache.get('hostmask')
713 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000714 x = self._address_class(int(self.netmask) ^ self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000715 self._cache['hostmask'] = x
716 return x
717
718 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000719 def with_prefixlen(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000720 return '%s/%d' % (self.network_address, self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000721
722 @property
723 def with_netmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000724 return '%s/%s' % (self.network_address, self.netmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000725
726 @property
727 def with_hostmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000728 return '%s/%s' % (self.network_address, self.hostmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000729
730 @property
731 def num_addresses(self):
732 """Number of hosts in the current subnet."""
733 return int(self.broadcast_address) - int(self.network_address) + 1
734
735 @property
Nick Coghlan51c30672012-05-27 00:25:58 +1000736 def _address_class(self):
Nick Coghland9722652012-06-17 16:33:00 +1000737 # Returning bare address objects (rather than interfaces) allows for
738 # more consistent behaviour across the network address, broadcast
739 # address and individual host addresses.
740 msg = '%200s has no associated address class' % (type(self),)
741 raise NotImplementedError(msg)
Nick Coghlan51c30672012-05-27 00:25:58 +1000742
743 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000744 def prefixlen(self):
745 return self._prefixlen
746
747 def address_exclude(self, other):
748 """Remove an address from a larger block.
749
750 For example:
751
752 addr1 = ip_network('192.0.2.0/28')
753 addr2 = ip_network('192.0.2.1/32')
754 addr1.address_exclude(addr2) =
755 [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
756 IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
757
758 or IPv6:
759
760 addr1 = ip_network('2001:db8::1/32')
761 addr2 = ip_network('2001:db8::1/128')
762 addr1.address_exclude(addr2) =
763 [ip_network('2001:db8::1/128'),
764 ip_network('2001:db8::2/127'),
765 ip_network('2001:db8::4/126'),
766 ip_network('2001:db8::8/125'),
767 ...
768 ip_network('2001:db8:8000::/33')]
769
770 Args:
771 other: An IPv4Network or IPv6Network object of the same type.
772
773 Returns:
774 An iterator of the the IPv(4|6)Network objects which is self
775 minus other.
776
777 Raises:
778 TypeError: If self and other are of difffering address
779 versions, or if other is not a network object.
780 ValueError: If other is not completely contained by self.
781
782 """
783 if not self._version == other._version:
784 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000785 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000786
787 if not isinstance(other, _BaseNetwork):
Nick Coghlan912238e2012-07-07 13:34:50 +1000788 raise TypeError("%s is not a network object" % other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000789
790 if not (other.network_address >= self.network_address and
791 other.broadcast_address <= self.broadcast_address):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200792 raise ValueError('%s not contained in %s' % (other, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000793 if other == self:
794 raise StopIteration
795
Nick Coghlandc9b2552012-05-20 21:01:57 +1000796 # Make sure we're comparing the network of other.
Nick Coghlan912238e2012-07-07 13:34:50 +1000797 other = other.__class__('%s/%s' % (other.network_address,
798 other.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000799
800 s1, s2 = self.subnets()
801 while s1 != other and s2 != other:
802 if (other.network_address >= s1.network_address and
803 other.broadcast_address <= s1.broadcast_address):
804 yield s2
805 s1, s2 = s1.subnets()
806 elif (other.network_address >= s2.network_address and
807 other.broadcast_address <= s2.broadcast_address):
808 yield s1
809 s1, s2 = s2.subnets()
810 else:
811 # If we got here, there's a bug somewhere.
812 raise AssertionError('Error performing exclusion: '
813 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000814 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000815 if s1 == other:
816 yield s2
817 elif s2 == other:
818 yield s1
819 else:
820 # If we got here, there's a bug somewhere.
821 raise AssertionError('Error performing exclusion: '
822 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000823 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000824
825 def compare_networks(self, other):
826 """Compare two IP objects.
827
828 This is only concerned about the comparison of the integer
829 representation of the network addresses. This means that the
830 host bits aren't considered at all in this method. If you want
831 to compare host bits, you can easily enough do a
832 'HostA._ip < HostB._ip'
833
834 Args:
835 other: An IP object.
836
837 Returns:
838 If the IP versions of self and other are the same, returns:
839
840 -1 if self < other:
841 eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
842 IPv6Network('2001:db8::1000/124') <
843 IPv6Network('2001:db8::2000/124')
844 0 if self == other
845 eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
846 IPv6Network('2001:db8::1000/124') ==
847 IPv6Network('2001:db8::1000/124')
848 1 if self > other
849 eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
850 IPv6Network('2001:db8::2000/124') >
851 IPv6Network('2001:db8::1000/124')
852
853 Raises:
854 TypeError if the IP versions are different.
855
856 """
857 # does this need to raise a ValueError?
858 if self._version != other._version:
859 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000860 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000861 # self._version == other._version below here:
862 if self.network_address < other.network_address:
863 return -1
864 if self.network_address > other.network_address:
865 return 1
866 # self.network_address == other.network_address below here:
867 if self.netmask < other.netmask:
868 return -1
869 if self.netmask > other.netmask:
870 return 1
871 return 0
872
873 def _get_networks_key(self):
874 """Network-only key function.
875
876 Returns an object that identifies this address' network and
877 netmask. This function is a suitable "key" argument for sorted()
878 and list.sort().
879
880 """
881 return (self._version, self.network_address, self.netmask)
882
883 def subnets(self, prefixlen_diff=1, new_prefix=None):
884 """The subnets which join to make the current subnet.
885
886 In the case that self contains only one IP
887 (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
888 for IPv6), yield an iterator with just ourself.
889
890 Args:
891 prefixlen_diff: An integer, the amount the prefix length
892 should be increased by. This should not be set if
893 new_prefix is also set.
894 new_prefix: The desired new prefix length. This must be a
895 larger number (smaller prefix) than the existing prefix.
896 This should not be set if prefixlen_diff is also set.
897
898 Returns:
899 An iterator of IPv(4|6) objects.
900
901 Raises:
902 ValueError: The prefixlen_diff is too small or too large.
903 OR
904 prefixlen_diff and new_prefix are both set or new_prefix
905 is a smaller number than the current prefix (smaller
906 number means a larger network)
907
908 """
909 if self._prefixlen == self._max_prefixlen:
910 yield self
911 return
912
913 if new_prefix is not None:
914 if new_prefix < self._prefixlen:
915 raise ValueError('new prefix must be longer')
916 if prefixlen_diff != 1:
917 raise ValueError('cannot set prefixlen_diff and new_prefix')
918 prefixlen_diff = new_prefix - self._prefixlen
919
920 if prefixlen_diff < 0:
921 raise ValueError('prefix length diff must be > 0')
922 new_prefixlen = self._prefixlen + prefixlen_diff
923
924 if not self._is_valid_netmask(str(new_prefixlen)):
925 raise ValueError(
926 'prefix length diff %d is invalid for netblock %s' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000927 new_prefixlen, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000928
Nick Coghlan51c30672012-05-27 00:25:58 +1000929 first = self.__class__('%s/%s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000930 (self.network_address,
931 self._prefixlen + prefixlen_diff))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000932
933 yield first
934 current = first
935 while True:
936 broadcast = current.broadcast_address
937 if broadcast == self.broadcast_address:
938 return
Nick Coghlan51c30672012-05-27 00:25:58 +1000939 new_addr = self._address_class(int(broadcast) + 1)
Nick Coghlan912238e2012-07-07 13:34:50 +1000940 current = self.__class__('%s/%s' % (new_addr,
941 new_prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000942
943 yield current
944
Nick Coghlandc9b2552012-05-20 21:01:57 +1000945 def supernet(self, prefixlen_diff=1, new_prefix=None):
946 """The supernet containing the current network.
947
948 Args:
949 prefixlen_diff: An integer, the amount the prefix length of
950 the network should be decreased by. For example, given a
951 /24 network and a prefixlen_diff of 3, a supernet with a
952 /21 netmask is returned.
953
954 Returns:
955 An IPv4 network object.
956
957 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200958 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
959 a negative prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000960 OR
961 If prefixlen_diff and new_prefix are both set or new_prefix is a
962 larger number than the current prefix (larger number means a
963 smaller network)
964
965 """
966 if self._prefixlen == 0:
967 return self
968
969 if new_prefix is not None:
970 if new_prefix > self._prefixlen:
971 raise ValueError('new prefix must be shorter')
972 if prefixlen_diff != 1:
973 raise ValueError('cannot set prefixlen_diff and new_prefix')
974 prefixlen_diff = self._prefixlen - new_prefix
975
Nick Coghlandc9b2552012-05-20 21:01:57 +1000976 if self.prefixlen - prefixlen_diff < 0:
977 raise ValueError(
978 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
979 (self.prefixlen, prefixlen_diff))
980 # TODO (pmoody): optimize this.
Nick Coghlan912238e2012-07-07 13:34:50 +1000981 t = self.__class__('%s/%d' % (self.network_address,
Nick Coghlan51c30672012-05-27 00:25:58 +1000982 self.prefixlen - prefixlen_diff),
983 strict=False)
Nick Coghlan912238e2012-07-07 13:34:50 +1000984 return t.__class__('%s/%d' % (t.network_address, t.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000985
986
Hynek Schlawackc4b78a32012-06-01 11:48:32 +0200987class _BaseV4:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000988
989 """Base IPv4 object.
990
991 The following methods are used by IPv4 objects in both single IP
992 addresses and networks.
993
994 """
995
996 # Equivalent to 255.255.255.255 or 32 bits of 1's.
997 _ALL_ONES = (2**IPV4LENGTH) - 1
998 _DECIMAL_DIGITS = frozenset('0123456789')
999
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001000 # the valid octets for host and netmasks. only useful for IPv4.
1001 _valid_mask_octets = set((255, 254, 252, 248, 240, 224, 192, 128, 0))
1002
Nick Coghlandc9b2552012-05-20 21:01:57 +10001003 def __init__(self, address):
1004 self._version = 4
1005 self._max_prefixlen = IPV4LENGTH
1006
1007 def _explode_shorthand_ip_string(self):
1008 return str(self)
1009
1010 def _ip_int_from_string(self, ip_str):
1011 """Turn the given IP string into an integer for comparison.
1012
1013 Args:
1014 ip_str: A string, the IP ip_str.
1015
1016 Returns:
1017 The IP ip_str as an integer.
1018
1019 Raises:
1020 AddressValueError: if ip_str isn't a valid IPv4 Address.
1021
1022 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001023 if not ip_str:
1024 raise AddressValueError('Address cannot be empty')
1025
Nick Coghlandc9b2552012-05-20 21:01:57 +10001026 octets = ip_str.split('.')
1027 if len(octets) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001028 raise AddressValueError("Expected 4 octets in %r" % ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001029
1030 packed_ip = 0
1031 for oc in octets:
1032 try:
1033 packed_ip = (packed_ip << 8) | self._parse_octet(oc)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001034 except ValueError as exc:
1035 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001036 return packed_ip
1037
1038 def _parse_octet(self, octet_str):
1039 """Convert a decimal octet into an integer.
1040
1041 Args:
1042 octet_str: A string, the number to parse.
1043
1044 Returns:
1045 The octet as an integer.
1046
1047 Raises:
1048 ValueError: if the octet isn't strictly a decimal from [0..255].
1049
1050 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001051 if not octet_str:
1052 raise ValueError("Empty octet not permitted")
Nick Coghlandc9b2552012-05-20 21:01:57 +10001053 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1054 if not self._DECIMAL_DIGITS.issuperset(octet_str):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001055 raise ValueError("Only decimal digits permitted in %r" % octet_str)
1056 # Convert to integer (we know digits are legal)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001057 octet_int = int(octet_str, 10)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001058 # Any octets that look like they *might* be written in octal,
1059 # and which don't look exactly the same in both octal and
1060 # decimal are rejected as ambiguous
1061 if octet_int > 7 and octet_str[0] == '0':
1062 raise ValueError("Ambiguous leading zero in %r not permitted" %
1063 octet_str)
1064 if octet_int > 255:
1065 raise ValueError("Octet %d > 255 not permitted" % octet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001066 return octet_int
1067
1068 def _string_from_ip_int(self, ip_int):
1069 """Turns a 32-bit integer into dotted decimal notation.
1070
1071 Args:
1072 ip_int: An integer, the IP address.
1073
1074 Returns:
1075 The IP address as a string in dotted decimal notation.
1076
1077 """
1078 octets = []
1079 for _ in range(4):
1080 octets.insert(0, str(ip_int & 0xFF))
1081 ip_int >>= 8
1082 return '.'.join(octets)
1083
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001084 def _is_valid_netmask(self, netmask):
1085 """Verify that the netmask is valid.
1086
1087 Args:
1088 netmask: A string, either a prefix or dotted decimal
1089 netmask.
1090
1091 Returns:
1092 A boolean, True if the prefix represents a valid IPv4
1093 netmask.
1094
1095 """
1096 mask = netmask.split('.')
1097 if len(mask) == 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001098 for x in mask:
1099 try:
1100 if int(x) in self._valid_mask_octets:
1101 continue
1102 except ValueError:
1103 pass
1104 # Found something that isn't an integer or isn't valid
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001105 return False
1106 if [y for idx, y in enumerate(mask) if idx > 0 and
1107 y > mask[idx - 1]]:
1108 return False
1109 return True
1110 try:
1111 netmask = int(netmask)
1112 except ValueError:
1113 return False
1114 return 0 <= netmask <= self._max_prefixlen
1115
1116 def _is_hostmask(self, ip_str):
1117 """Test if the IP string is a hostmask (rather than a netmask).
1118
1119 Args:
1120 ip_str: A string, the potential hostmask.
1121
1122 Returns:
1123 A boolean, True if the IP string is a hostmask.
1124
1125 """
1126 bits = ip_str.split('.')
1127 try:
1128 parts = [int(x) for x in bits if int(x) in self._valid_mask_octets]
1129 except ValueError:
1130 return False
1131 if len(parts) != len(bits):
1132 return False
1133 if parts[0] < parts[-1]:
1134 return True
1135 return False
1136
Nick Coghlandc9b2552012-05-20 21:01:57 +10001137 @property
1138 def max_prefixlen(self):
1139 return self._max_prefixlen
1140
1141 @property
1142 def version(self):
1143 return self._version
1144
1145 @property
1146 def is_reserved(self):
1147 """Test if the address is otherwise IETF reserved.
1148
1149 Returns:
1150 A boolean, True if the address is within the
1151 reserved IPv4 Network range.
1152
1153 """
1154 reserved_network = IPv4Network('240.0.0.0/4')
1155 if isinstance(self, _BaseAddress):
1156 return self in reserved_network
1157 return (self.network_address in reserved_network and
1158 self.broadcast_address in reserved_network)
1159
1160 @property
1161 def is_private(self):
1162 """Test if this address is allocated for private networks.
1163
1164 Returns:
1165 A boolean, True if the address is reserved per RFC 1918.
1166
1167 """
1168 private_10 = IPv4Network('10.0.0.0/8')
1169 private_172 = IPv4Network('172.16.0.0/12')
1170 private_192 = IPv4Network('192.168.0.0/16')
1171 if isinstance(self, _BaseAddress):
1172 return (self in private_10 or self in private_172 or
1173 self in private_192)
1174 else:
1175 return ((self.network_address in private_10 and
1176 self.broadcast_address in private_10) or
1177 (self.network_address in private_172 and
1178 self.broadcast_address in private_172) or
1179 (self.network_address in private_192 and
1180 self.broadcast_address in private_192))
1181
1182 @property
1183 def is_multicast(self):
1184 """Test if the address is reserved for multicast use.
1185
1186 Returns:
1187 A boolean, True if the address is multicast.
1188 See RFC 3171 for details.
1189
1190 """
1191 multicast_network = IPv4Network('224.0.0.0/4')
1192 if isinstance(self, _BaseAddress):
1193 return self in IPv4Network('224.0.0.0/4')
1194 return (self.network_address in multicast_network and
1195 self.broadcast_address in multicast_network)
1196
1197 @property
1198 def is_unspecified(self):
1199 """Test if the address is unspecified.
1200
1201 Returns:
1202 A boolean, True if this is the unspecified address as defined in
1203 RFC 5735 3.
1204
1205 """
1206 unspecified_address = IPv4Address('0.0.0.0')
1207 if isinstance(self, _BaseAddress):
Hynek Schlawackbcd30442012-06-04 14:19:39 +02001208 return self == unspecified_address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001209 return (self.network_address == self.broadcast_address ==
1210 unspecified_address)
1211
1212 @property
1213 def is_loopback(self):
1214 """Test if the address is a loopback address.
1215
1216 Returns:
1217 A boolean, True if the address is a loopback per RFC 3330.
1218
1219 """
1220 loopback_address = IPv4Network('127.0.0.0/8')
1221 if isinstance(self, _BaseAddress):
1222 return self in loopback_address
1223
1224 return (self.network_address in loopback_address and
1225 self.broadcast_address in loopback_address)
1226
1227 @property
1228 def is_link_local(self):
1229 """Test if the address is reserved for link-local.
1230
1231 Returns:
1232 A boolean, True if the address is link-local per RFC 3927.
1233
1234 """
1235 linklocal_network = IPv4Network('169.254.0.0/16')
1236 if isinstance(self, _BaseAddress):
1237 return self in linklocal_network
1238 return (self.network_address in linklocal_network and
1239 self.broadcast_address in linklocal_network)
1240
1241
1242class IPv4Address(_BaseV4, _BaseAddress):
1243
1244 """Represent and manipulate single IPv4 Addresses."""
1245
1246 def __init__(self, address):
1247
1248 """
1249 Args:
1250 address: A string or integer representing the IP
1251
1252 Additionally, an integer can be passed, so
1253 IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1254 or, more generally
1255 IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1256 IPv4Address('192.0.2.1')
1257
1258 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001259 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001260
1261 """
1262 _BaseAddress.__init__(self, address)
1263 _BaseV4.__init__(self, address)
1264
1265 # Efficient constructor from integer.
1266 if isinstance(address, int):
1267 self._ip = address
1268 if address < 0 or address > self._ALL_ONES:
1269 raise AddressValueError(address)
1270 return
1271
1272 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001273 if isinstance(address, bytes):
1274 if len(address) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001275 msg = "Packed address %r must be exactly 4 bytes"
1276 raise AddressValueError(msg % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001277 self._ip = struct.unpack('!I', address)[0]
1278 return
1279
1280 # Assume input argument to be string or any object representation
1281 # which converts into a formatted IP string.
1282 addr_str = str(address)
1283 self._ip = self._ip_int_from_string(addr_str)
1284
1285 @property
1286 def packed(self):
1287 """The binary representation of this address."""
1288 return v4_int_to_packed(self._ip)
1289
1290
1291class IPv4Interface(IPv4Address):
1292
Nick Coghlandc9b2552012-05-20 21:01:57 +10001293 def __init__(self, address):
1294 if isinstance(address, (bytes, int)):
1295 IPv4Address.__init__(self, address)
1296 self.network = IPv4Network(self._ip)
1297 self._prefixlen = self._max_prefixlen
1298 return
1299
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001300 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001301 IPv4Address.__init__(self, addr[0])
1302
1303 self.network = IPv4Network(address, strict=False)
1304 self._prefixlen = self.network._prefixlen
1305
1306 self.netmask = self.network.netmask
1307 self.hostmask = self.network.hostmask
1308
Nick Coghlandc9b2552012-05-20 21:01:57 +10001309 def __str__(self):
1310 return '%s/%d' % (self._string_from_ip_int(self._ip),
1311 self.network.prefixlen)
1312
1313 def __eq__(self, other):
1314 try:
1315 return (IPv4Address.__eq__(self, other) and
1316 self.network == other.network)
1317 except AttributeError:
1318 return NotImplemented
1319
1320 def __hash__(self):
1321 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1322
Nick Coghlandc9b2552012-05-20 21:01:57 +10001323 @property
1324 def prefixlen(self):
1325 return self._prefixlen
1326
1327 @property
1328 def ip(self):
1329 return IPv4Address(self._ip)
1330
1331 @property
1332 def with_prefixlen(self):
1333 return self
1334
1335 @property
1336 def with_netmask(self):
1337 return '%s/%s' % (self._string_from_ip_int(self._ip),
1338 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001339
Nick Coghlandc9b2552012-05-20 21:01:57 +10001340 @property
1341 def with_hostmask(self):
1342 return '%s/%s' % (self._string_from_ip_int(self._ip),
1343 self.hostmask)
1344
1345
1346class IPv4Network(_BaseV4, _BaseNetwork):
1347
1348 """This class represents and manipulates 32-bit IPv4 network + addresses..
1349
1350 Attributes: [examples for IPv4Network('192.0.2.0/27')]
1351 .network_address: IPv4Address('192.0.2.0')
1352 .hostmask: IPv4Address('0.0.0.31')
1353 .broadcast_address: IPv4Address('192.0.2.32')
1354 .netmask: IPv4Address('255.255.255.224')
1355 .prefixlen: 27
1356
1357 """
Nick Coghlan51c30672012-05-27 00:25:58 +10001358 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001359 _address_class = IPv4Address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001360
Nick Coghlandc9b2552012-05-20 21:01:57 +10001361 def __init__(self, address, strict=True):
1362
1363 """Instantiate a new IPv4 network object.
1364
1365 Args:
1366 address: A string or integer representing the IP [& network].
1367 '192.0.2.0/24'
1368 '192.0.2.0/255.255.255.0'
1369 '192.0.0.2/0.0.0.255'
1370 are all functionally the same in IPv4. Similarly,
1371 '192.0.2.1'
1372 '192.0.2.1/255.255.255.255'
1373 '192.0.2.1/32'
1374 are also functionaly equivalent. That is to say, failing to
1375 provide a subnetmask will create an object with a mask of /32.
1376
1377 If the mask (portion after the / in the argument) is given in
1378 dotted quad form, it is treated as a netmask if it starts with a
1379 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1380 starts with a zero field (e.g. 0.255.255.255 == /8), with the
1381 single exception of an all-zero mask which is treated as a
1382 netmask == /0. If no mask is given, a default of /32 is used.
1383
1384 Additionally, an integer can be passed, so
1385 IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1386 or, more generally
1387 IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1388 IPv4Interface('192.0.2.1')
1389
1390 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001391 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001392 NetmaskValueError: If the netmask isn't valid for
1393 an IPv4 address.
Sandro Tosib4386d32012-06-02 17:14:22 +02001394 ValueError: If strict is True and a network address is not
Nick Coghlandc9b2552012-05-20 21:01:57 +10001395 supplied.
1396
1397 """
1398
1399 _BaseV4.__init__(self, address)
1400 _BaseNetwork.__init__(self, address)
1401
1402 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001403 if isinstance(address, bytes):
1404 if len(address) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001405 msg = "Packed address %r must be exactly 4 bytes"
1406 raise AddressValueError(msg % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001407 self.network_address = IPv4Address(
1408 struct.unpack('!I', address)[0])
1409 self._prefixlen = self._max_prefixlen
1410 self.netmask = IPv4Address(self._ALL_ONES)
1411 #fixme: address/network test here
1412 return
1413
1414 # Efficient constructor from integer.
1415 if isinstance(address, int):
1416 self._prefixlen = self._max_prefixlen
1417 self.netmask = IPv4Address(self._ALL_ONES)
1418 if address < 0 or address > self._ALL_ONES:
1419 raise AddressValueError(address)
1420 self.network_address = IPv4Address(address)
1421 #fixme: address/network test here.
1422 return
1423
1424 # Assume input argument to be string or any object representation
1425 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001426 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001427 self.network_address = IPv4Address(self._ip_int_from_string(addr[0]))
1428
Nick Coghlandc9b2552012-05-20 21:01:57 +10001429 if len(addr) == 2:
1430 mask = addr[1].split('.')
1431
1432 if len(mask) == 4:
1433 # We have dotted decimal netmask.
1434 if self._is_valid_netmask(addr[1]):
1435 self.netmask = IPv4Address(self._ip_int_from_string(
1436 addr[1]))
1437 elif self._is_hostmask(addr[1]):
1438 self.netmask = IPv4Address(
1439 self._ip_int_from_string(addr[1]) ^ self._ALL_ONES)
1440 else:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001441 raise NetmaskValueError('%r is not a valid netmask'
Nick Coghlandc9b2552012-05-20 21:01:57 +10001442 % addr[1])
1443
1444 self._prefixlen = self._prefix_from_ip_int(int(self.netmask))
1445 else:
1446 # We have a netmask in prefix length form.
1447 if not self._is_valid_netmask(addr[1]):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001448 raise NetmaskValueError('%r is not a valid netmask'
1449 % addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001450 self._prefixlen = int(addr[1])
1451 self.netmask = IPv4Address(self._ip_int_from_prefix(
1452 self._prefixlen))
1453 else:
1454 self._prefixlen = self._max_prefixlen
1455 self.netmask = IPv4Address(self._ip_int_from_prefix(
1456 self._prefixlen))
1457
1458 if strict:
1459 if (IPv4Address(int(self.network_address) & int(self.netmask)) !=
1460 self.network_address):
1461 raise ValueError('%s has host bits set' % self)
1462 self.network_address = IPv4Address(int(self.network_address) &
1463 int(self.netmask))
1464
1465 if self._prefixlen == (self._max_prefixlen - 1):
1466 self.hosts = self.__iter__
1467
Nick Coghlandc9b2552012-05-20 21:01:57 +10001468
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001469class _BaseV6:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001470
1471 """Base IPv6 object.
1472
1473 The following methods are used by IPv6 objects in both single IP
1474 addresses and networks.
1475
1476 """
1477
1478 _ALL_ONES = (2**IPV6LENGTH) - 1
1479 _HEXTET_COUNT = 8
1480 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
1481
1482 def __init__(self, address):
1483 self._version = 6
1484 self._max_prefixlen = IPV6LENGTH
1485
1486 def _ip_int_from_string(self, ip_str):
1487 """Turn an IPv6 ip_str into an integer.
1488
1489 Args:
1490 ip_str: A string, the IPv6 ip_str.
1491
1492 Returns:
1493 An int, the IPv6 address
1494
1495 Raises:
1496 AddressValueError: if ip_str isn't a valid IPv6 Address.
1497
1498 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001499 if not ip_str:
1500 raise AddressValueError('Address cannot be empty')
1501
Nick Coghlandc9b2552012-05-20 21:01:57 +10001502 parts = ip_str.split(':')
1503
1504 # An IPv6 address needs at least 2 colons (3 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001505 _min_parts = 3
1506 if len(parts) < _min_parts:
1507 msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
1508 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001509
1510 # If the address has an IPv4-style suffix, convert it to hexadecimal.
1511 if '.' in parts[-1]:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001512 try:
1513 ipv4_int = IPv4Address(parts.pop())._ip
1514 except AddressValueError as exc:
1515 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001516 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1517 parts.append('%x' % (ipv4_int & 0xFFFF))
1518
1519 # An IPv6 address can't have more than 8 colons (9 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001520 # The extra colon comes from using the "::" notation for a single
1521 # leading or trailing zero part.
1522 _max_parts = self._HEXTET_COUNT + 1
1523 if len(parts) > _max_parts:
1524 msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
1525 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001526
1527 # Disregarding the endpoints, find '::' with nothing in between.
1528 # This indicates that a run of zeroes has been skipped.
1529 try:
1530 skip_index, = (
1531 [i for i in range(1, len(parts) - 1) if not parts[i]] or
1532 [None])
1533 except ValueError:
1534 # Can't have more than one '::'
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001535 msg = "At most one '::' permitted in %r" % ip_str
1536 raise AddressValueError(msg) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001537
1538 # parts_hi is the number of parts to copy from above/before the '::'
1539 # parts_lo is the number of parts to copy from below/after the '::'
1540 if skip_index is not None:
1541 # If we found a '::', then check if it also covers the endpoints.
1542 parts_hi = skip_index
1543 parts_lo = len(parts) - skip_index - 1
1544 if not parts[0]:
1545 parts_hi -= 1
1546 if parts_hi:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001547 msg = "Leading ':' only permitted as part of '::' in %r"
1548 raise AddressValueError(msg % ip_str) # ^: requires ^::
Nick Coghlandc9b2552012-05-20 21:01:57 +10001549 if not parts[-1]:
1550 parts_lo -= 1
1551 if parts_lo:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001552 msg = "Trailing ':' only permitted as part of '::' in %r"
1553 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001554 parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo)
1555 if parts_skipped < 1:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001556 msg = "Expected at most %d other parts with '::' in %r"
1557 raise AddressValueError(msg % (self._HEXTET_COUNT-1, ip_str))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001558 else:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001559 # Otherwise, allocate the entire address to parts_hi. The
1560 # endpoints could still be empty, but _parse_hextet() will check
1561 # for that.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001562 if len(parts) != self._HEXTET_COUNT:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001563 msg = "Exactly %d parts expected without '::' in %r"
1564 raise AddressValueError(msg % (self._HEXTET_COUNT, ip_str))
1565 if not parts[0]:
1566 msg = "Leading ':' only permitted as part of '::' in %r"
1567 raise AddressValueError(msg % ip_str) # ^: requires ^::
1568 if not parts[-1]:
1569 msg = "Trailing ':' only permitted as part of '::' in %r"
1570 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001571 parts_hi = len(parts)
1572 parts_lo = 0
1573 parts_skipped = 0
1574
1575 try:
1576 # Now, parse the hextets into a 128-bit integer.
1577 ip_int = 0
1578 for i in range(parts_hi):
1579 ip_int <<= 16
1580 ip_int |= self._parse_hextet(parts[i])
1581 ip_int <<= 16 * parts_skipped
1582 for i in range(-parts_lo, 0):
1583 ip_int <<= 16
1584 ip_int |= self._parse_hextet(parts[i])
1585 return ip_int
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001586 except ValueError as exc:
1587 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001588
1589 def _parse_hextet(self, hextet_str):
1590 """Convert an IPv6 hextet string into an integer.
1591
1592 Args:
1593 hextet_str: A string, the number to parse.
1594
1595 Returns:
1596 The hextet as an integer.
1597
1598 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001599 ValueError: if the input isn't strictly a hex number from
1600 [0..FFFF].
Nick Coghlandc9b2552012-05-20 21:01:57 +10001601
1602 """
1603 # Whitelist the characters, since int() allows a lot of bizarre stuff.
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001604 # Higher level wrappers convert these to more informative errors
Nick Coghlandc9b2552012-05-20 21:01:57 +10001605 if not self._HEX_DIGITS.issuperset(hextet_str):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001606 raise ValueError("Only hex digits permitted in %r" % hextet_str)
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001607 if len(hextet_str) > 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001608 msg = "At most 4 characters permitted in %r"
1609 raise ValueError(msg % hextet_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001610 hextet_int = int(hextet_str, 16)
1611 if hextet_int > 0xFFFF:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001612 # This is unreachable due to the string length check above
1613 raise ValueError("Part %d > 0xFFFF not permitted" % hextet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001614 return hextet_int
1615
1616 def _compress_hextets(self, hextets):
1617 """Compresses a list of hextets.
1618
1619 Compresses a list of strings, replacing the longest continuous
1620 sequence of "0" in the list with "" and adding empty strings at
1621 the beginning or at the end of the string such that subsequently
1622 calling ":".join(hextets) will produce the compressed version of
1623 the IPv6 address.
1624
1625 Args:
1626 hextets: A list of strings, the hextets to compress.
1627
1628 Returns:
1629 A list of strings.
1630
1631 """
1632 best_doublecolon_start = -1
1633 best_doublecolon_len = 0
1634 doublecolon_start = -1
1635 doublecolon_len = 0
1636 for index in range(len(hextets)):
1637 if hextets[index] == '0':
1638 doublecolon_len += 1
1639 if doublecolon_start == -1:
1640 # Start of a sequence of zeros.
1641 doublecolon_start = index
1642 if doublecolon_len > best_doublecolon_len:
1643 # This is the longest sequence of zeros so far.
1644 best_doublecolon_len = doublecolon_len
1645 best_doublecolon_start = doublecolon_start
1646 else:
1647 doublecolon_len = 0
1648 doublecolon_start = -1
1649
1650 if best_doublecolon_len > 1:
1651 best_doublecolon_end = (best_doublecolon_start +
1652 best_doublecolon_len)
1653 # For zeros at the end of the address.
1654 if best_doublecolon_end == len(hextets):
1655 hextets += ['']
1656 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1657 # For zeros at the beginning of the address.
1658 if best_doublecolon_start == 0:
1659 hextets = [''] + hextets
1660
1661 return hextets
1662
1663 def _string_from_ip_int(self, ip_int=None):
1664 """Turns a 128-bit integer into hexadecimal notation.
1665
1666 Args:
1667 ip_int: An integer, the IP address.
1668
1669 Returns:
1670 A string, the hexadecimal representation of the address.
1671
1672 Raises:
1673 ValueError: The address is bigger than 128 bits of all ones.
1674
1675 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001676 if ip_int is None:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001677 ip_int = int(self._ip)
1678
1679 if ip_int > self._ALL_ONES:
1680 raise ValueError('IPv6 address is too large')
1681
1682 hex_str = '%032x' % ip_int
1683 hextets = []
1684 for x in range(0, 32, 4):
1685 hextets.append('%x' % int(hex_str[x:x+4], 16))
1686
1687 hextets = self._compress_hextets(hextets)
1688 return ':'.join(hextets)
1689
1690 def _explode_shorthand_ip_string(self):
1691 """Expand a shortened IPv6 address.
1692
1693 Args:
1694 ip_str: A string, the IPv6 address.
1695
1696 Returns:
1697 A string, the expanded IPv6 address.
1698
1699 """
1700 if isinstance(self, IPv6Network):
1701 ip_str = str(self.network_address)
1702 elif isinstance(self, IPv6Interface):
1703 ip_str = str(self.ip)
1704 else:
1705 ip_str = str(self)
1706
1707 ip_int = self._ip_int_from_string(ip_str)
1708 parts = []
1709 for i in range(self._HEXTET_COUNT):
1710 parts.append('%04x' % (ip_int & 0xFFFF))
1711 ip_int >>= 16
1712 parts.reverse()
1713 if isinstance(self, (_BaseNetwork, IPv6Interface)):
1714 return '%s/%d' % (':'.join(parts), self.prefixlen)
1715 return ':'.join(parts)
1716
1717 @property
1718 def max_prefixlen(self):
1719 return self._max_prefixlen
1720
1721 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001722 def version(self):
1723 return self._version
1724
1725 @property
1726 def is_multicast(self):
1727 """Test if the address is reserved for multicast use.
1728
1729 Returns:
1730 A boolean, True if the address is a multicast address.
1731 See RFC 2373 2.7 for details.
1732
1733 """
1734 multicast_network = IPv6Network('ff00::/8')
1735 if isinstance(self, _BaseAddress):
1736 return self in multicast_network
1737 return (self.network_address in multicast_network and
1738 self.broadcast_address in multicast_network)
1739
1740 @property
1741 def is_reserved(self):
1742 """Test if the address is otherwise IETF reserved.
1743
1744 Returns:
1745 A boolean, True if the address is within one of the
1746 reserved IPv6 Network ranges.
1747
1748 """
1749 reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'),
1750 IPv6Network('200::/7'), IPv6Network('400::/6'),
1751 IPv6Network('800::/5'), IPv6Network('1000::/4'),
1752 IPv6Network('4000::/3'), IPv6Network('6000::/3'),
1753 IPv6Network('8000::/3'), IPv6Network('A000::/3'),
1754 IPv6Network('C000::/3'), IPv6Network('E000::/4'),
1755 IPv6Network('F000::/5'), IPv6Network('F800::/6'),
1756 IPv6Network('FE00::/9')]
1757
1758 if isinstance(self, _BaseAddress):
1759 return len([x for x in reserved_networks if self in x]) > 0
1760 return len([x for x in reserved_networks if self.network_address in x
1761 and self.broadcast_address in x]) > 0
1762
1763 @property
1764 def is_link_local(self):
1765 """Test if the address is reserved for link-local.
1766
1767 Returns:
1768 A boolean, True if the address is reserved per RFC 4291.
1769
1770 """
1771 linklocal_network = IPv6Network('fe80::/10')
1772 if isinstance(self, _BaseAddress):
1773 return self in linklocal_network
1774 return (self.network_address in linklocal_network and
1775 self.broadcast_address in linklocal_network)
1776
1777 @property
1778 def is_site_local(self):
1779 """Test if the address is reserved for site-local.
1780
1781 Note that the site-local address space has been deprecated by RFC 3879.
1782 Use is_private to test if this address is in the space of unique local
1783 addresses as defined by RFC 4193.
1784
1785 Returns:
1786 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1787
1788 """
1789 sitelocal_network = IPv6Network('fec0::/10')
1790 if isinstance(self, _BaseAddress):
1791 return self in sitelocal_network
1792 return (self.network_address in sitelocal_network and
1793 self.broadcast_address in sitelocal_network)
1794
1795 @property
1796 def is_private(self):
1797 """Test if this address is allocated for private networks.
1798
1799 Returns:
1800 A boolean, True if the address is reserved per RFC 4193.
1801
1802 """
1803 private_network = IPv6Network('fc00::/7')
1804 if isinstance(self, _BaseAddress):
1805 return self in private_network
1806 return (self.network_address in private_network and
1807 self.broadcast_address in private_network)
1808
Nick Coghlandc9b2552012-05-20 21:01:57 +10001809 @property
1810 def ipv4_mapped(self):
1811 """Return the IPv4 mapped address.
1812
1813 Returns:
1814 If the IPv6 address is a v4 mapped address, return the
1815 IPv4 mapped address. Return None otherwise.
1816
1817 """
1818 if (self._ip >> 32) != 0xFFFF:
1819 return None
1820 return IPv4Address(self._ip & 0xFFFFFFFF)
1821
1822 @property
1823 def teredo(self):
1824 """Tuple of embedded teredo IPs.
1825
1826 Returns:
1827 Tuple of the (server, client) IPs or None if the address
1828 doesn't appear to be a teredo address (doesn't start with
1829 2001::/32)
1830
1831 """
1832 if (self._ip >> 96) != 0x20010000:
1833 return None
1834 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
1835 IPv4Address(~self._ip & 0xFFFFFFFF))
1836
1837 @property
1838 def sixtofour(self):
1839 """Return the IPv4 6to4 embedded address.
1840
1841 Returns:
1842 The IPv4 6to4-embedded address if present or None if the
1843 address doesn't appear to contain a 6to4 embedded address.
1844
1845 """
1846 if (self._ip >> 112) != 0x2002:
1847 return None
1848 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
1849
1850 @property
1851 def is_unspecified(self):
1852 """Test if the address is unspecified.
1853
1854 Returns:
1855 A boolean, True if this is the unspecified address as defined in
1856 RFC 2373 2.5.2.
1857
1858 """
1859 if isinstance(self, (IPv6Network, IPv6Interface)):
1860 return int(self.network_address) == 0 and getattr(
1861 self, '_prefixlen', 128) == 128
1862 return self._ip == 0
1863
1864 @property
1865 def is_loopback(self):
1866 """Test if the address is a loopback address.
1867
1868 Returns:
1869 A boolean, True if the address is a loopback address as defined in
1870 RFC 2373 2.5.3.
1871
1872 """
1873 if isinstance(self, IPv6Network):
Nick Coghlan2c589102012-05-27 01:03:25 +10001874 return int(self) == 1 and getattr(
Nick Coghlandc9b2552012-05-20 21:01:57 +10001875 self, '_prefixlen', 128) == 128
1876 elif isinstance(self, IPv6Interface):
1877 return int(self.network.network_address) == 1 and getattr(
1878 self, '_prefixlen', 128) == 128
1879 return self._ip == 1
1880
1881
1882class IPv6Address(_BaseV6, _BaseAddress):
1883
Sandro Tosib95c6342012-05-23 23:17:22 +02001884 """Represent and manipulate single IPv6 Addresses."""
Nick Coghlandc9b2552012-05-20 21:01:57 +10001885
1886 def __init__(self, address):
1887 """Instantiate a new IPv6 address object.
1888
1889 Args:
1890 address: A string or integer representing the IP
1891
1892 Additionally, an integer can be passed, so
1893 IPv6Address('2001:db8::') ==
1894 IPv6Address(42540766411282592856903984951653826560)
1895 or, more generally
1896 IPv6Address(int(IPv6Address('2001:db8::'))) ==
1897 IPv6Address('2001:db8::')
1898
1899 Raises:
1900 AddressValueError: If address isn't a valid IPv6 address.
1901
1902 """
1903 _BaseAddress.__init__(self, address)
1904 _BaseV6.__init__(self, address)
1905
1906 # Efficient constructor from integer.
1907 if isinstance(address, int):
1908 self._ip = address
1909 if address < 0 or address > self._ALL_ONES:
1910 raise AddressValueError(address)
1911 return
1912
1913 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001914 if isinstance(address, bytes):
1915 if len(address) != 16:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001916 msg = "Packed address %r must be exactly 16 bytes"
1917 raise AddressValueError(msg % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001918 tmp = struct.unpack('!QQ', address)
1919 self._ip = (tmp[0] << 64) | tmp[1]
1920 return
1921
1922 # Assume input argument to be string or any object representation
1923 # which converts into a formatted IP string.
1924 addr_str = str(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001925 self._ip = self._ip_int_from_string(addr_str)
1926
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001927 @property
1928 def packed(self):
1929 """The binary representation of this address."""
1930 return v6_int_to_packed(self._ip)
1931
Nick Coghlandc9b2552012-05-20 21:01:57 +10001932
1933class IPv6Interface(IPv6Address):
1934
1935 def __init__(self, address):
1936 if isinstance(address, (bytes, int)):
1937 IPv6Address.__init__(self, address)
1938 self.network = IPv6Network(self._ip)
1939 self._prefixlen = self._max_prefixlen
1940 return
1941
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001942 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001943 IPv6Address.__init__(self, addr[0])
1944 self.network = IPv6Network(address, strict=False)
1945 self.netmask = self.network.netmask
1946 self._prefixlen = self.network._prefixlen
1947 self.hostmask = self.network.hostmask
1948
Nick Coghlandc9b2552012-05-20 21:01:57 +10001949 def __str__(self):
1950 return '%s/%d' % (self._string_from_ip_int(self._ip),
1951 self.network.prefixlen)
1952
1953 def __eq__(self, other):
1954 try:
1955 return (IPv6Address.__eq__(self, other) and
1956 self.network == other.network)
1957 except AttributeError:
1958 return NotImplemented
1959
1960 def __hash__(self):
1961 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1962
1963 @property
1964 def prefixlen(self):
1965 return self._prefixlen
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001966
Nick Coghlandc9b2552012-05-20 21:01:57 +10001967 @property
1968 def ip(self):
1969 return IPv6Address(self._ip)
1970
1971 @property
1972 def with_prefixlen(self):
1973 return self
1974
1975 @property
1976 def with_netmask(self):
1977 return self.with_prefixlen
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001978
Nick Coghlandc9b2552012-05-20 21:01:57 +10001979 @property
1980 def with_hostmask(self):
1981 return '%s/%s' % (self._string_from_ip_int(self._ip),
1982 self.hostmask)
1983
1984
1985class IPv6Network(_BaseV6, _BaseNetwork):
1986
1987 """This class represents and manipulates 128-bit IPv6 networks.
1988
1989 Attributes: [examples for IPv6('2001:db8::1000/124')]
1990 .network_address: IPv6Address('2001:db8::1000')
1991 .hostmask: IPv6Address('::f')
1992 .broadcast_address: IPv6Address('2001:db8::100f')
1993 .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
1994 .prefixlen: 124
1995
1996 """
1997
Nick Coghlan51c30672012-05-27 00:25:58 +10001998 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001999 _address_class = IPv6Address
2000
Nick Coghlandc9b2552012-05-20 21:01:57 +10002001 def __init__(self, address, strict=True):
2002 """Instantiate a new IPv6 Network object.
2003
2004 Args:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02002005 address: A string or integer representing the IPv6 network or the
2006 IP and prefix/netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +10002007 '2001:db8::/128'
2008 '2001:db8:0000:0000:0000:0000:0000:0000/128'
2009 '2001:db8::'
2010 are all functionally the same in IPv6. That is to say,
2011 failing to provide a subnetmask will create an object with
2012 a mask of /128.
2013
2014 Additionally, an integer can be passed, so
2015 IPv6Network('2001:db8::') ==
2016 IPv6Network(42540766411282592856903984951653826560)
2017 or, more generally
2018 IPv6Network(int(IPv6Network('2001:db8::'))) ==
2019 IPv6Network('2001:db8::')
2020
2021 strict: A boolean. If true, ensure that we have been passed
2022 A true network address, eg, 2001:db8::1000/124 and not an
2023 IP address on a network, eg, 2001:db8::1/124.
2024
2025 Raises:
2026 AddressValueError: If address isn't a valid IPv6 address.
2027 NetmaskValueError: If the netmask isn't valid for
2028 an IPv6 address.
2029 ValueError: If strict was True and a network address was not
2030 supplied.
2031
2032 """
2033 _BaseV6.__init__(self, address)
2034 _BaseNetwork.__init__(self, address)
2035
2036 # Efficient constructor from integer.
2037 if isinstance(address, int):
2038 if address < 0 or address > self._ALL_ONES:
2039 raise AddressValueError(address)
2040 self.network_address = IPv6Address(address)
2041 self._prefixlen = self._max_prefixlen
2042 self.netmask = IPv6Address(self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002043 return
2044
2045 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10002046 if isinstance(address, bytes):
2047 if len(address) != 16:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002048 msg = "Packed address %r must be exactly 16 bytes"
2049 raise AddressValueError(msg % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002050 tmp = struct.unpack('!QQ', address)
2051 self.network_address = IPv6Address((tmp[0] << 64) | tmp[1])
2052 self._prefixlen = self._max_prefixlen
2053 self.netmask = IPv6Address(self._ALL_ONES)
Hynek Schlawacked36b2e2012-06-08 15:21:21 +02002054 return
Nick Coghlandc9b2552012-05-20 21:01:57 +10002055
2056 # Assume input argument to be string or any object representation
2057 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002058 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002059
2060 self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))
2061
2062 if len(addr) == 2:
2063 if self._is_valid_netmask(addr[1]):
2064 self._prefixlen = int(addr[1])
2065 else:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002066 raise NetmaskValueError('%r is not a valid netmask'
2067 % addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10002068 else:
2069 self._prefixlen = self._max_prefixlen
2070
2071 self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen))
2072 if strict:
2073 if (IPv6Address(int(self.network_address) & int(self.netmask)) !=
2074 self.network_address):
Nick Coghlan912238e2012-07-07 13:34:50 +10002075 raise ValueError('%s has host bits set' % self)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002076 self.network_address = IPv6Address(int(self.network_address) &
2077 int(self.netmask))
2078
2079 if self._prefixlen == (self._max_prefixlen - 1):
2080 self.hosts = self.__iter__
2081
Nick Coghlandc9b2552012-05-20 21:01:57 +10002082 def _is_valid_netmask(self, prefixlen):
2083 """Verify that the netmask/prefixlen is valid.
2084
2085 Args:
2086 prefixlen: A string, the netmask in prefix length format.
2087
2088 Returns:
2089 A boolean, True if the prefix represents a valid IPv6
2090 netmask.
2091
2092 """
2093 try:
2094 prefixlen = int(prefixlen)
2095 except ValueError:
2096 return False
2097 return 0 <= prefixlen <= self._max_prefixlen