blob: 612236e2f50bb18fd243cf0b06e75579cbf3f205 [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
Nick Coghlan3008ec02012-07-08 00:45:33 +100015import functools
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 Coghlan297b1432012-07-08 17:11:04 +1000166
Nick Coghlandc9b2552012-05-20 21:01:57 +1000167def _find_address_range(addresses):
Sandro Tosi876ecad2012-05-23 22:26:55 +0200168 """Find a sequence of IPv#Address.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000169
170 Args:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200171 addresses: a list of IPv#Address objects.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000172
173 Returns:
174 A tuple containing the first and last IP addresses in the sequence.
175
176 """
177 first = last = addresses[0]
178 for ip in addresses[1:]:
179 if ip._ip == last._ip + 1:
180 last = ip
181 else:
182 break
183 return (first, last)
184
Sandro Tosib95c6342012-05-23 23:17:22 +0200185
Nick Coghlandc9b2552012-05-20 21:01:57 +1000186def _count_righthand_zero_bits(number, bits):
187 """Count the number of zero bits on the right hand side.
188
189 Args:
190 number: an integer.
191 bits: maximum number of bits to count.
192
193 Returns:
194 The number of zero bits on the right hand side of the number.
195
196 """
197 if number == 0:
198 return bits
199 for i in range(bits):
Nick Coghlan7319f692012-07-07 21:43:30 +1000200 if (number >> i) & 1:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000201 return i
Nick Coghlan7319f692012-07-07 21:43:30 +1000202 # All bits of interest were zero, even if there are more in the number
203 return bits
Nick Coghlandc9b2552012-05-20 21:01:57 +1000204
205
206def summarize_address_range(first, last):
207 """Summarize a network range given the first and last IP addresses.
208
209 Example:
210 >>> summarize_address_range(IPv4Address('192.0.2.0'),
211 IPv4Address('192.0.2.130'))
212 [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'),
213 IPv4Network('192.0.2.130/32')]
214
215 Args:
216 first: the first IPv4Address or IPv6Address in the range.
217 last: the last IPv4Address or IPv6Address in the range.
218
219 Returns:
220 An iterator of the summarized IPv(4|6) network objects.
221
222 Raise:
223 TypeError:
224 If the first and last objects are not IP addresses.
225 If the first and last objects are not the same version.
226 ValueError:
227 If the last object is not greater than the first.
Nick Coghlan51c30672012-05-27 00:25:58 +1000228 If the version of the first address is not 4 or 6.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000229
230 """
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200231 if (not (isinstance(first, _BaseAddress) and
232 isinstance(last, _BaseAddress))):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000233 raise TypeError('first and last must be IP addresses, not networks')
234 if first.version != last.version:
235 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000236 first, last))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000237 if first > last:
238 raise ValueError('last IP address must be greater than first')
239
Nick Coghlandc9b2552012-05-20 21:01:57 +1000240 if first.version == 4:
241 ip = IPv4Network
242 elif first.version == 6:
243 ip = IPv6Network
244 else:
245 raise ValueError('unknown IP version')
246
247 ip_bits = first._max_prefixlen
248 first_int = first._ip
249 last_int = last._ip
250 while first_int <= last_int:
Nick Coghlan7319f692012-07-07 21:43:30 +1000251 nbits = min(_count_righthand_zero_bits(first_int, ip_bits),
252 (last_int - first_int + 1).bit_length() - 1)
253 net = ip('%s/%d' % (first, ip_bits - nbits))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000254 yield net
Nick Coghlan7319f692012-07-07 21:43:30 +1000255 first_int += 1 << nbits
256 if first_int - 1 == ip._ALL_ONES:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000257 break
Nick Coghlan51c30672012-05-27 00:25:58 +1000258 first = first.__class__(first_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000259
Sandro Tosib95c6342012-05-23 23:17:22 +0200260
Nick Coghlandc9b2552012-05-20 21:01:57 +1000261def _collapse_addresses_recursive(addresses):
262 """Loops through the addresses, collapsing concurrent netblocks.
263
264 Example:
265
266 ip1 = IPv4Network('192.0.2.0/26')
267 ip2 = IPv4Network('192.0.2.64/26')
268 ip3 = IPv4Network('192.0.2.128/26')
269 ip4 = IPv4Network('192.0.2.192/26')
270
271 _collapse_addresses_recursive([ip1, ip2, ip3, ip4]) ->
272 [IPv4Network('192.0.2.0/24')]
273
274 This shouldn't be called directly; it is called via
275 collapse_addresses([]).
276
277 Args:
278 addresses: A list of IPv4Network's or IPv6Network's
279
280 Returns:
281 A list of IPv4Network's or IPv6Network's depending on what we were
282 passed.
283
284 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000285 while True:
286 last_addr = None
287 ret_array = []
288 optimized = False
Nick Coghlandc9b2552012-05-20 21:01:57 +1000289
Nick Coghlan7319f692012-07-07 21:43:30 +1000290 for cur_addr in addresses:
291 if not ret_array:
292 last_addr = cur_addr
293 ret_array.append(cur_addr)
294 elif (cur_addr.network_address >= last_addr.network_address and
295 cur_addr.broadcast_address <= last_addr.broadcast_address):
296 optimized = True
297 elif cur_addr == list(last_addr.supernet().subnets())[1]:
298 ret_array[-1] = last_addr = last_addr.supernet()
299 optimized = True
300 else:
301 last_addr = cur_addr
302 ret_array.append(cur_addr)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000303
Nick Coghlan7319f692012-07-07 21:43:30 +1000304 addresses = ret_array
305 if not optimized:
306 return addresses
Nick Coghlandc9b2552012-05-20 21:01:57 +1000307
308
309def collapse_addresses(addresses):
310 """Collapse a list of IP objects.
311
312 Example:
313 collapse_addresses([IPv4Network('192.0.2.0/25'),
314 IPv4Network('192.0.2.128/25')]) ->
315 [IPv4Network('192.0.2.0/24')]
316
317 Args:
318 addresses: An iterator of IPv4Network or IPv6Network objects.
319
320 Returns:
321 An iterator of the collapsed IPv(4|6)Network objects.
322
323 Raises:
324 TypeError: If passed a list of mixed version objects.
325
326 """
327 i = 0
328 addrs = []
329 ips = []
330 nets = []
331
332 # split IP addresses and networks
333 for ip in addresses:
334 if isinstance(ip, _BaseAddress):
335 if ips and ips[-1]._version != ip._version:
336 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000337 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000338 ips.append(ip)
339 elif ip._prefixlen == ip._max_prefixlen:
340 if ips and ips[-1]._version != ip._version:
341 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000342 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000343 try:
344 ips.append(ip.ip)
345 except AttributeError:
346 ips.append(ip.network_address)
347 else:
348 if nets and nets[-1]._version != ip._version:
349 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000350 ip, nets[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000351 nets.append(ip)
352
353 # sort and dedup
354 ips = sorted(set(ips))
355 nets = sorted(set(nets))
356
357 while i < len(ips):
358 (first, last) = _find_address_range(ips[i:])
359 i = ips.index(last) + 1
360 addrs.extend(summarize_address_range(first, last))
361
362 return iter(_collapse_addresses_recursive(sorted(
363 addrs + nets, key=_BaseNetwork._get_networks_key)))
364
365
366def get_mixed_type_key(obj):
367 """Return a key suitable for sorting between networks and addresses.
368
369 Address and Network objects are not sortable by default; they're
370 fundamentally different so the expression
371
372 IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
373
374 doesn't make any sense. There are some times however, where you may wish
375 to have ipaddress sort these for you anyway. If you need to do this, you
376 can use this function as the key= argument to sorted().
377
378 Args:
379 obj: either a Network or Address object.
380 Returns:
381 appropriate key.
382
383 """
384 if isinstance(obj, _BaseNetwork):
385 return obj._get_networks_key()
386 elif isinstance(obj, _BaseAddress):
387 return obj._get_address_key()
388 return NotImplemented
389
390
Nick Coghlan3008ec02012-07-08 00:45:33 +1000391class _TotalOrderingMixin:
392 # Helper that derives the other comparison operations from
393 # __lt__ and __eq__
Nick Coghlan297b1432012-07-08 17:11:04 +1000394 # We avoid functools.total_ordering because it doesn't handle
395 # NotImplemented correctly yet (http://bugs.python.org/issue10042)
Nick Coghlan3008ec02012-07-08 00:45:33 +1000396 def __eq__(self, other):
397 raise NotImplementedError
398 def __ne__(self, other):
399 equal = self.__eq__(other)
400 if equal is NotImplemented:
401 return NotImplemented
402 return not equal
403 def __lt__(self, other):
404 raise NotImplementedError
405 def __le__(self, other):
406 less = self.__lt__(other)
407 if less is NotImplemented or not less:
408 return self.__eq__(other)
409 return less
410 def __gt__(self, other):
411 less = self.__lt__(other)
412 if less is NotImplemented:
413 return NotImplemented
414 equal = self.__eq__(other)
415 if equal is NotImplemented:
416 return NotImplemented
417 return not (less or equal)
418 def __ge__(self, other):
419 less = self.__lt__(other)
420 if less is NotImplemented:
421 return NotImplemented
422 return not less
423
424class _IPAddressBase(_TotalOrderingMixin):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000425
426 """The mother class."""
427
428 @property
429 def exploded(self):
430 """Return the longhand version of the IP address as a string."""
431 return self._explode_shorthand_ip_string()
432
433 @property
434 def compressed(self):
435 """Return the shorthand version of the IP address as a string."""
436 return str(self)
437
Nick Coghland9722652012-06-17 16:33:00 +1000438 @property
439 def version(self):
440 msg = '%200s has no version specified' % (type(self),)
441 raise NotImplementedError(msg)
442
Nick Coghlan297b1432012-07-08 17:11:04 +1000443 def _check_int_address(self, address):
444 if address < 0:
445 msg = "%d (< 0) is not permitted as an IPv%d address"
446 raise AddressValueError(msg % (address, self._version))
447 if address > self._ALL_ONES:
448 msg = "%d (>= 2**%d) is not permitted as an IPv%d address"
449 raise AddressValueError(msg % (address, self._max_prefixlen,
450 self._version))
451
452 def _check_packed_address(self, address, expected_len):
453 address_len = len(address)
454 if address_len != expected_len:
455 msg = "%r (len %d != %d) is not permitted as an IPv%d address"
456 raise AddressValueError(msg % (address, address_len,
457 expected_len, self._version))
458
Nick Coghlandc9b2552012-05-20 21:01:57 +1000459 def _ip_int_from_prefix(self, prefixlen=None):
460 """Turn the prefix length netmask into a int for comparison.
461
462 Args:
463 prefixlen: An integer, the prefix length.
464
465 Returns:
466 An integer.
467
468 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +0200469 if prefixlen is None:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000470 prefixlen = self._prefixlen
471 return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen)
472
473 def _prefix_from_ip_int(self, ip_int, mask=32):
474 """Return prefix length from the decimal netmask.
475
476 Args:
477 ip_int: An integer, the IP address.
478 mask: The netmask. Defaults to 32.
479
480 Returns:
481 An integer, the prefix length.
482
483 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000484 return mask - _count_righthand_zero_bits(ip_int, mask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000485
486 def _ip_string_from_prefix(self, prefixlen=None):
487 """Turn a prefix length into a dotted decimal string.
488
489 Args:
490 prefixlen: An integer, the netmask prefix length.
491
492 Returns:
493 A string, the dotted decimal netmask string.
494
495 """
496 if not prefixlen:
497 prefixlen = self._prefixlen
498 return self._string_from_ip_int(self._ip_int_from_prefix(prefixlen))
499
Nick Coghlandc9b2552012-05-20 21:01:57 +1000500class _BaseAddress(_IPAddressBase):
501
502 """A generic IP object.
503
504 This IP class contains the version independent methods which are
505 used by single IP addresses.
506
507 """
508
509 def __init__(self, address):
510 if (not isinstance(address, bytes)
511 and '/' in str(address)):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000512 raise AddressValueError("Unexpected '/' in %r" % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000513
Nick Coghlandc9b2552012-05-20 21:01:57 +1000514 def __int__(self):
515 return self._ip
516
Nick Coghlandc9b2552012-05-20 21:01:57 +1000517 def __eq__(self, other):
518 try:
519 return (self._ip == other._ip
520 and self._version == other._version)
521 except AttributeError:
522 return NotImplemented
523
Nick Coghlandc9b2552012-05-20 21:01:57 +1000524 def __lt__(self, other):
525 if self._version != other._version:
526 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000527 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000528 if not isinstance(other, _BaseAddress):
529 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000530 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000531 if self._ip != other._ip:
532 return self._ip < other._ip
533 return False
534
Nick Coghlandc9b2552012-05-20 21:01:57 +1000535 # Shorthand for Integer addition and subtraction. This is not
536 # meant to ever support addition/subtraction of addresses.
537 def __add__(self, other):
538 if not isinstance(other, int):
539 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000540 return self.__class__(int(self) + other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000541
542 def __sub__(self, other):
543 if not isinstance(other, int):
544 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000545 return self.__class__(int(self) - other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000546
547 def __repr__(self):
548 return '%s(%r)' % (self.__class__.__name__, str(self))
549
550 def __str__(self):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200551 return str(self._string_from_ip_int(self._ip))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000552
553 def __hash__(self):
554 return hash(hex(int(self._ip)))
555
556 def _get_address_key(self):
557 return (self._version, self)
558
Nick Coghlandc9b2552012-05-20 21:01:57 +1000559
560class _BaseNetwork(_IPAddressBase):
561
Nick Coghlan51c30672012-05-27 00:25:58 +1000562 """A generic IP network object.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000563
564 This IP class contains the version independent methods which are
565 used by networks.
566
567 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000568 def __init__(self, address):
569 self._cache = {}
570
Nick Coghlandc9b2552012-05-20 21:01:57 +1000571 def __int__(self):
572 return int(self.network_address)
573
574 def __repr__(self):
575 return '%s(%r)' % (self.__class__.__name__, str(self))
576
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200577 def __str__(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000578 return '%s/%d' % (self.network_address, self.prefixlen)
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200579
Nick Coghlandc9b2552012-05-20 21:01:57 +1000580 def hosts(self):
581 """Generate Iterator over usable hosts in a network.
582
Sandro Tosib95c6342012-05-23 23:17:22 +0200583 This is like __iter__ except it doesn't return the network
584 or broadcast addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000585
586 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000587 network = int(self.network_address)
588 broadcast = int(self.broadcast_address)
589 for x in range(network + 1, broadcast):
590 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000591
592 def __iter__(self):
Nick Coghlan7319f692012-07-07 21:43:30 +1000593 network = int(self.network_address)
594 broadcast = int(self.broadcast_address)
595 for x in range(network, broadcast + 1):
596 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000597
598 def __getitem__(self, n):
599 network = int(self.network_address)
600 broadcast = int(self.broadcast_address)
601 if n >= 0:
602 if network + n > broadcast:
603 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000604 return self._address_class(network + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000605 else:
606 n += 1
607 if broadcast + n < network:
608 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000609 return self._address_class(broadcast + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000610
611 def __lt__(self, other):
612 if self._version != other._version:
613 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000614 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000615 if not isinstance(other, _BaseNetwork):
616 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000617 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000618 if self.network_address != other.network_address:
619 return self.network_address < other.network_address
620 if self.netmask != other.netmask:
621 return self.netmask < other.netmask
622 return False
623
Nick Coghlandc9b2552012-05-20 21:01:57 +1000624 def __eq__(self, other):
Nick Coghlan9a9c28c2012-07-07 23:05:59 +1000625 try:
626 return (self._version == other._version and
627 self.network_address == other.network_address and
628 int(self.netmask) == int(other.netmask))
629 except AttributeError:
630 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000631
Nick Coghlandc9b2552012-05-20 21:01:57 +1000632 def __hash__(self):
633 return hash(int(self.network_address) ^ int(self.netmask))
634
635 def __contains__(self, other):
636 # always false if one is v4 and the other is v6.
637 if self._version != other._version:
638 return False
639 # dealing with another network.
640 if isinstance(other, _BaseNetwork):
641 return False
642 # dealing with another address
643 else:
644 # address
645 return (int(self.network_address) <= int(other._ip) <=
646 int(self.broadcast_address))
647
648 def overlaps(self, other):
649 """Tell if self is partly contained in other."""
650 return self.network_address in other or (
651 self.broadcast_address in other or (
652 other.network_address in self or (
653 other.broadcast_address in self)))
654
655 @property
656 def broadcast_address(self):
657 x = self._cache.get('broadcast_address')
658 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000659 x = self._address_class(int(self.network_address) |
660 int(self.hostmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000661 self._cache['broadcast_address'] = x
662 return x
663
664 @property
665 def hostmask(self):
666 x = self._cache.get('hostmask')
667 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000668 x = self._address_class(int(self.netmask) ^ self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000669 self._cache['hostmask'] = x
670 return x
671
672 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000673 def with_prefixlen(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000674 return '%s/%d' % (self.network_address, self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000675
676 @property
677 def with_netmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000678 return '%s/%s' % (self.network_address, self.netmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000679
680 @property
681 def with_hostmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000682 return '%s/%s' % (self.network_address, self.hostmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000683
684 @property
685 def num_addresses(self):
686 """Number of hosts in the current subnet."""
687 return int(self.broadcast_address) - int(self.network_address) + 1
688
689 @property
Nick Coghlan51c30672012-05-27 00:25:58 +1000690 def _address_class(self):
Nick Coghland9722652012-06-17 16:33:00 +1000691 # Returning bare address objects (rather than interfaces) allows for
692 # more consistent behaviour across the network address, broadcast
693 # address and individual host addresses.
694 msg = '%200s has no associated address class' % (type(self),)
695 raise NotImplementedError(msg)
Nick Coghlan51c30672012-05-27 00:25:58 +1000696
697 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000698 def prefixlen(self):
699 return self._prefixlen
700
701 def address_exclude(self, other):
702 """Remove an address from a larger block.
703
704 For example:
705
706 addr1 = ip_network('192.0.2.0/28')
707 addr2 = ip_network('192.0.2.1/32')
708 addr1.address_exclude(addr2) =
709 [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
710 IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
711
712 or IPv6:
713
714 addr1 = ip_network('2001:db8::1/32')
715 addr2 = ip_network('2001:db8::1/128')
716 addr1.address_exclude(addr2) =
717 [ip_network('2001:db8::1/128'),
718 ip_network('2001:db8::2/127'),
719 ip_network('2001:db8::4/126'),
720 ip_network('2001:db8::8/125'),
721 ...
722 ip_network('2001:db8:8000::/33')]
723
724 Args:
725 other: An IPv4Network or IPv6Network object of the same type.
726
727 Returns:
728 An iterator of the the IPv(4|6)Network objects which is self
729 minus other.
730
731 Raises:
732 TypeError: If self and other are of difffering address
733 versions, or if other is not a network object.
734 ValueError: If other is not completely contained by self.
735
736 """
737 if not self._version == other._version:
738 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000739 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000740
741 if not isinstance(other, _BaseNetwork):
Nick Coghlan912238e2012-07-07 13:34:50 +1000742 raise TypeError("%s is not a network object" % other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000743
744 if not (other.network_address >= self.network_address and
745 other.broadcast_address <= self.broadcast_address):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200746 raise ValueError('%s not contained in %s' % (other, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000747 if other == self:
748 raise StopIteration
749
Nick Coghlandc9b2552012-05-20 21:01:57 +1000750 # Make sure we're comparing the network of other.
Nick Coghlan912238e2012-07-07 13:34:50 +1000751 other = other.__class__('%s/%s' % (other.network_address,
752 other.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000753
754 s1, s2 = self.subnets()
755 while s1 != other and s2 != other:
756 if (other.network_address >= s1.network_address and
757 other.broadcast_address <= s1.broadcast_address):
758 yield s2
759 s1, s2 = s1.subnets()
760 elif (other.network_address >= s2.network_address and
761 other.broadcast_address <= s2.broadcast_address):
762 yield s1
763 s1, s2 = s2.subnets()
764 else:
765 # If we got here, there's a bug somewhere.
766 raise AssertionError('Error performing exclusion: '
767 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000768 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000769 if s1 == other:
770 yield s2
771 elif s2 == other:
772 yield s1
773 else:
774 # If we got here, there's a bug somewhere.
775 raise AssertionError('Error performing exclusion: '
776 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000777 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000778
779 def compare_networks(self, other):
780 """Compare two IP objects.
781
782 This is only concerned about the comparison of the integer
783 representation of the network addresses. This means that the
784 host bits aren't considered at all in this method. If you want
785 to compare host bits, you can easily enough do a
786 'HostA._ip < HostB._ip'
787
788 Args:
789 other: An IP object.
790
791 Returns:
792 If the IP versions of self and other are the same, returns:
793
794 -1 if self < other:
795 eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
796 IPv6Network('2001:db8::1000/124') <
797 IPv6Network('2001:db8::2000/124')
798 0 if self == other
799 eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
800 IPv6Network('2001:db8::1000/124') ==
801 IPv6Network('2001:db8::1000/124')
802 1 if self > other
803 eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
804 IPv6Network('2001:db8::2000/124') >
805 IPv6Network('2001:db8::1000/124')
806
807 Raises:
808 TypeError if the IP versions are different.
809
810 """
811 # does this need to raise a ValueError?
812 if self._version != other._version:
813 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000814 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000815 # self._version == other._version below here:
816 if self.network_address < other.network_address:
817 return -1
818 if self.network_address > other.network_address:
819 return 1
820 # self.network_address == other.network_address below here:
821 if self.netmask < other.netmask:
822 return -1
823 if self.netmask > other.netmask:
824 return 1
825 return 0
826
827 def _get_networks_key(self):
828 """Network-only key function.
829
830 Returns an object that identifies this address' network and
831 netmask. This function is a suitable "key" argument for sorted()
832 and list.sort().
833
834 """
835 return (self._version, self.network_address, self.netmask)
836
837 def subnets(self, prefixlen_diff=1, new_prefix=None):
838 """The subnets which join to make the current subnet.
839
840 In the case that self contains only one IP
841 (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
842 for IPv6), yield an iterator with just ourself.
843
844 Args:
845 prefixlen_diff: An integer, the amount the prefix length
846 should be increased by. This should not be set if
847 new_prefix is also set.
848 new_prefix: The desired new prefix length. This must be a
849 larger number (smaller prefix) than the existing prefix.
850 This should not be set if prefixlen_diff is also set.
851
852 Returns:
853 An iterator of IPv(4|6) objects.
854
855 Raises:
856 ValueError: The prefixlen_diff is too small or too large.
857 OR
858 prefixlen_diff and new_prefix are both set or new_prefix
859 is a smaller number than the current prefix (smaller
860 number means a larger network)
861
862 """
863 if self._prefixlen == self._max_prefixlen:
864 yield self
865 return
866
867 if new_prefix is not None:
868 if new_prefix < self._prefixlen:
869 raise ValueError('new prefix must be longer')
870 if prefixlen_diff != 1:
871 raise ValueError('cannot set prefixlen_diff and new_prefix')
872 prefixlen_diff = new_prefix - self._prefixlen
873
874 if prefixlen_diff < 0:
875 raise ValueError('prefix length diff must be > 0')
876 new_prefixlen = self._prefixlen + prefixlen_diff
877
878 if not self._is_valid_netmask(str(new_prefixlen)):
879 raise ValueError(
880 'prefix length diff %d is invalid for netblock %s' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000881 new_prefixlen, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000882
Nick Coghlan51c30672012-05-27 00:25:58 +1000883 first = self.__class__('%s/%s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000884 (self.network_address,
885 self._prefixlen + prefixlen_diff))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000886
887 yield first
888 current = first
889 while True:
890 broadcast = current.broadcast_address
891 if broadcast == self.broadcast_address:
892 return
Nick Coghlan51c30672012-05-27 00:25:58 +1000893 new_addr = self._address_class(int(broadcast) + 1)
Nick Coghlan912238e2012-07-07 13:34:50 +1000894 current = self.__class__('%s/%s' % (new_addr,
895 new_prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000896
897 yield current
898
Nick Coghlandc9b2552012-05-20 21:01:57 +1000899 def supernet(self, prefixlen_diff=1, new_prefix=None):
900 """The supernet containing the current network.
901
902 Args:
903 prefixlen_diff: An integer, the amount the prefix length of
904 the network should be decreased by. For example, given a
905 /24 network and a prefixlen_diff of 3, a supernet with a
906 /21 netmask is returned.
907
908 Returns:
909 An IPv4 network object.
910
911 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200912 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
913 a negative prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000914 OR
915 If prefixlen_diff and new_prefix are both set or new_prefix is a
916 larger number than the current prefix (larger number means a
917 smaller network)
918
919 """
920 if self._prefixlen == 0:
921 return self
922
923 if new_prefix is not None:
924 if new_prefix > self._prefixlen:
925 raise ValueError('new prefix must be shorter')
926 if prefixlen_diff != 1:
927 raise ValueError('cannot set prefixlen_diff and new_prefix')
928 prefixlen_diff = self._prefixlen - new_prefix
929
Nick Coghlandc9b2552012-05-20 21:01:57 +1000930 if self.prefixlen - prefixlen_diff < 0:
931 raise ValueError(
932 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
933 (self.prefixlen, prefixlen_diff))
934 # TODO (pmoody): optimize this.
Nick Coghlan912238e2012-07-07 13:34:50 +1000935 t = self.__class__('%s/%d' % (self.network_address,
Nick Coghlan51c30672012-05-27 00:25:58 +1000936 self.prefixlen - prefixlen_diff),
937 strict=False)
Nick Coghlan912238e2012-07-07 13:34:50 +1000938 return t.__class__('%s/%d' % (t.network_address, t.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000939
940
Hynek Schlawackc4b78a32012-06-01 11:48:32 +0200941class _BaseV4:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000942
943 """Base IPv4 object.
944
945 The following methods are used by IPv4 objects in both single IP
946 addresses and networks.
947
948 """
949
950 # Equivalent to 255.255.255.255 or 32 bits of 1's.
951 _ALL_ONES = (2**IPV4LENGTH) - 1
952 _DECIMAL_DIGITS = frozenset('0123456789')
953
Hynek Schlawack91c5a342012-06-05 11:55:58 +0200954 # the valid octets for host and netmasks. only useful for IPv4.
Nick Coghlan7319f692012-07-07 21:43:30 +1000955 _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0))
Hynek Schlawack91c5a342012-06-05 11:55:58 +0200956
Nick Coghlandc9b2552012-05-20 21:01:57 +1000957 def __init__(self, address):
958 self._version = 4
959 self._max_prefixlen = IPV4LENGTH
960
961 def _explode_shorthand_ip_string(self):
962 return str(self)
963
964 def _ip_int_from_string(self, ip_str):
965 """Turn the given IP string into an integer for comparison.
966
967 Args:
968 ip_str: A string, the IP ip_str.
969
970 Returns:
971 The IP ip_str as an integer.
972
973 Raises:
974 AddressValueError: if ip_str isn't a valid IPv4 Address.
975
976 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000977 if not ip_str:
978 raise AddressValueError('Address cannot be empty')
979
Nick Coghlandc9b2552012-05-20 21:01:57 +1000980 octets = ip_str.split('.')
981 if len(octets) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000982 raise AddressValueError("Expected 4 octets in %r" % ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000983
Nick Coghlan7319f692012-07-07 21:43:30 +1000984 try:
985 return int.from_bytes(map(self._parse_octet, octets), 'big')
986 except ValueError as exc:
987 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +1000988
989 def _parse_octet(self, octet_str):
990 """Convert a decimal octet into an integer.
991
992 Args:
993 octet_str: A string, the number to parse.
994
995 Returns:
996 The octet as an integer.
997
998 Raises:
999 ValueError: if the octet isn't strictly a decimal from [0..255].
1000
1001 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001002 if not octet_str:
1003 raise ValueError("Empty octet not permitted")
Nick Coghlandc9b2552012-05-20 21:01:57 +10001004 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1005 if not self._DECIMAL_DIGITS.issuperset(octet_str):
Nick Coghlan07c4e332012-07-08 23:06:45 +10001006 msg = "Only decimal digits permitted in %r"
1007 raise ValueError(msg % octet_str)
1008 # We do the length check second, since the invalid character error
1009 # is likely to be more informative for the user
1010 if len(octet_str) > 3:
1011 msg = "At most 3 characters permitted in %r"
1012 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001013 # Convert to integer (we know digits are legal)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001014 octet_int = int(octet_str, 10)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001015 # Any octets that look like they *might* be written in octal,
1016 # and which don't look exactly the same in both octal and
1017 # decimal are rejected as ambiguous
1018 if octet_int > 7 and octet_str[0] == '0':
Nick Coghlan07c4e332012-07-08 23:06:45 +10001019 msg = "Ambiguous (octal/decimal) value in %r not permitted"
1020 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001021 if octet_int > 255:
Nick Coghlanb582ecc2012-07-07 22:15:22 +10001022 raise ValueError("Octet %d (> 255) not permitted" % octet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001023 return octet_int
1024
1025 def _string_from_ip_int(self, ip_int):
1026 """Turns a 32-bit integer into dotted decimal notation.
1027
1028 Args:
1029 ip_int: An integer, the IP address.
1030
1031 Returns:
1032 The IP address as a string in dotted decimal notation.
1033
1034 """
Nick Coghlan7319f692012-07-07 21:43:30 +10001035 return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001036
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001037 def _is_valid_netmask(self, netmask):
1038 """Verify that the netmask is valid.
1039
1040 Args:
1041 netmask: A string, either a prefix or dotted decimal
1042 netmask.
1043
1044 Returns:
1045 A boolean, True if the prefix represents a valid IPv4
1046 netmask.
1047
1048 """
1049 mask = netmask.split('.')
1050 if len(mask) == 4:
Nick Coghlan7319f692012-07-07 21:43:30 +10001051 try:
1052 for x in mask:
1053 if int(x) not in self._valid_mask_octets:
1054 return False
1055 except ValueError:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001056 # Found something that isn't an integer or isn't valid
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001057 return False
Nick Coghlan7319f692012-07-07 21:43:30 +10001058 for idx, y in enumerate(mask):
1059 if idx > 0 and y > mask[idx - 1]:
1060 return False
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001061 return True
1062 try:
1063 netmask = int(netmask)
1064 except ValueError:
1065 return False
1066 return 0 <= netmask <= self._max_prefixlen
1067
1068 def _is_hostmask(self, ip_str):
1069 """Test if the IP string is a hostmask (rather than a netmask).
1070
1071 Args:
1072 ip_str: A string, the potential hostmask.
1073
1074 Returns:
1075 A boolean, True if the IP string is a hostmask.
1076
1077 """
1078 bits = ip_str.split('.')
1079 try:
Nick Coghlan7319f692012-07-07 21:43:30 +10001080 parts = [x for x in map(int, bits) if x in self._valid_mask_octets]
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001081 except ValueError:
1082 return False
1083 if len(parts) != len(bits):
1084 return False
1085 if parts[0] < parts[-1]:
1086 return True
1087 return False
1088
Nick Coghlandc9b2552012-05-20 21:01:57 +10001089 @property
1090 def max_prefixlen(self):
1091 return self._max_prefixlen
1092
1093 @property
1094 def version(self):
1095 return self._version
1096
1097 @property
1098 def is_reserved(self):
1099 """Test if the address is otherwise IETF reserved.
1100
1101 Returns:
1102 A boolean, True if the address is within the
1103 reserved IPv4 Network range.
1104
1105 """
1106 reserved_network = IPv4Network('240.0.0.0/4')
1107 if isinstance(self, _BaseAddress):
1108 return self in reserved_network
1109 return (self.network_address in reserved_network and
1110 self.broadcast_address in reserved_network)
1111
1112 @property
1113 def is_private(self):
1114 """Test if this address is allocated for private networks.
1115
1116 Returns:
1117 A boolean, True if the address is reserved per RFC 1918.
1118
1119 """
1120 private_10 = IPv4Network('10.0.0.0/8')
1121 private_172 = IPv4Network('172.16.0.0/12')
1122 private_192 = IPv4Network('192.168.0.0/16')
1123 if isinstance(self, _BaseAddress):
1124 return (self in private_10 or self in private_172 or
1125 self in private_192)
1126 else:
1127 return ((self.network_address in private_10 and
1128 self.broadcast_address in private_10) or
1129 (self.network_address in private_172 and
1130 self.broadcast_address in private_172) or
1131 (self.network_address in private_192 and
1132 self.broadcast_address in private_192))
1133
1134 @property
1135 def is_multicast(self):
1136 """Test if the address is reserved for multicast use.
1137
1138 Returns:
1139 A boolean, True if the address is multicast.
1140 See RFC 3171 for details.
1141
1142 """
1143 multicast_network = IPv4Network('224.0.0.0/4')
1144 if isinstance(self, _BaseAddress):
1145 return self in IPv4Network('224.0.0.0/4')
1146 return (self.network_address in multicast_network and
1147 self.broadcast_address in multicast_network)
1148
1149 @property
1150 def is_unspecified(self):
1151 """Test if the address is unspecified.
1152
1153 Returns:
1154 A boolean, True if this is the unspecified address as defined in
1155 RFC 5735 3.
1156
1157 """
1158 unspecified_address = IPv4Address('0.0.0.0')
1159 if isinstance(self, _BaseAddress):
Hynek Schlawackbcd30442012-06-04 14:19:39 +02001160 return self == unspecified_address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001161 return (self.network_address == self.broadcast_address ==
1162 unspecified_address)
1163
1164 @property
1165 def is_loopback(self):
1166 """Test if the address is a loopback address.
1167
1168 Returns:
1169 A boolean, True if the address is a loopback per RFC 3330.
1170
1171 """
1172 loopback_address = IPv4Network('127.0.0.0/8')
1173 if isinstance(self, _BaseAddress):
1174 return self in loopback_address
1175
1176 return (self.network_address in loopback_address and
1177 self.broadcast_address in loopback_address)
1178
1179 @property
1180 def is_link_local(self):
1181 """Test if the address is reserved for link-local.
1182
1183 Returns:
1184 A boolean, True if the address is link-local per RFC 3927.
1185
1186 """
1187 linklocal_network = IPv4Network('169.254.0.0/16')
1188 if isinstance(self, _BaseAddress):
1189 return self in linklocal_network
1190 return (self.network_address in linklocal_network and
1191 self.broadcast_address in linklocal_network)
1192
1193
1194class IPv4Address(_BaseV4, _BaseAddress):
1195
1196 """Represent and manipulate single IPv4 Addresses."""
1197
1198 def __init__(self, address):
1199
1200 """
1201 Args:
1202 address: A string or integer representing the IP
1203
1204 Additionally, an integer can be passed, so
1205 IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1206 or, more generally
1207 IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1208 IPv4Address('192.0.2.1')
1209
1210 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001211 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001212
1213 """
1214 _BaseAddress.__init__(self, address)
1215 _BaseV4.__init__(self, address)
1216
1217 # Efficient constructor from integer.
1218 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001219 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001220 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001221 return
1222
1223 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001224 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001225 self._check_packed_address(address, 4)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001226 self._ip = struct.unpack('!I', address)[0]
1227 return
1228
1229 # Assume input argument to be string or any object representation
1230 # which converts into a formatted IP string.
1231 addr_str = str(address)
1232 self._ip = self._ip_int_from_string(addr_str)
1233
1234 @property
1235 def packed(self):
1236 """The binary representation of this address."""
1237 return v4_int_to_packed(self._ip)
1238
1239
1240class IPv4Interface(IPv4Address):
1241
Nick Coghlandc9b2552012-05-20 21:01:57 +10001242 def __init__(self, address):
1243 if isinstance(address, (bytes, int)):
1244 IPv4Address.__init__(self, address)
1245 self.network = IPv4Network(self._ip)
1246 self._prefixlen = self._max_prefixlen
1247 return
1248
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001249 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001250 IPv4Address.__init__(self, addr[0])
1251
1252 self.network = IPv4Network(address, strict=False)
1253 self._prefixlen = self.network._prefixlen
1254
1255 self.netmask = self.network.netmask
1256 self.hostmask = self.network.hostmask
1257
Nick Coghlandc9b2552012-05-20 21:01:57 +10001258 def __str__(self):
1259 return '%s/%d' % (self._string_from_ip_int(self._ip),
1260 self.network.prefixlen)
1261
1262 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001263 address_equal = IPv4Address.__eq__(self, other)
1264 if not address_equal or address_equal is NotImplemented:
1265 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001266 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001267 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001268 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001269 # An interface with an associated network is NOT the
1270 # same as an unassociated address. That's why the hash
1271 # takes the extra info into account.
1272 return False
1273
1274 def __lt__(self, other):
1275 address_less = IPv4Address.__lt__(self, other)
1276 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001277 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001278 try:
1279 return self.network < other.network
1280 except AttributeError:
1281 # We *do* allow addresses and interfaces to be sorted. The
1282 # unassociated address is considered less than all interfaces.
1283 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001284
1285 def __hash__(self):
1286 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1287
Nick Coghlandc9b2552012-05-20 21:01:57 +10001288 @property
1289 def prefixlen(self):
1290 return self._prefixlen
1291
1292 @property
1293 def ip(self):
1294 return IPv4Address(self._ip)
1295
1296 @property
1297 def with_prefixlen(self):
1298 return self
1299
1300 @property
1301 def with_netmask(self):
1302 return '%s/%s' % (self._string_from_ip_int(self._ip),
1303 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001304
Nick Coghlandc9b2552012-05-20 21:01:57 +10001305 @property
1306 def with_hostmask(self):
1307 return '%s/%s' % (self._string_from_ip_int(self._ip),
1308 self.hostmask)
1309
1310
1311class IPv4Network(_BaseV4, _BaseNetwork):
1312
1313 """This class represents and manipulates 32-bit IPv4 network + addresses..
1314
1315 Attributes: [examples for IPv4Network('192.0.2.0/27')]
1316 .network_address: IPv4Address('192.0.2.0')
1317 .hostmask: IPv4Address('0.0.0.31')
1318 .broadcast_address: IPv4Address('192.0.2.32')
1319 .netmask: IPv4Address('255.255.255.224')
1320 .prefixlen: 27
1321
1322 """
Nick Coghlan51c30672012-05-27 00:25:58 +10001323 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001324 _address_class = IPv4Address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001325
Nick Coghlandc9b2552012-05-20 21:01:57 +10001326 def __init__(self, address, strict=True):
1327
1328 """Instantiate a new IPv4 network object.
1329
1330 Args:
1331 address: A string or integer representing the IP [& network].
1332 '192.0.2.0/24'
1333 '192.0.2.0/255.255.255.0'
1334 '192.0.0.2/0.0.0.255'
1335 are all functionally the same in IPv4. Similarly,
1336 '192.0.2.1'
1337 '192.0.2.1/255.255.255.255'
1338 '192.0.2.1/32'
1339 are also functionaly equivalent. That is to say, failing to
1340 provide a subnetmask will create an object with a mask of /32.
1341
1342 If the mask (portion after the / in the argument) is given in
1343 dotted quad form, it is treated as a netmask if it starts with a
1344 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1345 starts with a zero field (e.g. 0.255.255.255 == /8), with the
1346 single exception of an all-zero mask which is treated as a
1347 netmask == /0. If no mask is given, a default of /32 is used.
1348
1349 Additionally, an integer can be passed, so
1350 IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1351 or, more generally
1352 IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1353 IPv4Interface('192.0.2.1')
1354
1355 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001356 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001357 NetmaskValueError: If the netmask isn't valid for
1358 an IPv4 address.
Sandro Tosib4386d32012-06-02 17:14:22 +02001359 ValueError: If strict is True and a network address is not
Nick Coghlandc9b2552012-05-20 21:01:57 +10001360 supplied.
1361
1362 """
1363
1364 _BaseV4.__init__(self, address)
1365 _BaseNetwork.__init__(self, address)
1366
1367 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001368 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001369 self.network_address = IPv4Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001370 self._prefixlen = self._max_prefixlen
1371 self.netmask = IPv4Address(self._ALL_ONES)
1372 #fixme: address/network test here
1373 return
1374
1375 # Efficient constructor from integer.
1376 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001377 self.network_address = IPv4Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001378 self._prefixlen = self._max_prefixlen
1379 self.netmask = IPv4Address(self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001380 #fixme: address/network test here.
1381 return
1382
1383 # Assume input argument to be string or any object representation
1384 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001385 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001386 self.network_address = IPv4Address(self._ip_int_from_string(addr[0]))
1387
Nick Coghlandc9b2552012-05-20 21:01:57 +10001388 if len(addr) == 2:
1389 mask = addr[1].split('.')
1390
1391 if len(mask) == 4:
1392 # We have dotted decimal netmask.
1393 if self._is_valid_netmask(addr[1]):
1394 self.netmask = IPv4Address(self._ip_int_from_string(
1395 addr[1]))
1396 elif self._is_hostmask(addr[1]):
1397 self.netmask = IPv4Address(
1398 self._ip_int_from_string(addr[1]) ^ self._ALL_ONES)
1399 else:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001400 raise NetmaskValueError('%r is not a valid netmask'
Nick Coghlandc9b2552012-05-20 21:01:57 +10001401 % addr[1])
1402
1403 self._prefixlen = self._prefix_from_ip_int(int(self.netmask))
1404 else:
1405 # We have a netmask in prefix length form.
1406 if not self._is_valid_netmask(addr[1]):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001407 raise NetmaskValueError('%r is not a valid netmask'
1408 % addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001409 self._prefixlen = int(addr[1])
1410 self.netmask = IPv4Address(self._ip_int_from_prefix(
1411 self._prefixlen))
1412 else:
1413 self._prefixlen = self._max_prefixlen
1414 self.netmask = IPv4Address(self._ip_int_from_prefix(
1415 self._prefixlen))
1416
1417 if strict:
1418 if (IPv4Address(int(self.network_address) & int(self.netmask)) !=
1419 self.network_address):
1420 raise ValueError('%s has host bits set' % self)
1421 self.network_address = IPv4Address(int(self.network_address) &
1422 int(self.netmask))
1423
1424 if self._prefixlen == (self._max_prefixlen - 1):
1425 self.hosts = self.__iter__
1426
Nick Coghlandc9b2552012-05-20 21:01:57 +10001427
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001428class _BaseV6:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001429
1430 """Base IPv6 object.
1431
1432 The following methods are used by IPv6 objects in both single IP
1433 addresses and networks.
1434
1435 """
1436
1437 _ALL_ONES = (2**IPV6LENGTH) - 1
1438 _HEXTET_COUNT = 8
1439 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
1440
1441 def __init__(self, address):
1442 self._version = 6
1443 self._max_prefixlen = IPV6LENGTH
1444
1445 def _ip_int_from_string(self, ip_str):
1446 """Turn an IPv6 ip_str into an integer.
1447
1448 Args:
1449 ip_str: A string, the IPv6 ip_str.
1450
1451 Returns:
1452 An int, the IPv6 address
1453
1454 Raises:
1455 AddressValueError: if ip_str isn't a valid IPv6 Address.
1456
1457 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001458 if not ip_str:
1459 raise AddressValueError('Address cannot be empty')
1460
Nick Coghlandc9b2552012-05-20 21:01:57 +10001461 parts = ip_str.split(':')
1462
1463 # An IPv6 address needs at least 2 colons (3 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001464 _min_parts = 3
1465 if len(parts) < _min_parts:
1466 msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
1467 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001468
1469 # If the address has an IPv4-style suffix, convert it to hexadecimal.
1470 if '.' in parts[-1]:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001471 try:
1472 ipv4_int = IPv4Address(parts.pop())._ip
1473 except AddressValueError as exc:
1474 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001475 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1476 parts.append('%x' % (ipv4_int & 0xFFFF))
1477
1478 # An IPv6 address can't have more than 8 colons (9 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001479 # The extra colon comes from using the "::" notation for a single
1480 # leading or trailing zero part.
1481 _max_parts = self._HEXTET_COUNT + 1
1482 if len(parts) > _max_parts:
1483 msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
1484 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001485
1486 # Disregarding the endpoints, find '::' with nothing in between.
1487 # This indicates that a run of zeroes has been skipped.
Nick Coghlan7319f692012-07-07 21:43:30 +10001488 skip_index = None
1489 for i in range(1, len(parts) - 1):
1490 if not parts[i]:
1491 if skip_index is not None:
1492 # Can't have more than one '::'
1493 msg = "At most one '::' permitted in %r" % ip_str
1494 raise AddressValueError(msg)
1495 skip_index = i
Nick Coghlandc9b2552012-05-20 21:01:57 +10001496
1497 # parts_hi is the number of parts to copy from above/before the '::'
1498 # parts_lo is the number of parts to copy from below/after the '::'
1499 if skip_index is not None:
1500 # If we found a '::', then check if it also covers the endpoints.
1501 parts_hi = skip_index
1502 parts_lo = len(parts) - skip_index - 1
1503 if not parts[0]:
1504 parts_hi -= 1
1505 if parts_hi:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001506 msg = "Leading ':' only permitted as part of '::' in %r"
1507 raise AddressValueError(msg % ip_str) # ^: requires ^::
Nick Coghlandc9b2552012-05-20 21:01:57 +10001508 if not parts[-1]:
1509 parts_lo -= 1
1510 if parts_lo:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001511 msg = "Trailing ':' only permitted as part of '::' in %r"
1512 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001513 parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo)
1514 if parts_skipped < 1:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001515 msg = "Expected at most %d other parts with '::' in %r"
1516 raise AddressValueError(msg % (self._HEXTET_COUNT-1, ip_str))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001517 else:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001518 # Otherwise, allocate the entire address to parts_hi. The
1519 # endpoints could still be empty, but _parse_hextet() will check
1520 # for that.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001521 if len(parts) != self._HEXTET_COUNT:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001522 msg = "Exactly %d parts expected without '::' in %r"
1523 raise AddressValueError(msg % (self._HEXTET_COUNT, ip_str))
1524 if not parts[0]:
1525 msg = "Leading ':' only permitted as part of '::' in %r"
1526 raise AddressValueError(msg % ip_str) # ^: requires ^::
1527 if not parts[-1]:
1528 msg = "Trailing ':' only permitted as part of '::' in %r"
1529 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001530 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
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001545 except ValueError as exc:
1546 raise AddressValueError("%s in %r" % (exc, 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.
1563 if not self._HEX_DIGITS.issuperset(hextet_str):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001564 raise ValueError("Only hex digits permitted in %r" % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001565 # We do the length check second, since the invalid character error
1566 # is likely to be more informative for the user
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001567 if len(hextet_str) > 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001568 msg = "At most 4 characters permitted in %r"
1569 raise ValueError(msg % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001570 # Length check means we can skip checking the integer value
1571 return int(hextet_str, 16)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001572
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
Nick Coghlan7319f692012-07-07 21:43:30 +10001640 hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001641
1642 hextets = self._compress_hextets(hextets)
1643 return ':'.join(hextets)
1644
1645 def _explode_shorthand_ip_string(self):
1646 """Expand a shortened IPv6 address.
1647
1648 Args:
1649 ip_str: A string, the IPv6 address.
1650
1651 Returns:
1652 A string, the expanded IPv6 address.
1653
1654 """
1655 if isinstance(self, IPv6Network):
1656 ip_str = str(self.network_address)
1657 elif isinstance(self, IPv6Interface):
1658 ip_str = str(self.ip)
1659 else:
1660 ip_str = str(self)
1661
1662 ip_int = self._ip_int_from_string(ip_str)
Nick Coghlan7319f692012-07-07 21:43:30 +10001663 hex_str = '%032x' % ip_int
1664 parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001665 if isinstance(self, (_BaseNetwork, IPv6Interface)):
1666 return '%s/%d' % (':'.join(parts), self.prefixlen)
1667 return ':'.join(parts)
1668
1669 @property
1670 def max_prefixlen(self):
1671 return self._max_prefixlen
1672
1673 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001674 def version(self):
1675 return self._version
1676
1677 @property
1678 def is_multicast(self):
1679 """Test if the address is reserved for multicast use.
1680
1681 Returns:
1682 A boolean, True if the address is a multicast address.
1683 See RFC 2373 2.7 for details.
1684
1685 """
1686 multicast_network = IPv6Network('ff00::/8')
1687 if isinstance(self, _BaseAddress):
1688 return self in multicast_network
1689 return (self.network_address in multicast_network and
1690 self.broadcast_address in multicast_network)
1691
1692 @property
1693 def is_reserved(self):
1694 """Test if the address is otherwise IETF reserved.
1695
1696 Returns:
1697 A boolean, True if the address is within one of the
1698 reserved IPv6 Network ranges.
1699
1700 """
1701 reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'),
1702 IPv6Network('200::/7'), IPv6Network('400::/6'),
1703 IPv6Network('800::/5'), IPv6Network('1000::/4'),
1704 IPv6Network('4000::/3'), IPv6Network('6000::/3'),
1705 IPv6Network('8000::/3'), IPv6Network('A000::/3'),
1706 IPv6Network('C000::/3'), IPv6Network('E000::/4'),
1707 IPv6Network('F000::/5'), IPv6Network('F800::/6'),
1708 IPv6Network('FE00::/9')]
1709
1710 if isinstance(self, _BaseAddress):
Nick Coghlan7319f692012-07-07 21:43:30 +10001711 return any(self in x for x in reserved_networks)
1712 return any(self.network_address in x and self.broadcast_address in x
1713 for x in reserved_networks)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001714
1715 @property
1716 def is_link_local(self):
1717 """Test if the address is reserved for link-local.
1718
1719 Returns:
1720 A boolean, True if the address is reserved per RFC 4291.
1721
1722 """
1723 linklocal_network = IPv6Network('fe80::/10')
1724 if isinstance(self, _BaseAddress):
1725 return self in linklocal_network
1726 return (self.network_address in linklocal_network and
1727 self.broadcast_address in linklocal_network)
1728
1729 @property
1730 def is_site_local(self):
1731 """Test if the address is reserved for site-local.
1732
1733 Note that the site-local address space has been deprecated by RFC 3879.
1734 Use is_private to test if this address is in the space of unique local
1735 addresses as defined by RFC 4193.
1736
1737 Returns:
1738 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1739
1740 """
1741 sitelocal_network = IPv6Network('fec0::/10')
1742 if isinstance(self, _BaseAddress):
1743 return self in sitelocal_network
1744 return (self.network_address in sitelocal_network and
1745 self.broadcast_address in sitelocal_network)
1746
1747 @property
1748 def is_private(self):
1749 """Test if this address is allocated for private networks.
1750
1751 Returns:
1752 A boolean, True if the address is reserved per RFC 4193.
1753
1754 """
1755 private_network = IPv6Network('fc00::/7')
1756 if isinstance(self, _BaseAddress):
1757 return self in private_network
1758 return (self.network_address in private_network and
1759 self.broadcast_address in private_network)
1760
Nick Coghlandc9b2552012-05-20 21:01:57 +10001761 @property
1762 def ipv4_mapped(self):
1763 """Return the IPv4 mapped address.
1764
1765 Returns:
1766 If the IPv6 address is a v4 mapped address, return the
1767 IPv4 mapped address. Return None otherwise.
1768
1769 """
1770 if (self._ip >> 32) != 0xFFFF:
1771 return None
1772 return IPv4Address(self._ip & 0xFFFFFFFF)
1773
1774 @property
1775 def teredo(self):
1776 """Tuple of embedded teredo IPs.
1777
1778 Returns:
1779 Tuple of the (server, client) IPs or None if the address
1780 doesn't appear to be a teredo address (doesn't start with
1781 2001::/32)
1782
1783 """
1784 if (self._ip >> 96) != 0x20010000:
1785 return None
1786 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
1787 IPv4Address(~self._ip & 0xFFFFFFFF))
1788
1789 @property
1790 def sixtofour(self):
1791 """Return the IPv4 6to4 embedded address.
1792
1793 Returns:
1794 The IPv4 6to4-embedded address if present or None if the
1795 address doesn't appear to contain a 6to4 embedded address.
1796
1797 """
1798 if (self._ip >> 112) != 0x2002:
1799 return None
1800 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
1801
1802 @property
1803 def is_unspecified(self):
1804 """Test if the address is unspecified.
1805
1806 Returns:
1807 A boolean, True if this is the unspecified address as defined in
1808 RFC 2373 2.5.2.
1809
1810 """
1811 if isinstance(self, (IPv6Network, IPv6Interface)):
1812 return int(self.network_address) == 0 and getattr(
1813 self, '_prefixlen', 128) == 128
1814 return self._ip == 0
1815
1816 @property
1817 def is_loopback(self):
1818 """Test if the address is a loopback address.
1819
1820 Returns:
1821 A boolean, True if the address is a loopback address as defined in
1822 RFC 2373 2.5.3.
1823
1824 """
1825 if isinstance(self, IPv6Network):
Nick Coghlan2c589102012-05-27 01:03:25 +10001826 return int(self) == 1 and getattr(
Nick Coghlandc9b2552012-05-20 21:01:57 +10001827 self, '_prefixlen', 128) == 128
1828 elif isinstance(self, IPv6Interface):
1829 return int(self.network.network_address) == 1 and getattr(
1830 self, '_prefixlen', 128) == 128
1831 return self._ip == 1
1832
1833
1834class IPv6Address(_BaseV6, _BaseAddress):
1835
Sandro Tosib95c6342012-05-23 23:17:22 +02001836 """Represent and manipulate single IPv6 Addresses."""
Nick Coghlandc9b2552012-05-20 21:01:57 +10001837
1838 def __init__(self, address):
1839 """Instantiate a new IPv6 address object.
1840
1841 Args:
1842 address: A string or integer representing the IP
1843
1844 Additionally, an integer can be passed, so
1845 IPv6Address('2001:db8::') ==
1846 IPv6Address(42540766411282592856903984951653826560)
1847 or, more generally
1848 IPv6Address(int(IPv6Address('2001:db8::'))) ==
1849 IPv6Address('2001:db8::')
1850
1851 Raises:
1852 AddressValueError: If address isn't a valid IPv6 address.
1853
1854 """
1855 _BaseAddress.__init__(self, address)
1856 _BaseV6.__init__(self, address)
1857
1858 # Efficient constructor from integer.
1859 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001860 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001861 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001862 return
1863
1864 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001865 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001866 self._check_packed_address(address, 16)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001867 tmp = struct.unpack('!QQ', address)
1868 self._ip = (tmp[0] << 64) | tmp[1]
1869 return
1870
1871 # Assume input argument to be string or any object representation
1872 # which converts into a formatted IP string.
1873 addr_str = str(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001874 self._ip = self._ip_int_from_string(addr_str)
1875
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001876 @property
1877 def packed(self):
1878 """The binary representation of this address."""
1879 return v6_int_to_packed(self._ip)
1880
Nick Coghlandc9b2552012-05-20 21:01:57 +10001881
1882class IPv6Interface(IPv6Address):
1883
1884 def __init__(self, address):
1885 if isinstance(address, (bytes, int)):
1886 IPv6Address.__init__(self, address)
1887 self.network = IPv6Network(self._ip)
1888 self._prefixlen = self._max_prefixlen
1889 return
1890
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001891 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001892 IPv6Address.__init__(self, addr[0])
1893 self.network = IPv6Network(address, strict=False)
1894 self.netmask = self.network.netmask
1895 self._prefixlen = self.network._prefixlen
1896 self.hostmask = self.network.hostmask
1897
Nick Coghlandc9b2552012-05-20 21:01:57 +10001898 def __str__(self):
1899 return '%s/%d' % (self._string_from_ip_int(self._ip),
1900 self.network.prefixlen)
1901
1902 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001903 address_equal = IPv6Address.__eq__(self, other)
1904 if not address_equal or address_equal is NotImplemented:
1905 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001906 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001907 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001908 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001909 # An interface with an associated network is NOT the
1910 # same as an unassociated address. That's why the hash
1911 # takes the extra info into account.
1912 return False
1913
1914 def __lt__(self, other):
1915 address_less = IPv6Address.__lt__(self, other)
1916 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001917 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001918 try:
1919 return self.network < other.network
1920 except AttributeError:
1921 # We *do* allow addresses and interfaces to be sorted. The
1922 # unassociated address is considered less than all interfaces.
1923 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001924
1925 def __hash__(self):
1926 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1927
1928 @property
1929 def prefixlen(self):
1930 return self._prefixlen
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001931
Nick Coghlandc9b2552012-05-20 21:01:57 +10001932 @property
1933 def ip(self):
1934 return IPv6Address(self._ip)
1935
1936 @property
1937 def with_prefixlen(self):
1938 return self
1939
1940 @property
1941 def with_netmask(self):
1942 return self.with_prefixlen
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001943
Nick Coghlandc9b2552012-05-20 21:01:57 +10001944 @property
1945 def with_hostmask(self):
1946 return '%s/%s' % (self._string_from_ip_int(self._ip),
1947 self.hostmask)
1948
1949
1950class IPv6Network(_BaseV6, _BaseNetwork):
1951
1952 """This class represents and manipulates 128-bit IPv6 networks.
1953
1954 Attributes: [examples for IPv6('2001:db8::1000/124')]
1955 .network_address: IPv6Address('2001:db8::1000')
1956 .hostmask: IPv6Address('::f')
1957 .broadcast_address: IPv6Address('2001:db8::100f')
1958 .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
1959 .prefixlen: 124
1960
1961 """
1962
Nick Coghlan51c30672012-05-27 00:25:58 +10001963 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001964 _address_class = IPv6Address
1965
Nick Coghlandc9b2552012-05-20 21:01:57 +10001966 def __init__(self, address, strict=True):
1967 """Instantiate a new IPv6 Network object.
1968
1969 Args:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001970 address: A string or integer representing the IPv6 network or the
1971 IP and prefix/netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001972 '2001:db8::/128'
1973 '2001:db8:0000:0000:0000:0000:0000:0000/128'
1974 '2001:db8::'
1975 are all functionally the same in IPv6. That is to say,
1976 failing to provide a subnetmask will create an object with
1977 a mask of /128.
1978
1979 Additionally, an integer can be passed, so
1980 IPv6Network('2001:db8::') ==
1981 IPv6Network(42540766411282592856903984951653826560)
1982 or, more generally
1983 IPv6Network(int(IPv6Network('2001:db8::'))) ==
1984 IPv6Network('2001:db8::')
1985
1986 strict: A boolean. If true, ensure that we have been passed
1987 A true network address, eg, 2001:db8::1000/124 and not an
1988 IP address on a network, eg, 2001:db8::1/124.
1989
1990 Raises:
1991 AddressValueError: If address isn't a valid IPv6 address.
1992 NetmaskValueError: If the netmask isn't valid for
1993 an IPv6 address.
1994 ValueError: If strict was True and a network address was not
1995 supplied.
1996
1997 """
1998 _BaseV6.__init__(self, address)
1999 _BaseNetwork.__init__(self, address)
2000
2001 # Efficient constructor from integer.
2002 if isinstance(address, int):
Nick Coghlandc9b2552012-05-20 21:01:57 +10002003 self.network_address = IPv6Address(address)
2004 self._prefixlen = self._max_prefixlen
2005 self.netmask = IPv6Address(self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002006 return
2007
2008 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10002009 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10002010 self.network_address = IPv6Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002011 self._prefixlen = self._max_prefixlen
2012 self.netmask = IPv6Address(self._ALL_ONES)
Hynek Schlawacked36b2e2012-06-08 15:21:21 +02002013 return
Nick Coghlandc9b2552012-05-20 21:01:57 +10002014
2015 # Assume input argument to be string or any object representation
2016 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002017 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002018
2019 self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))
2020
2021 if len(addr) == 2:
2022 if self._is_valid_netmask(addr[1]):
2023 self._prefixlen = int(addr[1])
2024 else:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002025 raise NetmaskValueError('%r is not a valid netmask'
2026 % addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10002027 else:
2028 self._prefixlen = self._max_prefixlen
2029
2030 self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen))
2031 if strict:
2032 if (IPv6Address(int(self.network_address) & int(self.netmask)) !=
2033 self.network_address):
Nick Coghlan912238e2012-07-07 13:34:50 +10002034 raise ValueError('%s has host bits set' % self)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002035 self.network_address = IPv6Address(int(self.network_address) &
2036 int(self.netmask))
2037
2038 if self._prefixlen == (self._max_prefixlen - 1):
2039 self.hosts = self.__iter__
2040
Nick Coghlandc9b2552012-05-20 21:01:57 +10002041 def _is_valid_netmask(self, prefixlen):
2042 """Verify that the netmask/prefixlen is valid.
2043
2044 Args:
2045 prefixlen: A string, the netmask in prefix length format.
2046
2047 Returns:
2048 A boolean, True if the prefix represents a valid IPv6
2049 netmask.
2050
2051 """
2052 try:
2053 prefixlen = int(prefixlen)
2054 except ValueError:
2055 return False
2056 return 0 <= prefixlen <= self._max_prefixlen