blob: c6eea7fac8f0dc310f83daee3143fb25aa07d999 [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
514 def __index__(self):
515 return self._ip
516
517 def __int__(self):
518 return self._ip
519
Nick Coghlandc9b2552012-05-20 21:01:57 +1000520 def __eq__(self, other):
521 try:
522 return (self._ip == other._ip
523 and self._version == other._version)
524 except AttributeError:
525 return NotImplemented
526
Nick Coghlandc9b2552012-05-20 21:01:57 +1000527 def __lt__(self, other):
528 if self._version != other._version:
529 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000530 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000531 if not isinstance(other, _BaseAddress):
532 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000533 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000534 if self._ip != other._ip:
535 return self._ip < other._ip
536 return False
537
Nick Coghlandc9b2552012-05-20 21:01:57 +1000538 # Shorthand for Integer addition and subtraction. This is not
539 # meant to ever support addition/subtraction of addresses.
540 def __add__(self, other):
541 if not isinstance(other, int):
542 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000543 return self.__class__(int(self) + other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000544
545 def __sub__(self, other):
546 if not isinstance(other, int):
547 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000548 return self.__class__(int(self) - other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000549
550 def __repr__(self):
551 return '%s(%r)' % (self.__class__.__name__, str(self))
552
553 def __str__(self):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200554 return str(self._string_from_ip_int(self._ip))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000555
556 def __hash__(self):
557 return hash(hex(int(self._ip)))
558
559 def _get_address_key(self):
560 return (self._version, self)
561
Nick Coghlandc9b2552012-05-20 21:01:57 +1000562
563class _BaseNetwork(_IPAddressBase):
564
Nick Coghlan51c30672012-05-27 00:25:58 +1000565 """A generic IP network object.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000566
567 This IP class contains the version independent methods which are
568 used by networks.
569
570 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000571 def __init__(self, address):
572 self._cache = {}
573
574 def __index__(self):
575 return int(self.network_address) ^ self.prefixlen
576
577 def __int__(self):
578 return int(self.network_address)
579
580 def __repr__(self):
581 return '%s(%r)' % (self.__class__.__name__, str(self))
582
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200583 def __str__(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000584 return '%s/%d' % (self.network_address, self.prefixlen)
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200585
Nick Coghlandc9b2552012-05-20 21:01:57 +1000586 def hosts(self):
587 """Generate Iterator over usable hosts in a network.
588
Sandro Tosib95c6342012-05-23 23:17:22 +0200589 This is like __iter__ except it doesn't return the network
590 or broadcast addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000591
592 """
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 + 1, broadcast):
596 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000597
598 def __iter__(self):
Nick Coghlan7319f692012-07-07 21:43:30 +1000599 network = int(self.network_address)
600 broadcast = int(self.broadcast_address)
601 for x in range(network, broadcast + 1):
602 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000603
604 def __getitem__(self, n):
605 network = int(self.network_address)
606 broadcast = int(self.broadcast_address)
607 if n >= 0:
608 if network + n > broadcast:
609 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000610 return self._address_class(network + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000611 else:
612 n += 1
613 if broadcast + n < network:
614 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000615 return self._address_class(broadcast + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000616
617 def __lt__(self, other):
618 if self._version != other._version:
619 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000620 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000621 if not isinstance(other, _BaseNetwork):
622 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000623 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000624 if self.network_address != other.network_address:
625 return self.network_address < other.network_address
626 if self.netmask != other.netmask:
627 return self.netmask < other.netmask
628 return False
629
Nick Coghlandc9b2552012-05-20 21:01:57 +1000630 def __eq__(self, other):
Nick Coghlan9a9c28c2012-07-07 23:05:59 +1000631 try:
632 return (self._version == other._version and
633 self.network_address == other.network_address and
634 int(self.netmask) == int(other.netmask))
635 except AttributeError:
636 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000637
Nick Coghlandc9b2552012-05-20 21:01:57 +1000638 def __hash__(self):
639 return hash(int(self.network_address) ^ int(self.netmask))
640
641 def __contains__(self, other):
642 # always false if one is v4 and the other is v6.
643 if self._version != other._version:
644 return False
645 # dealing with another network.
646 if isinstance(other, _BaseNetwork):
647 return False
648 # dealing with another address
649 else:
650 # address
651 return (int(self.network_address) <= int(other._ip) <=
652 int(self.broadcast_address))
653
654 def overlaps(self, other):
655 """Tell if self is partly contained in other."""
656 return self.network_address in other or (
657 self.broadcast_address in other or (
658 other.network_address in self or (
659 other.broadcast_address in self)))
660
661 @property
662 def broadcast_address(self):
663 x = self._cache.get('broadcast_address')
664 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000665 x = self._address_class(int(self.network_address) |
666 int(self.hostmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000667 self._cache['broadcast_address'] = x
668 return x
669
670 @property
671 def hostmask(self):
672 x = self._cache.get('hostmask')
673 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000674 x = self._address_class(int(self.netmask) ^ self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000675 self._cache['hostmask'] = x
676 return x
677
678 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000679 def with_prefixlen(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000680 return '%s/%d' % (self.network_address, self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000681
682 @property
683 def with_netmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000684 return '%s/%s' % (self.network_address, self.netmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000685
686 @property
687 def with_hostmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000688 return '%s/%s' % (self.network_address, self.hostmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000689
690 @property
691 def num_addresses(self):
692 """Number of hosts in the current subnet."""
693 return int(self.broadcast_address) - int(self.network_address) + 1
694
695 @property
Nick Coghlan51c30672012-05-27 00:25:58 +1000696 def _address_class(self):
Nick Coghland9722652012-06-17 16:33:00 +1000697 # Returning bare address objects (rather than interfaces) allows for
698 # more consistent behaviour across the network address, broadcast
699 # address and individual host addresses.
700 msg = '%200s has no associated address class' % (type(self),)
701 raise NotImplementedError(msg)
Nick Coghlan51c30672012-05-27 00:25:58 +1000702
703 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000704 def prefixlen(self):
705 return self._prefixlen
706
707 def address_exclude(self, other):
708 """Remove an address from a larger block.
709
710 For example:
711
712 addr1 = ip_network('192.0.2.0/28')
713 addr2 = ip_network('192.0.2.1/32')
714 addr1.address_exclude(addr2) =
715 [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
716 IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
717
718 or IPv6:
719
720 addr1 = ip_network('2001:db8::1/32')
721 addr2 = ip_network('2001:db8::1/128')
722 addr1.address_exclude(addr2) =
723 [ip_network('2001:db8::1/128'),
724 ip_network('2001:db8::2/127'),
725 ip_network('2001:db8::4/126'),
726 ip_network('2001:db8::8/125'),
727 ...
728 ip_network('2001:db8:8000::/33')]
729
730 Args:
731 other: An IPv4Network or IPv6Network object of the same type.
732
733 Returns:
734 An iterator of the the IPv(4|6)Network objects which is self
735 minus other.
736
737 Raises:
738 TypeError: If self and other are of difffering address
739 versions, or if other is not a network object.
740 ValueError: If other is not completely contained by self.
741
742 """
743 if not self._version == other._version:
744 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000745 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000746
747 if not isinstance(other, _BaseNetwork):
Nick Coghlan912238e2012-07-07 13:34:50 +1000748 raise TypeError("%s is not a network object" % other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000749
750 if not (other.network_address >= self.network_address and
751 other.broadcast_address <= self.broadcast_address):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200752 raise ValueError('%s not contained in %s' % (other, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000753 if other == self:
754 raise StopIteration
755
Nick Coghlandc9b2552012-05-20 21:01:57 +1000756 # Make sure we're comparing the network of other.
Nick Coghlan912238e2012-07-07 13:34:50 +1000757 other = other.__class__('%s/%s' % (other.network_address,
758 other.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000759
760 s1, s2 = self.subnets()
761 while s1 != other and s2 != other:
762 if (other.network_address >= s1.network_address and
763 other.broadcast_address <= s1.broadcast_address):
764 yield s2
765 s1, s2 = s1.subnets()
766 elif (other.network_address >= s2.network_address and
767 other.broadcast_address <= s2.broadcast_address):
768 yield s1
769 s1, s2 = s2.subnets()
770 else:
771 # If we got here, there's a bug somewhere.
772 raise AssertionError('Error performing exclusion: '
773 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000774 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000775 if s1 == other:
776 yield s2
777 elif s2 == other:
778 yield s1
779 else:
780 # If we got here, there's a bug somewhere.
781 raise AssertionError('Error performing exclusion: '
782 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000783 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000784
785 def compare_networks(self, other):
786 """Compare two IP objects.
787
788 This is only concerned about the comparison of the integer
789 representation of the network addresses. This means that the
790 host bits aren't considered at all in this method. If you want
791 to compare host bits, you can easily enough do a
792 'HostA._ip < HostB._ip'
793
794 Args:
795 other: An IP object.
796
797 Returns:
798 If the IP versions of self and other are the same, returns:
799
800 -1 if self < other:
801 eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
802 IPv6Network('2001:db8::1000/124') <
803 IPv6Network('2001:db8::2000/124')
804 0 if self == other
805 eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
806 IPv6Network('2001:db8::1000/124') ==
807 IPv6Network('2001:db8::1000/124')
808 1 if self > other
809 eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
810 IPv6Network('2001:db8::2000/124') >
811 IPv6Network('2001:db8::1000/124')
812
813 Raises:
814 TypeError if the IP versions are different.
815
816 """
817 # does this need to raise a ValueError?
818 if self._version != other._version:
819 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000820 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000821 # self._version == other._version below here:
822 if self.network_address < other.network_address:
823 return -1
824 if self.network_address > other.network_address:
825 return 1
826 # self.network_address == other.network_address below here:
827 if self.netmask < other.netmask:
828 return -1
829 if self.netmask > other.netmask:
830 return 1
831 return 0
832
833 def _get_networks_key(self):
834 """Network-only key function.
835
836 Returns an object that identifies this address' network and
837 netmask. This function is a suitable "key" argument for sorted()
838 and list.sort().
839
840 """
841 return (self._version, self.network_address, self.netmask)
842
843 def subnets(self, prefixlen_diff=1, new_prefix=None):
844 """The subnets which join to make the current subnet.
845
846 In the case that self contains only one IP
847 (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
848 for IPv6), yield an iterator with just ourself.
849
850 Args:
851 prefixlen_diff: An integer, the amount the prefix length
852 should be increased by. This should not be set if
853 new_prefix is also set.
854 new_prefix: The desired new prefix length. This must be a
855 larger number (smaller prefix) than the existing prefix.
856 This should not be set if prefixlen_diff is also set.
857
858 Returns:
859 An iterator of IPv(4|6) objects.
860
861 Raises:
862 ValueError: The prefixlen_diff is too small or too large.
863 OR
864 prefixlen_diff and new_prefix are both set or new_prefix
865 is a smaller number than the current prefix (smaller
866 number means a larger network)
867
868 """
869 if self._prefixlen == self._max_prefixlen:
870 yield self
871 return
872
873 if new_prefix is not None:
874 if new_prefix < self._prefixlen:
875 raise ValueError('new prefix must be longer')
876 if prefixlen_diff != 1:
877 raise ValueError('cannot set prefixlen_diff and new_prefix')
878 prefixlen_diff = new_prefix - self._prefixlen
879
880 if prefixlen_diff < 0:
881 raise ValueError('prefix length diff must be > 0')
882 new_prefixlen = self._prefixlen + prefixlen_diff
883
884 if not self._is_valid_netmask(str(new_prefixlen)):
885 raise ValueError(
886 'prefix length diff %d is invalid for netblock %s' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000887 new_prefixlen, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000888
Nick Coghlan51c30672012-05-27 00:25:58 +1000889 first = self.__class__('%s/%s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000890 (self.network_address,
891 self._prefixlen + prefixlen_diff))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000892
893 yield first
894 current = first
895 while True:
896 broadcast = current.broadcast_address
897 if broadcast == self.broadcast_address:
898 return
Nick Coghlan51c30672012-05-27 00:25:58 +1000899 new_addr = self._address_class(int(broadcast) + 1)
Nick Coghlan912238e2012-07-07 13:34:50 +1000900 current = self.__class__('%s/%s' % (new_addr,
901 new_prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000902
903 yield current
904
Nick Coghlandc9b2552012-05-20 21:01:57 +1000905 def supernet(self, prefixlen_diff=1, new_prefix=None):
906 """The supernet containing the current network.
907
908 Args:
909 prefixlen_diff: An integer, the amount the prefix length of
910 the network should be decreased by. For example, given a
911 /24 network and a prefixlen_diff of 3, a supernet with a
912 /21 netmask is returned.
913
914 Returns:
915 An IPv4 network object.
916
917 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200918 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
919 a negative prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000920 OR
921 If prefixlen_diff and new_prefix are both set or new_prefix is a
922 larger number than the current prefix (larger number means a
923 smaller network)
924
925 """
926 if self._prefixlen == 0:
927 return self
928
929 if new_prefix is not None:
930 if new_prefix > self._prefixlen:
931 raise ValueError('new prefix must be shorter')
932 if prefixlen_diff != 1:
933 raise ValueError('cannot set prefixlen_diff and new_prefix')
934 prefixlen_diff = self._prefixlen - new_prefix
935
Nick Coghlandc9b2552012-05-20 21:01:57 +1000936 if self.prefixlen - prefixlen_diff < 0:
937 raise ValueError(
938 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
939 (self.prefixlen, prefixlen_diff))
940 # TODO (pmoody): optimize this.
Nick Coghlan912238e2012-07-07 13:34:50 +1000941 t = self.__class__('%s/%d' % (self.network_address,
Nick Coghlan51c30672012-05-27 00:25:58 +1000942 self.prefixlen - prefixlen_diff),
943 strict=False)
Nick Coghlan912238e2012-07-07 13:34:50 +1000944 return t.__class__('%s/%d' % (t.network_address, t.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000945
946
Hynek Schlawackc4b78a32012-06-01 11:48:32 +0200947class _BaseV4:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000948
949 """Base IPv4 object.
950
951 The following methods are used by IPv4 objects in both single IP
952 addresses and networks.
953
954 """
955
956 # Equivalent to 255.255.255.255 or 32 bits of 1's.
957 _ALL_ONES = (2**IPV4LENGTH) - 1
958 _DECIMAL_DIGITS = frozenset('0123456789')
959
Hynek Schlawack91c5a342012-06-05 11:55:58 +0200960 # the valid octets for host and netmasks. only useful for IPv4.
Nick Coghlan7319f692012-07-07 21:43:30 +1000961 _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0))
Hynek Schlawack91c5a342012-06-05 11:55:58 +0200962
Nick Coghlandc9b2552012-05-20 21:01:57 +1000963 def __init__(self, address):
964 self._version = 4
965 self._max_prefixlen = IPV4LENGTH
966
967 def _explode_shorthand_ip_string(self):
968 return str(self)
969
970 def _ip_int_from_string(self, ip_str):
971 """Turn the given IP string into an integer for comparison.
972
973 Args:
974 ip_str: A string, the IP ip_str.
975
976 Returns:
977 The IP ip_str as an integer.
978
979 Raises:
980 AddressValueError: if ip_str isn't a valid IPv4 Address.
981
982 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000983 if not ip_str:
984 raise AddressValueError('Address cannot be empty')
985
Nick Coghlandc9b2552012-05-20 21:01:57 +1000986 octets = ip_str.split('.')
987 if len(octets) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000988 raise AddressValueError("Expected 4 octets in %r" % ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000989
Nick Coghlan7319f692012-07-07 21:43:30 +1000990 try:
991 return int.from_bytes(map(self._parse_octet, octets), 'big')
992 except ValueError as exc:
993 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +1000994
995 def _parse_octet(self, octet_str):
996 """Convert a decimal octet into an integer.
997
998 Args:
999 octet_str: A string, the number to parse.
1000
1001 Returns:
1002 The octet as an integer.
1003
1004 Raises:
1005 ValueError: if the octet isn't strictly a decimal from [0..255].
1006
1007 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001008 if not octet_str:
1009 raise ValueError("Empty octet not permitted")
Nick Coghlandc9b2552012-05-20 21:01:57 +10001010 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1011 if not self._DECIMAL_DIGITS.issuperset(octet_str):
Nick Coghlan07c4e332012-07-08 23:06:45 +10001012 msg = "Only decimal digits permitted in %r"
1013 raise ValueError(msg % octet_str)
1014 # We do the length check second, since the invalid character error
1015 # is likely to be more informative for the user
1016 if len(octet_str) > 3:
1017 msg = "At most 3 characters permitted in %r"
1018 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001019 # Convert to integer (we know digits are legal)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001020 octet_int = int(octet_str, 10)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001021 # Any octets that look like they *might* be written in octal,
1022 # and which don't look exactly the same in both octal and
1023 # decimal are rejected as ambiguous
1024 if octet_int > 7 and octet_str[0] == '0':
Nick Coghlan07c4e332012-07-08 23:06:45 +10001025 msg = "Ambiguous (octal/decimal) value in %r not permitted"
1026 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001027 if octet_int > 255:
Nick Coghlanb582ecc2012-07-07 22:15:22 +10001028 raise ValueError("Octet %d (> 255) not permitted" % octet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001029 return octet_int
1030
1031 def _string_from_ip_int(self, ip_int):
1032 """Turns a 32-bit integer into dotted decimal notation.
1033
1034 Args:
1035 ip_int: An integer, the IP address.
1036
1037 Returns:
1038 The IP address as a string in dotted decimal notation.
1039
1040 """
Nick Coghlan7319f692012-07-07 21:43:30 +10001041 return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001042
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001043 def _is_valid_netmask(self, netmask):
1044 """Verify that the netmask is valid.
1045
1046 Args:
1047 netmask: A string, either a prefix or dotted decimal
1048 netmask.
1049
1050 Returns:
1051 A boolean, True if the prefix represents a valid IPv4
1052 netmask.
1053
1054 """
1055 mask = netmask.split('.')
1056 if len(mask) == 4:
Nick Coghlan7319f692012-07-07 21:43:30 +10001057 try:
1058 for x in mask:
1059 if int(x) not in self._valid_mask_octets:
1060 return False
1061 except ValueError:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001062 # Found something that isn't an integer or isn't valid
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001063 return False
Nick Coghlan7319f692012-07-07 21:43:30 +10001064 for idx, y in enumerate(mask):
1065 if idx > 0 and y > mask[idx - 1]:
1066 return False
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001067 return True
1068 try:
1069 netmask = int(netmask)
1070 except ValueError:
1071 return False
1072 return 0 <= netmask <= self._max_prefixlen
1073
1074 def _is_hostmask(self, ip_str):
1075 """Test if the IP string is a hostmask (rather than a netmask).
1076
1077 Args:
1078 ip_str: A string, the potential hostmask.
1079
1080 Returns:
1081 A boolean, True if the IP string is a hostmask.
1082
1083 """
1084 bits = ip_str.split('.')
1085 try:
Nick Coghlan7319f692012-07-07 21:43:30 +10001086 parts = [x for x in map(int, bits) if x in self._valid_mask_octets]
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001087 except ValueError:
1088 return False
1089 if len(parts) != len(bits):
1090 return False
1091 if parts[0] < parts[-1]:
1092 return True
1093 return False
1094
Nick Coghlandc9b2552012-05-20 21:01:57 +10001095 @property
1096 def max_prefixlen(self):
1097 return self._max_prefixlen
1098
1099 @property
1100 def version(self):
1101 return self._version
1102
1103 @property
1104 def is_reserved(self):
1105 """Test if the address is otherwise IETF reserved.
1106
1107 Returns:
1108 A boolean, True if the address is within the
1109 reserved IPv4 Network range.
1110
1111 """
1112 reserved_network = IPv4Network('240.0.0.0/4')
1113 if isinstance(self, _BaseAddress):
1114 return self in reserved_network
1115 return (self.network_address in reserved_network and
1116 self.broadcast_address in reserved_network)
1117
1118 @property
1119 def is_private(self):
1120 """Test if this address is allocated for private networks.
1121
1122 Returns:
1123 A boolean, True if the address is reserved per RFC 1918.
1124
1125 """
1126 private_10 = IPv4Network('10.0.0.0/8')
1127 private_172 = IPv4Network('172.16.0.0/12')
1128 private_192 = IPv4Network('192.168.0.0/16')
1129 if isinstance(self, _BaseAddress):
1130 return (self in private_10 or self in private_172 or
1131 self in private_192)
1132 else:
1133 return ((self.network_address in private_10 and
1134 self.broadcast_address in private_10) or
1135 (self.network_address in private_172 and
1136 self.broadcast_address in private_172) or
1137 (self.network_address in private_192 and
1138 self.broadcast_address in private_192))
1139
1140 @property
1141 def is_multicast(self):
1142 """Test if the address is reserved for multicast use.
1143
1144 Returns:
1145 A boolean, True if the address is multicast.
1146 See RFC 3171 for details.
1147
1148 """
1149 multicast_network = IPv4Network('224.0.0.0/4')
1150 if isinstance(self, _BaseAddress):
1151 return self in IPv4Network('224.0.0.0/4')
1152 return (self.network_address in multicast_network and
1153 self.broadcast_address in multicast_network)
1154
1155 @property
1156 def is_unspecified(self):
1157 """Test if the address is unspecified.
1158
1159 Returns:
1160 A boolean, True if this is the unspecified address as defined in
1161 RFC 5735 3.
1162
1163 """
1164 unspecified_address = IPv4Address('0.0.0.0')
1165 if isinstance(self, _BaseAddress):
Hynek Schlawackbcd30442012-06-04 14:19:39 +02001166 return self == unspecified_address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001167 return (self.network_address == self.broadcast_address ==
1168 unspecified_address)
1169
1170 @property
1171 def is_loopback(self):
1172 """Test if the address is a loopback address.
1173
1174 Returns:
1175 A boolean, True if the address is a loopback per RFC 3330.
1176
1177 """
1178 loopback_address = IPv4Network('127.0.0.0/8')
1179 if isinstance(self, _BaseAddress):
1180 return self in loopback_address
1181
1182 return (self.network_address in loopback_address and
1183 self.broadcast_address in loopback_address)
1184
1185 @property
1186 def is_link_local(self):
1187 """Test if the address is reserved for link-local.
1188
1189 Returns:
1190 A boolean, True if the address is link-local per RFC 3927.
1191
1192 """
1193 linklocal_network = IPv4Network('169.254.0.0/16')
1194 if isinstance(self, _BaseAddress):
1195 return self in linklocal_network
1196 return (self.network_address in linklocal_network and
1197 self.broadcast_address in linklocal_network)
1198
1199
1200class IPv4Address(_BaseV4, _BaseAddress):
1201
1202 """Represent and manipulate single IPv4 Addresses."""
1203
1204 def __init__(self, address):
1205
1206 """
1207 Args:
1208 address: A string or integer representing the IP
1209
1210 Additionally, an integer can be passed, so
1211 IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1212 or, more generally
1213 IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1214 IPv4Address('192.0.2.1')
1215
1216 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001217 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001218
1219 """
1220 _BaseAddress.__init__(self, address)
1221 _BaseV4.__init__(self, address)
1222
1223 # Efficient constructor from integer.
1224 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001225 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001226 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001227 return
1228
1229 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001230 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001231 self._check_packed_address(address, 4)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001232 self._ip = struct.unpack('!I', address)[0]
1233 return
1234
1235 # Assume input argument to be string or any object representation
1236 # which converts into a formatted IP string.
1237 addr_str = str(address)
1238 self._ip = self._ip_int_from_string(addr_str)
1239
1240 @property
1241 def packed(self):
1242 """The binary representation of this address."""
1243 return v4_int_to_packed(self._ip)
1244
1245
1246class IPv4Interface(IPv4Address):
1247
Nick Coghlandc9b2552012-05-20 21:01:57 +10001248 def __init__(self, address):
1249 if isinstance(address, (bytes, int)):
1250 IPv4Address.__init__(self, address)
1251 self.network = IPv4Network(self._ip)
1252 self._prefixlen = self._max_prefixlen
1253 return
1254
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001255 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001256 IPv4Address.__init__(self, addr[0])
1257
1258 self.network = IPv4Network(address, strict=False)
1259 self._prefixlen = self.network._prefixlen
1260
1261 self.netmask = self.network.netmask
1262 self.hostmask = self.network.hostmask
1263
Nick Coghlandc9b2552012-05-20 21:01:57 +10001264 def __str__(self):
1265 return '%s/%d' % (self._string_from_ip_int(self._ip),
1266 self.network.prefixlen)
1267
1268 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001269 address_equal = IPv4Address.__eq__(self, other)
1270 if not address_equal or address_equal is NotImplemented:
1271 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001272 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001273 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001274 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001275 # An interface with an associated network is NOT the
1276 # same as an unassociated address. That's why the hash
1277 # takes the extra info into account.
1278 return False
1279
1280 def __lt__(self, other):
1281 address_less = IPv4Address.__lt__(self, other)
1282 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001283 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001284 try:
1285 return self.network < other.network
1286 except AttributeError:
1287 # We *do* allow addresses and interfaces to be sorted. The
1288 # unassociated address is considered less than all interfaces.
1289 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001290
1291 def __hash__(self):
1292 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1293
Nick Coghlandc9b2552012-05-20 21:01:57 +10001294 @property
1295 def prefixlen(self):
1296 return self._prefixlen
1297
1298 @property
1299 def ip(self):
1300 return IPv4Address(self._ip)
1301
1302 @property
1303 def with_prefixlen(self):
1304 return self
1305
1306 @property
1307 def with_netmask(self):
1308 return '%s/%s' % (self._string_from_ip_int(self._ip),
1309 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001310
Nick Coghlandc9b2552012-05-20 21:01:57 +10001311 @property
1312 def with_hostmask(self):
1313 return '%s/%s' % (self._string_from_ip_int(self._ip),
1314 self.hostmask)
1315
1316
1317class IPv4Network(_BaseV4, _BaseNetwork):
1318
1319 """This class represents and manipulates 32-bit IPv4 network + addresses..
1320
1321 Attributes: [examples for IPv4Network('192.0.2.0/27')]
1322 .network_address: IPv4Address('192.0.2.0')
1323 .hostmask: IPv4Address('0.0.0.31')
1324 .broadcast_address: IPv4Address('192.0.2.32')
1325 .netmask: IPv4Address('255.255.255.224')
1326 .prefixlen: 27
1327
1328 """
Nick Coghlan51c30672012-05-27 00:25:58 +10001329 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001330 _address_class = IPv4Address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001331
Nick Coghlandc9b2552012-05-20 21:01:57 +10001332 def __init__(self, address, strict=True):
1333
1334 """Instantiate a new IPv4 network object.
1335
1336 Args:
1337 address: A string or integer representing the IP [& network].
1338 '192.0.2.0/24'
1339 '192.0.2.0/255.255.255.0'
1340 '192.0.0.2/0.0.0.255'
1341 are all functionally the same in IPv4. Similarly,
1342 '192.0.2.1'
1343 '192.0.2.1/255.255.255.255'
1344 '192.0.2.1/32'
1345 are also functionaly equivalent. That is to say, failing to
1346 provide a subnetmask will create an object with a mask of /32.
1347
1348 If the mask (portion after the / in the argument) is given in
1349 dotted quad form, it is treated as a netmask if it starts with a
1350 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1351 starts with a zero field (e.g. 0.255.255.255 == /8), with the
1352 single exception of an all-zero mask which is treated as a
1353 netmask == /0. If no mask is given, a default of /32 is used.
1354
1355 Additionally, an integer can be passed, so
1356 IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1357 or, more generally
1358 IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1359 IPv4Interface('192.0.2.1')
1360
1361 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001362 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001363 NetmaskValueError: If the netmask isn't valid for
1364 an IPv4 address.
Sandro Tosib4386d32012-06-02 17:14:22 +02001365 ValueError: If strict is True and a network address is not
Nick Coghlandc9b2552012-05-20 21:01:57 +10001366 supplied.
1367
1368 """
1369
1370 _BaseV4.__init__(self, address)
1371 _BaseNetwork.__init__(self, address)
1372
1373 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001374 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001375 self.network_address = IPv4Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001376 self._prefixlen = self._max_prefixlen
1377 self.netmask = IPv4Address(self._ALL_ONES)
1378 #fixme: address/network test here
1379 return
1380
1381 # Efficient constructor from integer.
1382 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001383 self.network_address = IPv4Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001384 self._prefixlen = self._max_prefixlen
1385 self.netmask = IPv4Address(self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001386 #fixme: address/network test here.
1387 return
1388
1389 # Assume input argument to be string or any object representation
1390 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001391 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001392 self.network_address = IPv4Address(self._ip_int_from_string(addr[0]))
1393
Nick Coghlandc9b2552012-05-20 21:01:57 +10001394 if len(addr) == 2:
1395 mask = addr[1].split('.')
1396
1397 if len(mask) == 4:
1398 # We have dotted decimal netmask.
1399 if self._is_valid_netmask(addr[1]):
1400 self.netmask = IPv4Address(self._ip_int_from_string(
1401 addr[1]))
1402 elif self._is_hostmask(addr[1]):
1403 self.netmask = IPv4Address(
1404 self._ip_int_from_string(addr[1]) ^ self._ALL_ONES)
1405 else:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001406 raise NetmaskValueError('%r is not a valid netmask'
Nick Coghlandc9b2552012-05-20 21:01:57 +10001407 % addr[1])
1408
1409 self._prefixlen = self._prefix_from_ip_int(int(self.netmask))
1410 else:
1411 # We have a netmask in prefix length form.
1412 if not self._is_valid_netmask(addr[1]):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001413 raise NetmaskValueError('%r is not a valid netmask'
1414 % addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001415 self._prefixlen = int(addr[1])
1416 self.netmask = IPv4Address(self._ip_int_from_prefix(
1417 self._prefixlen))
1418 else:
1419 self._prefixlen = self._max_prefixlen
1420 self.netmask = IPv4Address(self._ip_int_from_prefix(
1421 self._prefixlen))
1422
1423 if strict:
1424 if (IPv4Address(int(self.network_address) & int(self.netmask)) !=
1425 self.network_address):
1426 raise ValueError('%s has host bits set' % self)
1427 self.network_address = IPv4Address(int(self.network_address) &
1428 int(self.netmask))
1429
1430 if self._prefixlen == (self._max_prefixlen - 1):
1431 self.hosts = self.__iter__
1432
Nick Coghlandc9b2552012-05-20 21:01:57 +10001433
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001434class _BaseV6:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001435
1436 """Base IPv6 object.
1437
1438 The following methods are used by IPv6 objects in both single IP
1439 addresses and networks.
1440
1441 """
1442
1443 _ALL_ONES = (2**IPV6LENGTH) - 1
1444 _HEXTET_COUNT = 8
1445 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
1446
1447 def __init__(self, address):
1448 self._version = 6
1449 self._max_prefixlen = IPV6LENGTH
1450
1451 def _ip_int_from_string(self, ip_str):
1452 """Turn an IPv6 ip_str into an integer.
1453
1454 Args:
1455 ip_str: A string, the IPv6 ip_str.
1456
1457 Returns:
1458 An int, the IPv6 address
1459
1460 Raises:
1461 AddressValueError: if ip_str isn't a valid IPv6 Address.
1462
1463 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001464 if not ip_str:
1465 raise AddressValueError('Address cannot be empty')
1466
Nick Coghlandc9b2552012-05-20 21:01:57 +10001467 parts = ip_str.split(':')
1468
1469 # An IPv6 address needs at least 2 colons (3 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001470 _min_parts = 3
1471 if len(parts) < _min_parts:
1472 msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
1473 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001474
1475 # If the address has an IPv4-style suffix, convert it to hexadecimal.
1476 if '.' in parts[-1]:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001477 try:
1478 ipv4_int = IPv4Address(parts.pop())._ip
1479 except AddressValueError as exc:
1480 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001481 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1482 parts.append('%x' % (ipv4_int & 0xFFFF))
1483
1484 # An IPv6 address can't have more than 8 colons (9 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001485 # The extra colon comes from using the "::" notation for a single
1486 # leading or trailing zero part.
1487 _max_parts = self._HEXTET_COUNT + 1
1488 if len(parts) > _max_parts:
1489 msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
1490 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001491
1492 # Disregarding the endpoints, find '::' with nothing in between.
1493 # This indicates that a run of zeroes has been skipped.
Nick Coghlan7319f692012-07-07 21:43:30 +10001494 skip_index = None
1495 for i in range(1, len(parts) - 1):
1496 if not parts[i]:
1497 if skip_index is not None:
1498 # Can't have more than one '::'
1499 msg = "At most one '::' permitted in %r" % ip_str
1500 raise AddressValueError(msg)
1501 skip_index = i
Nick Coghlandc9b2552012-05-20 21:01:57 +10001502
1503 # parts_hi is the number of parts to copy from above/before the '::'
1504 # parts_lo is the number of parts to copy from below/after the '::'
1505 if skip_index is not None:
1506 # If we found a '::', then check if it also covers the endpoints.
1507 parts_hi = skip_index
1508 parts_lo = len(parts) - skip_index - 1
1509 if not parts[0]:
1510 parts_hi -= 1
1511 if parts_hi:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001512 msg = "Leading ':' only permitted as part of '::' in %r"
1513 raise AddressValueError(msg % ip_str) # ^: requires ^::
Nick Coghlandc9b2552012-05-20 21:01:57 +10001514 if not parts[-1]:
1515 parts_lo -= 1
1516 if parts_lo:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001517 msg = "Trailing ':' only permitted as part of '::' in %r"
1518 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001519 parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo)
1520 if parts_skipped < 1:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001521 msg = "Expected at most %d other parts with '::' in %r"
1522 raise AddressValueError(msg % (self._HEXTET_COUNT-1, ip_str))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001523 else:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001524 # Otherwise, allocate the entire address to parts_hi. The
1525 # endpoints could still be empty, but _parse_hextet() will check
1526 # for that.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001527 if len(parts) != self._HEXTET_COUNT:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001528 msg = "Exactly %d parts expected without '::' in %r"
1529 raise AddressValueError(msg % (self._HEXTET_COUNT, ip_str))
1530 if not parts[0]:
1531 msg = "Leading ':' only permitted as part of '::' in %r"
1532 raise AddressValueError(msg % ip_str) # ^: requires ^::
1533 if not parts[-1]:
1534 msg = "Trailing ':' only permitted as part of '::' in %r"
1535 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001536 parts_hi = len(parts)
1537 parts_lo = 0
1538 parts_skipped = 0
1539
1540 try:
1541 # Now, parse the hextets into a 128-bit integer.
1542 ip_int = 0
1543 for i in range(parts_hi):
1544 ip_int <<= 16
1545 ip_int |= self._parse_hextet(parts[i])
1546 ip_int <<= 16 * parts_skipped
1547 for i in range(-parts_lo, 0):
1548 ip_int <<= 16
1549 ip_int |= self._parse_hextet(parts[i])
1550 return ip_int
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001551 except ValueError as exc:
1552 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001553
1554 def _parse_hextet(self, hextet_str):
1555 """Convert an IPv6 hextet string into an integer.
1556
1557 Args:
1558 hextet_str: A string, the number to parse.
1559
1560 Returns:
1561 The hextet as an integer.
1562
1563 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001564 ValueError: if the input isn't strictly a hex number from
1565 [0..FFFF].
Nick Coghlandc9b2552012-05-20 21:01:57 +10001566
1567 """
1568 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1569 if not self._HEX_DIGITS.issuperset(hextet_str):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001570 raise ValueError("Only hex digits permitted in %r" % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001571 # We do the length check second, since the invalid character error
1572 # is likely to be more informative for the user
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001573 if len(hextet_str) > 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001574 msg = "At most 4 characters permitted in %r"
1575 raise ValueError(msg % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001576 # Length check means we can skip checking the integer value
1577 return int(hextet_str, 16)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001578
1579 def _compress_hextets(self, hextets):
1580 """Compresses a list of hextets.
1581
1582 Compresses a list of strings, replacing the longest continuous
1583 sequence of "0" in the list with "" and adding empty strings at
1584 the beginning or at the end of the string such that subsequently
1585 calling ":".join(hextets) will produce the compressed version of
1586 the IPv6 address.
1587
1588 Args:
1589 hextets: A list of strings, the hextets to compress.
1590
1591 Returns:
1592 A list of strings.
1593
1594 """
1595 best_doublecolon_start = -1
1596 best_doublecolon_len = 0
1597 doublecolon_start = -1
1598 doublecolon_len = 0
1599 for index in range(len(hextets)):
1600 if hextets[index] == '0':
1601 doublecolon_len += 1
1602 if doublecolon_start == -1:
1603 # Start of a sequence of zeros.
1604 doublecolon_start = index
1605 if doublecolon_len > best_doublecolon_len:
1606 # This is the longest sequence of zeros so far.
1607 best_doublecolon_len = doublecolon_len
1608 best_doublecolon_start = doublecolon_start
1609 else:
1610 doublecolon_len = 0
1611 doublecolon_start = -1
1612
1613 if best_doublecolon_len > 1:
1614 best_doublecolon_end = (best_doublecolon_start +
1615 best_doublecolon_len)
1616 # For zeros at the end of the address.
1617 if best_doublecolon_end == len(hextets):
1618 hextets += ['']
1619 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1620 # For zeros at the beginning of the address.
1621 if best_doublecolon_start == 0:
1622 hextets = [''] + hextets
1623
1624 return hextets
1625
1626 def _string_from_ip_int(self, ip_int=None):
1627 """Turns a 128-bit integer into hexadecimal notation.
1628
1629 Args:
1630 ip_int: An integer, the IP address.
1631
1632 Returns:
1633 A string, the hexadecimal representation of the address.
1634
1635 Raises:
1636 ValueError: The address is bigger than 128 bits of all ones.
1637
1638 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001639 if ip_int is None:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001640 ip_int = int(self._ip)
1641
1642 if ip_int > self._ALL_ONES:
1643 raise ValueError('IPv6 address is too large')
1644
1645 hex_str = '%032x' % ip_int
Nick Coghlan7319f692012-07-07 21:43:30 +10001646 hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001647
1648 hextets = self._compress_hextets(hextets)
1649 return ':'.join(hextets)
1650
1651 def _explode_shorthand_ip_string(self):
1652 """Expand a shortened IPv6 address.
1653
1654 Args:
1655 ip_str: A string, the IPv6 address.
1656
1657 Returns:
1658 A string, the expanded IPv6 address.
1659
1660 """
1661 if isinstance(self, IPv6Network):
1662 ip_str = str(self.network_address)
1663 elif isinstance(self, IPv6Interface):
1664 ip_str = str(self.ip)
1665 else:
1666 ip_str = str(self)
1667
1668 ip_int = self._ip_int_from_string(ip_str)
Nick Coghlan7319f692012-07-07 21:43:30 +10001669 hex_str = '%032x' % ip_int
1670 parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001671 if isinstance(self, (_BaseNetwork, IPv6Interface)):
1672 return '%s/%d' % (':'.join(parts), self.prefixlen)
1673 return ':'.join(parts)
1674
1675 @property
1676 def max_prefixlen(self):
1677 return self._max_prefixlen
1678
1679 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001680 def version(self):
1681 return self._version
1682
1683 @property
1684 def is_multicast(self):
1685 """Test if the address is reserved for multicast use.
1686
1687 Returns:
1688 A boolean, True if the address is a multicast address.
1689 See RFC 2373 2.7 for details.
1690
1691 """
1692 multicast_network = IPv6Network('ff00::/8')
1693 if isinstance(self, _BaseAddress):
1694 return self in multicast_network
1695 return (self.network_address in multicast_network and
1696 self.broadcast_address in multicast_network)
1697
1698 @property
1699 def is_reserved(self):
1700 """Test if the address is otherwise IETF reserved.
1701
1702 Returns:
1703 A boolean, True if the address is within one of the
1704 reserved IPv6 Network ranges.
1705
1706 """
1707 reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'),
1708 IPv6Network('200::/7'), IPv6Network('400::/6'),
1709 IPv6Network('800::/5'), IPv6Network('1000::/4'),
1710 IPv6Network('4000::/3'), IPv6Network('6000::/3'),
1711 IPv6Network('8000::/3'), IPv6Network('A000::/3'),
1712 IPv6Network('C000::/3'), IPv6Network('E000::/4'),
1713 IPv6Network('F000::/5'), IPv6Network('F800::/6'),
1714 IPv6Network('FE00::/9')]
1715
1716 if isinstance(self, _BaseAddress):
Nick Coghlan7319f692012-07-07 21:43:30 +10001717 return any(self in x for x in reserved_networks)
1718 return any(self.network_address in x and self.broadcast_address in x
1719 for x in reserved_networks)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001720
1721 @property
1722 def is_link_local(self):
1723 """Test if the address is reserved for link-local.
1724
1725 Returns:
1726 A boolean, True if the address is reserved per RFC 4291.
1727
1728 """
1729 linklocal_network = IPv6Network('fe80::/10')
1730 if isinstance(self, _BaseAddress):
1731 return self in linklocal_network
1732 return (self.network_address in linklocal_network and
1733 self.broadcast_address in linklocal_network)
1734
1735 @property
1736 def is_site_local(self):
1737 """Test if the address is reserved for site-local.
1738
1739 Note that the site-local address space has been deprecated by RFC 3879.
1740 Use is_private to test if this address is in the space of unique local
1741 addresses as defined by RFC 4193.
1742
1743 Returns:
1744 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1745
1746 """
1747 sitelocal_network = IPv6Network('fec0::/10')
1748 if isinstance(self, _BaseAddress):
1749 return self in sitelocal_network
1750 return (self.network_address in sitelocal_network and
1751 self.broadcast_address in sitelocal_network)
1752
1753 @property
1754 def is_private(self):
1755 """Test if this address is allocated for private networks.
1756
1757 Returns:
1758 A boolean, True if the address is reserved per RFC 4193.
1759
1760 """
1761 private_network = IPv6Network('fc00::/7')
1762 if isinstance(self, _BaseAddress):
1763 return self in private_network
1764 return (self.network_address in private_network and
1765 self.broadcast_address in private_network)
1766
Nick Coghlandc9b2552012-05-20 21:01:57 +10001767 @property
1768 def ipv4_mapped(self):
1769 """Return the IPv4 mapped address.
1770
1771 Returns:
1772 If the IPv6 address is a v4 mapped address, return the
1773 IPv4 mapped address. Return None otherwise.
1774
1775 """
1776 if (self._ip >> 32) != 0xFFFF:
1777 return None
1778 return IPv4Address(self._ip & 0xFFFFFFFF)
1779
1780 @property
1781 def teredo(self):
1782 """Tuple of embedded teredo IPs.
1783
1784 Returns:
1785 Tuple of the (server, client) IPs or None if the address
1786 doesn't appear to be a teredo address (doesn't start with
1787 2001::/32)
1788
1789 """
1790 if (self._ip >> 96) != 0x20010000:
1791 return None
1792 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
1793 IPv4Address(~self._ip & 0xFFFFFFFF))
1794
1795 @property
1796 def sixtofour(self):
1797 """Return the IPv4 6to4 embedded address.
1798
1799 Returns:
1800 The IPv4 6to4-embedded address if present or None if the
1801 address doesn't appear to contain a 6to4 embedded address.
1802
1803 """
1804 if (self._ip >> 112) != 0x2002:
1805 return None
1806 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
1807
1808 @property
1809 def is_unspecified(self):
1810 """Test if the address is unspecified.
1811
1812 Returns:
1813 A boolean, True if this is the unspecified address as defined in
1814 RFC 2373 2.5.2.
1815
1816 """
1817 if isinstance(self, (IPv6Network, IPv6Interface)):
1818 return int(self.network_address) == 0 and getattr(
1819 self, '_prefixlen', 128) == 128
1820 return self._ip == 0
1821
1822 @property
1823 def is_loopback(self):
1824 """Test if the address is a loopback address.
1825
1826 Returns:
1827 A boolean, True if the address is a loopback address as defined in
1828 RFC 2373 2.5.3.
1829
1830 """
1831 if isinstance(self, IPv6Network):
Nick Coghlan2c589102012-05-27 01:03:25 +10001832 return int(self) == 1 and getattr(
Nick Coghlandc9b2552012-05-20 21:01:57 +10001833 self, '_prefixlen', 128) == 128
1834 elif isinstance(self, IPv6Interface):
1835 return int(self.network.network_address) == 1 and getattr(
1836 self, '_prefixlen', 128) == 128
1837 return self._ip == 1
1838
1839
1840class IPv6Address(_BaseV6, _BaseAddress):
1841
Sandro Tosib95c6342012-05-23 23:17:22 +02001842 """Represent and manipulate single IPv6 Addresses."""
Nick Coghlandc9b2552012-05-20 21:01:57 +10001843
1844 def __init__(self, address):
1845 """Instantiate a new IPv6 address object.
1846
1847 Args:
1848 address: A string or integer representing the IP
1849
1850 Additionally, an integer can be passed, so
1851 IPv6Address('2001:db8::') ==
1852 IPv6Address(42540766411282592856903984951653826560)
1853 or, more generally
1854 IPv6Address(int(IPv6Address('2001:db8::'))) ==
1855 IPv6Address('2001:db8::')
1856
1857 Raises:
1858 AddressValueError: If address isn't a valid IPv6 address.
1859
1860 """
1861 _BaseAddress.__init__(self, address)
1862 _BaseV6.__init__(self, address)
1863
1864 # Efficient constructor from integer.
1865 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001866 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001867 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001868 return
1869
1870 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001871 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001872 self._check_packed_address(address, 16)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001873 tmp = struct.unpack('!QQ', address)
1874 self._ip = (tmp[0] << 64) | tmp[1]
1875 return
1876
1877 # Assume input argument to be string or any object representation
1878 # which converts into a formatted IP string.
1879 addr_str = str(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001880 self._ip = self._ip_int_from_string(addr_str)
1881
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001882 @property
1883 def packed(self):
1884 """The binary representation of this address."""
1885 return v6_int_to_packed(self._ip)
1886
Nick Coghlandc9b2552012-05-20 21:01:57 +10001887
1888class IPv6Interface(IPv6Address):
1889
1890 def __init__(self, address):
1891 if isinstance(address, (bytes, int)):
1892 IPv6Address.__init__(self, address)
1893 self.network = IPv6Network(self._ip)
1894 self._prefixlen = self._max_prefixlen
1895 return
1896
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001897 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001898 IPv6Address.__init__(self, addr[0])
1899 self.network = IPv6Network(address, strict=False)
1900 self.netmask = self.network.netmask
1901 self._prefixlen = self.network._prefixlen
1902 self.hostmask = self.network.hostmask
1903
Nick Coghlandc9b2552012-05-20 21:01:57 +10001904 def __str__(self):
1905 return '%s/%d' % (self._string_from_ip_int(self._ip),
1906 self.network.prefixlen)
1907
1908 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001909 address_equal = IPv6Address.__eq__(self, other)
1910 if not address_equal or address_equal is NotImplemented:
1911 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001912 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001913 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001914 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001915 # An interface with an associated network is NOT the
1916 # same as an unassociated address. That's why the hash
1917 # takes the extra info into account.
1918 return False
1919
1920 def __lt__(self, other):
1921 address_less = IPv6Address.__lt__(self, other)
1922 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001923 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001924 try:
1925 return self.network < other.network
1926 except AttributeError:
1927 # We *do* allow addresses and interfaces to be sorted. The
1928 # unassociated address is considered less than all interfaces.
1929 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001930
1931 def __hash__(self):
1932 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1933
1934 @property
1935 def prefixlen(self):
1936 return self._prefixlen
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001937
Nick Coghlandc9b2552012-05-20 21:01:57 +10001938 @property
1939 def ip(self):
1940 return IPv6Address(self._ip)
1941
1942 @property
1943 def with_prefixlen(self):
1944 return self
1945
1946 @property
1947 def with_netmask(self):
1948 return self.with_prefixlen
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001949
Nick Coghlandc9b2552012-05-20 21:01:57 +10001950 @property
1951 def with_hostmask(self):
1952 return '%s/%s' % (self._string_from_ip_int(self._ip),
1953 self.hostmask)
1954
1955
1956class IPv6Network(_BaseV6, _BaseNetwork):
1957
1958 """This class represents and manipulates 128-bit IPv6 networks.
1959
1960 Attributes: [examples for IPv6('2001:db8::1000/124')]
1961 .network_address: IPv6Address('2001:db8::1000')
1962 .hostmask: IPv6Address('::f')
1963 .broadcast_address: IPv6Address('2001:db8::100f')
1964 .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
1965 .prefixlen: 124
1966
1967 """
1968
Nick Coghlan51c30672012-05-27 00:25:58 +10001969 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001970 _address_class = IPv6Address
1971
Nick Coghlandc9b2552012-05-20 21:01:57 +10001972 def __init__(self, address, strict=True):
1973 """Instantiate a new IPv6 Network object.
1974
1975 Args:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001976 address: A string or integer representing the IPv6 network or the
1977 IP and prefix/netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001978 '2001:db8::/128'
1979 '2001:db8:0000:0000:0000:0000:0000:0000/128'
1980 '2001:db8::'
1981 are all functionally the same in IPv6. That is to say,
1982 failing to provide a subnetmask will create an object with
1983 a mask of /128.
1984
1985 Additionally, an integer can be passed, so
1986 IPv6Network('2001:db8::') ==
1987 IPv6Network(42540766411282592856903984951653826560)
1988 or, more generally
1989 IPv6Network(int(IPv6Network('2001:db8::'))) ==
1990 IPv6Network('2001:db8::')
1991
1992 strict: A boolean. If true, ensure that we have been passed
1993 A true network address, eg, 2001:db8::1000/124 and not an
1994 IP address on a network, eg, 2001:db8::1/124.
1995
1996 Raises:
1997 AddressValueError: If address isn't a valid IPv6 address.
1998 NetmaskValueError: If the netmask isn't valid for
1999 an IPv6 address.
2000 ValueError: If strict was True and a network address was not
2001 supplied.
2002
2003 """
2004 _BaseV6.__init__(self, address)
2005 _BaseNetwork.__init__(self, address)
2006
2007 # Efficient constructor from integer.
2008 if isinstance(address, int):
Nick Coghlandc9b2552012-05-20 21:01:57 +10002009 self.network_address = IPv6Address(address)
2010 self._prefixlen = self._max_prefixlen
2011 self.netmask = IPv6Address(self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002012 return
2013
2014 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10002015 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10002016 self.network_address = IPv6Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002017 self._prefixlen = self._max_prefixlen
2018 self.netmask = IPv6Address(self._ALL_ONES)
Hynek Schlawacked36b2e2012-06-08 15:21:21 +02002019 return
Nick Coghlandc9b2552012-05-20 21:01:57 +10002020
2021 # Assume input argument to be string or any object representation
2022 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002023 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002024
2025 self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))
2026
2027 if len(addr) == 2:
2028 if self._is_valid_netmask(addr[1]):
2029 self._prefixlen = int(addr[1])
2030 else:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002031 raise NetmaskValueError('%r is not a valid netmask'
2032 % addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10002033 else:
2034 self._prefixlen = self._max_prefixlen
2035
2036 self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen))
2037 if strict:
2038 if (IPv6Address(int(self.network_address) & int(self.netmask)) !=
2039 self.network_address):
Nick Coghlan912238e2012-07-07 13:34:50 +10002040 raise ValueError('%s has host bits set' % self)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002041 self.network_address = IPv6Address(int(self.network_address) &
2042 int(self.netmask))
2043
2044 if self._prefixlen == (self._max_prefixlen - 1):
2045 self.hosts = self.__iter__
2046
Nick Coghlandc9b2552012-05-20 21:01:57 +10002047 def _is_valid_netmask(self, prefixlen):
2048 """Verify that the netmask/prefixlen is valid.
2049
2050 Args:
2051 prefixlen: A string, the netmask in prefix length format.
2052
2053 Returns:
2054 A boolean, True if the prefix represents a valid IPv6
2055 netmask.
2056
2057 """
2058 try:
2059 prefixlen = int(prefixlen)
2060 except ValueError:
2061 return False
2062 return 0 <= prefixlen <= self._max_prefixlen