blob: 7e6f03f0a2c417c390ac737314386aa2031f33e5 [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 Coghlan36f8dcd2012-07-07 19:23:53 +10001012 raise ValueError("Only decimal digits permitted in %r" % octet_str)
1013 # 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':
1019 raise ValueError("Ambiguous leading zero in %r not permitted" %
1020 octet_str)
1021 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.
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001563 # Higher level wrappers convert these to more informative errors
Nick Coghlandc9b2552012-05-20 21:01:57 +10001564 if not self._HEX_DIGITS.issuperset(hextet_str):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001565 raise ValueError("Only hex digits permitted in %r" % hextet_str)
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001566 if len(hextet_str) > 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001567 msg = "At most 4 characters permitted in %r"
1568 raise ValueError(msg % hextet_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001569 hextet_int = int(hextet_str, 16)
1570 if hextet_int > 0xFFFF:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001571 # This is unreachable due to the string length check above
Nick Coghlanb582ecc2012-07-07 22:15:22 +10001572 msg = "Part 0x%X (> 0xFFFF) not permitted"
1573 raise ValueError(msg % hextet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001574 return hextet_int
1575
1576 def _compress_hextets(self, hextets):
1577 """Compresses a list of hextets.
1578
1579 Compresses a list of strings, replacing the longest continuous
1580 sequence of "0" in the list with "" and adding empty strings at
1581 the beginning or at the end of the string such that subsequently
1582 calling ":".join(hextets) will produce the compressed version of
1583 the IPv6 address.
1584
1585 Args:
1586 hextets: A list of strings, the hextets to compress.
1587
1588 Returns:
1589 A list of strings.
1590
1591 """
1592 best_doublecolon_start = -1
1593 best_doublecolon_len = 0
1594 doublecolon_start = -1
1595 doublecolon_len = 0
1596 for index in range(len(hextets)):
1597 if hextets[index] == '0':
1598 doublecolon_len += 1
1599 if doublecolon_start == -1:
1600 # Start of a sequence of zeros.
1601 doublecolon_start = index
1602 if doublecolon_len > best_doublecolon_len:
1603 # This is the longest sequence of zeros so far.
1604 best_doublecolon_len = doublecolon_len
1605 best_doublecolon_start = doublecolon_start
1606 else:
1607 doublecolon_len = 0
1608 doublecolon_start = -1
1609
1610 if best_doublecolon_len > 1:
1611 best_doublecolon_end = (best_doublecolon_start +
1612 best_doublecolon_len)
1613 # For zeros at the end of the address.
1614 if best_doublecolon_end == len(hextets):
1615 hextets += ['']
1616 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1617 # For zeros at the beginning of the address.
1618 if best_doublecolon_start == 0:
1619 hextets = [''] + hextets
1620
1621 return hextets
1622
1623 def _string_from_ip_int(self, ip_int=None):
1624 """Turns a 128-bit integer into hexadecimal notation.
1625
1626 Args:
1627 ip_int: An integer, the IP address.
1628
1629 Returns:
1630 A string, the hexadecimal representation of the address.
1631
1632 Raises:
1633 ValueError: The address is bigger than 128 bits of all ones.
1634
1635 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001636 if ip_int is None:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001637 ip_int = int(self._ip)
1638
1639 if ip_int > self._ALL_ONES:
1640 raise ValueError('IPv6 address is too large')
1641
1642 hex_str = '%032x' % ip_int
Nick Coghlan7319f692012-07-07 21:43:30 +10001643 hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001644
1645 hextets = self._compress_hextets(hextets)
1646 return ':'.join(hextets)
1647
1648 def _explode_shorthand_ip_string(self):
1649 """Expand a shortened IPv6 address.
1650
1651 Args:
1652 ip_str: A string, the IPv6 address.
1653
1654 Returns:
1655 A string, the expanded IPv6 address.
1656
1657 """
1658 if isinstance(self, IPv6Network):
1659 ip_str = str(self.network_address)
1660 elif isinstance(self, IPv6Interface):
1661 ip_str = str(self.ip)
1662 else:
1663 ip_str = str(self)
1664
1665 ip_int = self._ip_int_from_string(ip_str)
Nick Coghlan7319f692012-07-07 21:43:30 +10001666 hex_str = '%032x' % ip_int
1667 parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001668 if isinstance(self, (_BaseNetwork, IPv6Interface)):
1669 return '%s/%d' % (':'.join(parts), self.prefixlen)
1670 return ':'.join(parts)
1671
1672 @property
1673 def max_prefixlen(self):
1674 return self._max_prefixlen
1675
1676 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001677 def version(self):
1678 return self._version
1679
1680 @property
1681 def is_multicast(self):
1682 """Test if the address is reserved for multicast use.
1683
1684 Returns:
1685 A boolean, True if the address is a multicast address.
1686 See RFC 2373 2.7 for details.
1687
1688 """
1689 multicast_network = IPv6Network('ff00::/8')
1690 if isinstance(self, _BaseAddress):
1691 return self in multicast_network
1692 return (self.network_address in multicast_network and
1693 self.broadcast_address in multicast_network)
1694
1695 @property
1696 def is_reserved(self):
1697 """Test if the address is otherwise IETF reserved.
1698
1699 Returns:
1700 A boolean, True if the address is within one of the
1701 reserved IPv6 Network ranges.
1702
1703 """
1704 reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'),
1705 IPv6Network('200::/7'), IPv6Network('400::/6'),
1706 IPv6Network('800::/5'), IPv6Network('1000::/4'),
1707 IPv6Network('4000::/3'), IPv6Network('6000::/3'),
1708 IPv6Network('8000::/3'), IPv6Network('A000::/3'),
1709 IPv6Network('C000::/3'), IPv6Network('E000::/4'),
1710 IPv6Network('F000::/5'), IPv6Network('F800::/6'),
1711 IPv6Network('FE00::/9')]
1712
1713 if isinstance(self, _BaseAddress):
Nick Coghlan7319f692012-07-07 21:43:30 +10001714 return any(self in x for x in reserved_networks)
1715 return any(self.network_address in x and self.broadcast_address in x
1716 for x in reserved_networks)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001717
1718 @property
1719 def is_link_local(self):
1720 """Test if the address is reserved for link-local.
1721
1722 Returns:
1723 A boolean, True if the address is reserved per RFC 4291.
1724
1725 """
1726 linklocal_network = IPv6Network('fe80::/10')
1727 if isinstance(self, _BaseAddress):
1728 return self in linklocal_network
1729 return (self.network_address in linklocal_network and
1730 self.broadcast_address in linklocal_network)
1731
1732 @property
1733 def is_site_local(self):
1734 """Test if the address is reserved for site-local.
1735
1736 Note that the site-local address space has been deprecated by RFC 3879.
1737 Use is_private to test if this address is in the space of unique local
1738 addresses as defined by RFC 4193.
1739
1740 Returns:
1741 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1742
1743 """
1744 sitelocal_network = IPv6Network('fec0::/10')
1745 if isinstance(self, _BaseAddress):
1746 return self in sitelocal_network
1747 return (self.network_address in sitelocal_network and
1748 self.broadcast_address in sitelocal_network)
1749
1750 @property
1751 def is_private(self):
1752 """Test if this address is allocated for private networks.
1753
1754 Returns:
1755 A boolean, True if the address is reserved per RFC 4193.
1756
1757 """
1758 private_network = IPv6Network('fc00::/7')
1759 if isinstance(self, _BaseAddress):
1760 return self in private_network
1761 return (self.network_address in private_network and
1762 self.broadcast_address in private_network)
1763
Nick Coghlandc9b2552012-05-20 21:01:57 +10001764 @property
1765 def ipv4_mapped(self):
1766 """Return the IPv4 mapped address.
1767
1768 Returns:
1769 If the IPv6 address is a v4 mapped address, return the
1770 IPv4 mapped address. Return None otherwise.
1771
1772 """
1773 if (self._ip >> 32) != 0xFFFF:
1774 return None
1775 return IPv4Address(self._ip & 0xFFFFFFFF)
1776
1777 @property
1778 def teredo(self):
1779 """Tuple of embedded teredo IPs.
1780
1781 Returns:
1782 Tuple of the (server, client) IPs or None if the address
1783 doesn't appear to be a teredo address (doesn't start with
1784 2001::/32)
1785
1786 """
1787 if (self._ip >> 96) != 0x20010000:
1788 return None
1789 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
1790 IPv4Address(~self._ip & 0xFFFFFFFF))
1791
1792 @property
1793 def sixtofour(self):
1794 """Return the IPv4 6to4 embedded address.
1795
1796 Returns:
1797 The IPv4 6to4-embedded address if present or None if the
1798 address doesn't appear to contain a 6to4 embedded address.
1799
1800 """
1801 if (self._ip >> 112) != 0x2002:
1802 return None
1803 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
1804
1805 @property
1806 def is_unspecified(self):
1807 """Test if the address is unspecified.
1808
1809 Returns:
1810 A boolean, True if this is the unspecified address as defined in
1811 RFC 2373 2.5.2.
1812
1813 """
1814 if isinstance(self, (IPv6Network, IPv6Interface)):
1815 return int(self.network_address) == 0 and getattr(
1816 self, '_prefixlen', 128) == 128
1817 return self._ip == 0
1818
1819 @property
1820 def is_loopback(self):
1821 """Test if the address is a loopback address.
1822
1823 Returns:
1824 A boolean, True if the address is a loopback address as defined in
1825 RFC 2373 2.5.3.
1826
1827 """
1828 if isinstance(self, IPv6Network):
Nick Coghlan2c589102012-05-27 01:03:25 +10001829 return int(self) == 1 and getattr(
Nick Coghlandc9b2552012-05-20 21:01:57 +10001830 self, '_prefixlen', 128) == 128
1831 elif isinstance(self, IPv6Interface):
1832 return int(self.network.network_address) == 1 and getattr(
1833 self, '_prefixlen', 128) == 128
1834 return self._ip == 1
1835
1836
1837class IPv6Address(_BaseV6, _BaseAddress):
1838
Sandro Tosib95c6342012-05-23 23:17:22 +02001839 """Represent and manipulate single IPv6 Addresses."""
Nick Coghlandc9b2552012-05-20 21:01:57 +10001840
1841 def __init__(self, address):
1842 """Instantiate a new IPv6 address object.
1843
1844 Args:
1845 address: A string or integer representing the IP
1846
1847 Additionally, an integer can be passed, so
1848 IPv6Address('2001:db8::') ==
1849 IPv6Address(42540766411282592856903984951653826560)
1850 or, more generally
1851 IPv6Address(int(IPv6Address('2001:db8::'))) ==
1852 IPv6Address('2001:db8::')
1853
1854 Raises:
1855 AddressValueError: If address isn't a valid IPv6 address.
1856
1857 """
1858 _BaseAddress.__init__(self, address)
1859 _BaseV6.__init__(self, address)
1860
1861 # Efficient constructor from integer.
1862 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001863 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001864 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001865 return
1866
1867 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001868 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001869 self._check_packed_address(address, 16)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001870 tmp = struct.unpack('!QQ', address)
1871 self._ip = (tmp[0] << 64) | tmp[1]
1872 return
1873
1874 # Assume input argument to be string or any object representation
1875 # which converts into a formatted IP string.
1876 addr_str = str(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001877 self._ip = self._ip_int_from_string(addr_str)
1878
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001879 @property
1880 def packed(self):
1881 """The binary representation of this address."""
1882 return v6_int_to_packed(self._ip)
1883
Nick Coghlandc9b2552012-05-20 21:01:57 +10001884
1885class IPv6Interface(IPv6Address):
1886
1887 def __init__(self, address):
1888 if isinstance(address, (bytes, int)):
1889 IPv6Address.__init__(self, address)
1890 self.network = IPv6Network(self._ip)
1891 self._prefixlen = self._max_prefixlen
1892 return
1893
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001894 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001895 IPv6Address.__init__(self, addr[0])
1896 self.network = IPv6Network(address, strict=False)
1897 self.netmask = self.network.netmask
1898 self._prefixlen = self.network._prefixlen
1899 self.hostmask = self.network.hostmask
1900
Nick Coghlandc9b2552012-05-20 21:01:57 +10001901 def __str__(self):
1902 return '%s/%d' % (self._string_from_ip_int(self._ip),
1903 self.network.prefixlen)
1904
1905 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001906 address_equal = IPv6Address.__eq__(self, other)
1907 if not address_equal or address_equal is NotImplemented:
1908 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001909 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001910 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001911 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001912 # An interface with an associated network is NOT the
1913 # same as an unassociated address. That's why the hash
1914 # takes the extra info into account.
1915 return False
1916
1917 def __lt__(self, other):
1918 address_less = IPv6Address.__lt__(self, other)
1919 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001920 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001921 try:
1922 return self.network < other.network
1923 except AttributeError:
1924 # We *do* allow addresses and interfaces to be sorted. The
1925 # unassociated address is considered less than all interfaces.
1926 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001927
1928 def __hash__(self):
1929 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1930
1931 @property
1932 def prefixlen(self):
1933 return self._prefixlen
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001934
Nick Coghlandc9b2552012-05-20 21:01:57 +10001935 @property
1936 def ip(self):
1937 return IPv6Address(self._ip)
1938
1939 @property
1940 def with_prefixlen(self):
1941 return self
1942
1943 @property
1944 def with_netmask(self):
1945 return self.with_prefixlen
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001946
Nick Coghlandc9b2552012-05-20 21:01:57 +10001947 @property
1948 def with_hostmask(self):
1949 return '%s/%s' % (self._string_from_ip_int(self._ip),
1950 self.hostmask)
1951
1952
1953class IPv6Network(_BaseV6, _BaseNetwork):
1954
1955 """This class represents and manipulates 128-bit IPv6 networks.
1956
1957 Attributes: [examples for IPv6('2001:db8::1000/124')]
1958 .network_address: IPv6Address('2001:db8::1000')
1959 .hostmask: IPv6Address('::f')
1960 .broadcast_address: IPv6Address('2001:db8::100f')
1961 .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
1962 .prefixlen: 124
1963
1964 """
1965
Nick Coghlan51c30672012-05-27 00:25:58 +10001966 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001967 _address_class = IPv6Address
1968
Nick Coghlandc9b2552012-05-20 21:01:57 +10001969 def __init__(self, address, strict=True):
1970 """Instantiate a new IPv6 Network object.
1971
1972 Args:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001973 address: A string or integer representing the IPv6 network or the
1974 IP and prefix/netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001975 '2001:db8::/128'
1976 '2001:db8:0000:0000:0000:0000:0000:0000/128'
1977 '2001:db8::'
1978 are all functionally the same in IPv6. That is to say,
1979 failing to provide a subnetmask will create an object with
1980 a mask of /128.
1981
1982 Additionally, an integer can be passed, so
1983 IPv6Network('2001:db8::') ==
1984 IPv6Network(42540766411282592856903984951653826560)
1985 or, more generally
1986 IPv6Network(int(IPv6Network('2001:db8::'))) ==
1987 IPv6Network('2001:db8::')
1988
1989 strict: A boolean. If true, ensure that we have been passed
1990 A true network address, eg, 2001:db8::1000/124 and not an
1991 IP address on a network, eg, 2001:db8::1/124.
1992
1993 Raises:
1994 AddressValueError: If address isn't a valid IPv6 address.
1995 NetmaskValueError: If the netmask isn't valid for
1996 an IPv6 address.
1997 ValueError: If strict was True and a network address was not
1998 supplied.
1999
2000 """
2001 _BaseV6.__init__(self, address)
2002 _BaseNetwork.__init__(self, address)
2003
2004 # Efficient constructor from integer.
2005 if isinstance(address, int):
Nick Coghlandc9b2552012-05-20 21:01:57 +10002006 self.network_address = IPv6Address(address)
2007 self._prefixlen = self._max_prefixlen
2008 self.netmask = IPv6Address(self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002009 return
2010
2011 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10002012 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10002013 self.network_address = IPv6Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002014 self._prefixlen = self._max_prefixlen
2015 self.netmask = IPv6Address(self._ALL_ONES)
Hynek Schlawacked36b2e2012-06-08 15:21:21 +02002016 return
Nick Coghlandc9b2552012-05-20 21:01:57 +10002017
2018 # Assume input argument to be string or any object representation
2019 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002020 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002021
2022 self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))
2023
2024 if len(addr) == 2:
2025 if self._is_valid_netmask(addr[1]):
2026 self._prefixlen = int(addr[1])
2027 else:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002028 raise NetmaskValueError('%r is not a valid netmask'
2029 % addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10002030 else:
2031 self._prefixlen = self._max_prefixlen
2032
2033 self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen))
2034 if strict:
2035 if (IPv6Address(int(self.network_address) & int(self.netmask)) !=
2036 self.network_address):
Nick Coghlan912238e2012-07-07 13:34:50 +10002037 raise ValueError('%s has host bits set' % self)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002038 self.network_address = IPv6Address(int(self.network_address) &
2039 int(self.netmask))
2040
2041 if self._prefixlen == (self._max_prefixlen - 1):
2042 self.hosts = self.__iter__
2043
Nick Coghlandc9b2552012-05-20 21:01:57 +10002044 def _is_valid_netmask(self, prefixlen):
2045 """Verify that the netmask/prefixlen is valid.
2046
2047 Args:
2048 prefixlen: A string, the netmask in prefix length format.
2049
2050 Returns:
2051 A boolean, True if the prefix represents a valid IPv6
2052 netmask.
2053
2054 """
2055 try:
2056 prefixlen = int(prefixlen)
2057 except ValueError:
2058 return False
2059 return 0 <= prefixlen <= self._max_prefixlen