blob: cfc370c38035ed5b40f48e5399393c5e12c78c4f [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 Coghlan730f67f2012-08-05 22:02:18 +1000500
Nick Coghlandc9b2552012-05-20 21:01:57 +1000501class _BaseAddress(_IPAddressBase):
502
503 """A generic IP object.
504
505 This IP class contains the version independent methods which are
506 used by single IP addresses.
507
508 """
509
510 def __init__(self, address):
511 if (not isinstance(address, bytes)
512 and '/' in str(address)):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000513 raise AddressValueError("Unexpected '/' in %r" % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000514
Nick Coghlandc9b2552012-05-20 21:01:57 +1000515 def __int__(self):
516 return self._ip
517
Nick Coghlandc9b2552012-05-20 21:01:57 +1000518 def __eq__(self, other):
519 try:
520 return (self._ip == other._ip
521 and self._version == other._version)
522 except AttributeError:
523 return NotImplemented
524
Nick Coghlandc9b2552012-05-20 21:01:57 +1000525 def __lt__(self, other):
526 if self._version != other._version:
527 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000528 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000529 if not isinstance(other, _BaseAddress):
530 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000531 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000532 if self._ip != other._ip:
533 return self._ip < other._ip
534 return False
535
Nick Coghlandc9b2552012-05-20 21:01:57 +1000536 # Shorthand for Integer addition and subtraction. This is not
537 # meant to ever support addition/subtraction of addresses.
538 def __add__(self, other):
539 if not isinstance(other, int):
540 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000541 return self.__class__(int(self) + other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000542
543 def __sub__(self, other):
544 if not isinstance(other, int):
545 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000546 return self.__class__(int(self) - other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000547
548 def __repr__(self):
549 return '%s(%r)' % (self.__class__.__name__, str(self))
550
551 def __str__(self):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200552 return str(self._string_from_ip_int(self._ip))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000553
554 def __hash__(self):
555 return hash(hex(int(self._ip)))
556
557 def _get_address_key(self):
558 return (self._version, self)
559
Nick Coghlandc9b2552012-05-20 21:01:57 +1000560
561class _BaseNetwork(_IPAddressBase):
562
Nick Coghlan51c30672012-05-27 00:25:58 +1000563 """A generic IP network object.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000564
565 This IP class contains the version independent methods which are
566 used by networks.
567
568 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000569 def __init__(self, address):
570 self._cache = {}
571
Nick Coghlandc9b2552012-05-20 21:01:57 +1000572 def __repr__(self):
573 return '%s(%r)' % (self.__class__.__name__, str(self))
574
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200575 def __str__(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000576 return '%s/%d' % (self.network_address, self.prefixlen)
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200577
Nick Coghlandc9b2552012-05-20 21:01:57 +1000578 def hosts(self):
579 """Generate Iterator over usable hosts in a network.
580
Sandro Tosib95c6342012-05-23 23:17:22 +0200581 This is like __iter__ except it doesn't return the network
582 or broadcast addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000583
584 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000585 network = int(self.network_address)
586 broadcast = int(self.broadcast_address)
587 for x in range(network + 1, broadcast):
588 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000589
590 def __iter__(self):
Nick Coghlan7319f692012-07-07 21:43:30 +1000591 network = int(self.network_address)
592 broadcast = int(self.broadcast_address)
593 for x in range(network, broadcast + 1):
594 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000595
596 def __getitem__(self, n):
597 network = int(self.network_address)
598 broadcast = int(self.broadcast_address)
599 if n >= 0:
600 if network + n > broadcast:
601 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000602 return self._address_class(network + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000603 else:
604 n += 1
605 if broadcast + n < network:
606 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000607 return self._address_class(broadcast + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000608
609 def __lt__(self, other):
610 if self._version != other._version:
611 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000612 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000613 if not isinstance(other, _BaseNetwork):
614 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000615 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000616 if self.network_address != other.network_address:
617 return self.network_address < other.network_address
618 if self.netmask != other.netmask:
619 return self.netmask < other.netmask
620 return False
621
Nick Coghlandc9b2552012-05-20 21:01:57 +1000622 def __eq__(self, other):
Nick Coghlan9a9c28c2012-07-07 23:05:59 +1000623 try:
624 return (self._version == other._version and
625 self.network_address == other.network_address and
626 int(self.netmask) == int(other.netmask))
627 except AttributeError:
628 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000629
Nick Coghlandc9b2552012-05-20 21:01:57 +1000630 def __hash__(self):
631 return hash(int(self.network_address) ^ int(self.netmask))
632
633 def __contains__(self, other):
634 # always false if one is v4 and the other is v6.
635 if self._version != other._version:
636 return False
637 # dealing with another network.
638 if isinstance(other, _BaseNetwork):
639 return False
640 # dealing with another address
641 else:
642 # address
643 return (int(self.network_address) <= int(other._ip) <=
644 int(self.broadcast_address))
645
646 def overlaps(self, other):
647 """Tell if self is partly contained in other."""
648 return self.network_address in other or (
649 self.broadcast_address in other or (
650 other.network_address in self or (
651 other.broadcast_address in self)))
652
653 @property
654 def broadcast_address(self):
655 x = self._cache.get('broadcast_address')
656 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000657 x = self._address_class(int(self.network_address) |
658 int(self.hostmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000659 self._cache['broadcast_address'] = x
660 return x
661
662 @property
663 def hostmask(self):
664 x = self._cache.get('hostmask')
665 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000666 x = self._address_class(int(self.netmask) ^ self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000667 self._cache['hostmask'] = x
668 return x
669
670 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000671 def with_prefixlen(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000672 return '%s/%d' % (self.network_address, self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000673
674 @property
675 def with_netmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000676 return '%s/%s' % (self.network_address, self.netmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000677
678 @property
679 def with_hostmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000680 return '%s/%s' % (self.network_address, self.hostmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000681
682 @property
683 def num_addresses(self):
684 """Number of hosts in the current subnet."""
685 return int(self.broadcast_address) - int(self.network_address) + 1
686
687 @property
Nick Coghlan51c30672012-05-27 00:25:58 +1000688 def _address_class(self):
Nick Coghland9722652012-06-17 16:33:00 +1000689 # Returning bare address objects (rather than interfaces) allows for
690 # more consistent behaviour across the network address, broadcast
691 # address and individual host addresses.
692 msg = '%200s has no associated address class' % (type(self),)
693 raise NotImplementedError(msg)
Nick Coghlan51c30672012-05-27 00:25:58 +1000694
695 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000696 def prefixlen(self):
697 return self._prefixlen
698
699 def address_exclude(self, other):
700 """Remove an address from a larger block.
701
702 For example:
703
704 addr1 = ip_network('192.0.2.0/28')
705 addr2 = ip_network('192.0.2.1/32')
706 addr1.address_exclude(addr2) =
707 [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
708 IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
709
710 or IPv6:
711
712 addr1 = ip_network('2001:db8::1/32')
713 addr2 = ip_network('2001:db8::1/128')
714 addr1.address_exclude(addr2) =
715 [ip_network('2001:db8::1/128'),
716 ip_network('2001:db8::2/127'),
717 ip_network('2001:db8::4/126'),
718 ip_network('2001:db8::8/125'),
719 ...
720 ip_network('2001:db8:8000::/33')]
721
722 Args:
723 other: An IPv4Network or IPv6Network object of the same type.
724
725 Returns:
726 An iterator of the the IPv(4|6)Network objects which is self
727 minus other.
728
729 Raises:
730 TypeError: If self and other are of difffering address
731 versions, or if other is not a network object.
732 ValueError: If other is not completely contained by self.
733
734 """
735 if not self._version == other._version:
736 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000737 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000738
739 if not isinstance(other, _BaseNetwork):
Nick Coghlan912238e2012-07-07 13:34:50 +1000740 raise TypeError("%s is not a network object" % other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000741
742 if not (other.network_address >= self.network_address and
743 other.broadcast_address <= self.broadcast_address):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200744 raise ValueError('%s not contained in %s' % (other, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000745 if other == self:
746 raise StopIteration
747
Nick Coghlandc9b2552012-05-20 21:01:57 +1000748 # Make sure we're comparing the network of other.
Nick Coghlan912238e2012-07-07 13:34:50 +1000749 other = other.__class__('%s/%s' % (other.network_address,
750 other.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000751
752 s1, s2 = self.subnets()
753 while s1 != other and s2 != other:
754 if (other.network_address >= s1.network_address and
755 other.broadcast_address <= s1.broadcast_address):
756 yield s2
757 s1, s2 = s1.subnets()
758 elif (other.network_address >= s2.network_address and
759 other.broadcast_address <= s2.broadcast_address):
760 yield s1
761 s1, s2 = s2.subnets()
762 else:
763 # If we got here, there's a bug somewhere.
764 raise AssertionError('Error performing exclusion: '
765 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000766 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000767 if s1 == other:
768 yield s2
769 elif s2 == other:
770 yield s1
771 else:
772 # If we got here, there's a bug somewhere.
773 raise AssertionError('Error performing exclusion: '
774 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000775 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000776
777 def compare_networks(self, other):
778 """Compare two IP objects.
779
780 This is only concerned about the comparison of the integer
781 representation of the network addresses. This means that the
782 host bits aren't considered at all in this method. If you want
783 to compare host bits, you can easily enough do a
784 'HostA._ip < HostB._ip'
785
786 Args:
787 other: An IP object.
788
789 Returns:
790 If the IP versions of self and other are the same, returns:
791
792 -1 if self < other:
793 eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
794 IPv6Network('2001:db8::1000/124') <
795 IPv6Network('2001:db8::2000/124')
796 0 if self == other
797 eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
798 IPv6Network('2001:db8::1000/124') ==
799 IPv6Network('2001:db8::1000/124')
800 1 if self > other
801 eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
802 IPv6Network('2001:db8::2000/124') >
803 IPv6Network('2001:db8::1000/124')
804
805 Raises:
806 TypeError if the IP versions are different.
807
808 """
809 # does this need to raise a ValueError?
810 if self._version != other._version:
811 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000812 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000813 # self._version == other._version below here:
814 if self.network_address < other.network_address:
815 return -1
816 if self.network_address > other.network_address:
817 return 1
818 # self.network_address == other.network_address below here:
819 if self.netmask < other.netmask:
820 return -1
821 if self.netmask > other.netmask:
822 return 1
823 return 0
824
825 def _get_networks_key(self):
826 """Network-only key function.
827
828 Returns an object that identifies this address' network and
829 netmask. This function is a suitable "key" argument for sorted()
830 and list.sort().
831
832 """
833 return (self._version, self.network_address, self.netmask)
834
835 def subnets(self, prefixlen_diff=1, new_prefix=None):
836 """The subnets which join to make the current subnet.
837
838 In the case that self contains only one IP
839 (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
840 for IPv6), yield an iterator with just ourself.
841
842 Args:
843 prefixlen_diff: An integer, the amount the prefix length
844 should be increased by. This should not be set if
845 new_prefix is also set.
846 new_prefix: The desired new prefix length. This must be a
847 larger number (smaller prefix) than the existing prefix.
848 This should not be set if prefixlen_diff is also set.
849
850 Returns:
851 An iterator of IPv(4|6) objects.
852
853 Raises:
854 ValueError: The prefixlen_diff is too small or too large.
855 OR
856 prefixlen_diff and new_prefix are both set or new_prefix
857 is a smaller number than the current prefix (smaller
858 number means a larger network)
859
860 """
861 if self._prefixlen == self._max_prefixlen:
862 yield self
863 return
864
865 if new_prefix is not None:
866 if new_prefix < self._prefixlen:
867 raise ValueError('new prefix must be longer')
868 if prefixlen_diff != 1:
869 raise ValueError('cannot set prefixlen_diff and new_prefix')
870 prefixlen_diff = new_prefix - self._prefixlen
871
872 if prefixlen_diff < 0:
873 raise ValueError('prefix length diff must be > 0')
874 new_prefixlen = self._prefixlen + prefixlen_diff
875
876 if not self._is_valid_netmask(str(new_prefixlen)):
877 raise ValueError(
878 'prefix length diff %d is invalid for netblock %s' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000879 new_prefixlen, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000880
Nick Coghlan51c30672012-05-27 00:25:58 +1000881 first = self.__class__('%s/%s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000882 (self.network_address,
883 self._prefixlen + prefixlen_diff))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000884
885 yield first
886 current = first
887 while True:
888 broadcast = current.broadcast_address
889 if broadcast == self.broadcast_address:
890 return
Nick Coghlan51c30672012-05-27 00:25:58 +1000891 new_addr = self._address_class(int(broadcast) + 1)
Nick Coghlan912238e2012-07-07 13:34:50 +1000892 current = self.__class__('%s/%s' % (new_addr,
893 new_prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000894
895 yield current
896
Nick Coghlandc9b2552012-05-20 21:01:57 +1000897 def supernet(self, prefixlen_diff=1, new_prefix=None):
898 """The supernet containing the current network.
899
900 Args:
901 prefixlen_diff: An integer, the amount the prefix length of
902 the network should be decreased by. For example, given a
903 /24 network and a prefixlen_diff of 3, a supernet with a
904 /21 netmask is returned.
905
906 Returns:
907 An IPv4 network object.
908
909 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200910 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
911 a negative prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000912 OR
913 If prefixlen_diff and new_prefix are both set or new_prefix is a
914 larger number than the current prefix (larger number means a
915 smaller network)
916
917 """
918 if self._prefixlen == 0:
919 return self
920
921 if new_prefix is not None:
922 if new_prefix > self._prefixlen:
923 raise ValueError('new prefix must be shorter')
924 if prefixlen_diff != 1:
925 raise ValueError('cannot set prefixlen_diff and new_prefix')
926 prefixlen_diff = self._prefixlen - new_prefix
927
Nick Coghlandc9b2552012-05-20 21:01:57 +1000928 if self.prefixlen - prefixlen_diff < 0:
929 raise ValueError(
930 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
931 (self.prefixlen, prefixlen_diff))
932 # TODO (pmoody): optimize this.
Nick Coghlan912238e2012-07-07 13:34:50 +1000933 t = self.__class__('%s/%d' % (self.network_address,
Nick Coghlan51c30672012-05-27 00:25:58 +1000934 self.prefixlen - prefixlen_diff),
935 strict=False)
Nick Coghlan912238e2012-07-07 13:34:50 +1000936 return t.__class__('%s/%d' % (t.network_address, t.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000937
Nick Coghlan730f67f2012-08-05 22:02:18 +1000938 @property
939 def is_multicast(self):
940 """Test if the address is reserved for multicast use.
941
942 Returns:
943 A boolean, True if the address is a multicast address.
944 See RFC 2373 2.7 for details.
945
946 """
947 return (self.network_address.is_multicast and
948 self.broadcast_address.is_multicast)
949
950 @property
951 def is_reserved(self):
952 """Test if the address is otherwise IETF reserved.
953
954 Returns:
955 A boolean, True if the address is within one of the
956 reserved IPv6 Network ranges.
957
958 """
959 return (self.network_address.is_reserved and
960 self.broadcast_address.is_reserved)
961
962 @property
963 def is_link_local(self):
964 """Test if the address is reserved for link-local.
965
966 Returns:
967 A boolean, True if the address is reserved per RFC 4291.
968
969 """
970 return (self.network_address.is_link_local and
971 self.broadcast_address.is_link_local)
972
973 @property
974 def is_private(self):
975 """Test if this address is allocated for private networks.
976
977 Returns:
978 A boolean, True if the address is reserved per RFC 4193.
979
980 """
981 return (self.network_address.is_private and
982 self.broadcast_address.is_private)
983
984 @property
985 def is_unspecified(self):
986 """Test if the address is unspecified.
987
988 Returns:
989 A boolean, True if this is the unspecified address as defined in
990 RFC 2373 2.5.2.
991
992 """
993 return (self.network_address.is_unspecified and
994 self.broadcast_address.is_unspecified)
995
996 @property
997 def is_loopback(self):
998 """Test if the address is a loopback address.
999
1000 Returns:
1001 A boolean, True if the address is a loopback address as defined in
1002 RFC 2373 2.5.3.
1003
1004 """
1005 return (self.network_address.is_loopback and
1006 self.broadcast_address.is_loopback)
1007
Nick Coghlandc9b2552012-05-20 21:01:57 +10001008
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001009class _BaseV4:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001010
1011 """Base IPv4 object.
1012
1013 The following methods are used by IPv4 objects in both single IP
1014 addresses and networks.
1015
1016 """
1017
1018 # Equivalent to 255.255.255.255 or 32 bits of 1's.
1019 _ALL_ONES = (2**IPV4LENGTH) - 1
1020 _DECIMAL_DIGITS = frozenset('0123456789')
1021
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001022 # the valid octets for host and netmasks. only useful for IPv4.
Nick Coghlan7319f692012-07-07 21:43:30 +10001023 _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0))
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001024
Nick Coghlandc9b2552012-05-20 21:01:57 +10001025 def __init__(self, address):
1026 self._version = 4
1027 self._max_prefixlen = IPV4LENGTH
1028
1029 def _explode_shorthand_ip_string(self):
1030 return str(self)
1031
1032 def _ip_int_from_string(self, ip_str):
1033 """Turn the given IP string into an integer for comparison.
1034
1035 Args:
1036 ip_str: A string, the IP ip_str.
1037
1038 Returns:
1039 The IP ip_str as an integer.
1040
1041 Raises:
1042 AddressValueError: if ip_str isn't a valid IPv4 Address.
1043
1044 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001045 if not ip_str:
1046 raise AddressValueError('Address cannot be empty')
1047
Nick Coghlandc9b2552012-05-20 21:01:57 +10001048 octets = ip_str.split('.')
1049 if len(octets) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001050 raise AddressValueError("Expected 4 octets in %r" % ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001051
Nick Coghlan7319f692012-07-07 21:43:30 +10001052 try:
1053 return int.from_bytes(map(self._parse_octet, octets), 'big')
1054 except ValueError as exc:
1055 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001056
1057 def _parse_octet(self, octet_str):
1058 """Convert a decimal octet into an integer.
1059
1060 Args:
1061 octet_str: A string, the number to parse.
1062
1063 Returns:
1064 The octet as an integer.
1065
1066 Raises:
1067 ValueError: if the octet isn't strictly a decimal from [0..255].
1068
1069 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001070 if not octet_str:
1071 raise ValueError("Empty octet not permitted")
Nick Coghlandc9b2552012-05-20 21:01:57 +10001072 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1073 if not self._DECIMAL_DIGITS.issuperset(octet_str):
Nick Coghlan07c4e332012-07-08 23:06:45 +10001074 msg = "Only decimal digits permitted in %r"
1075 raise ValueError(msg % octet_str)
1076 # We do the length check second, since the invalid character error
1077 # is likely to be more informative for the user
1078 if len(octet_str) > 3:
1079 msg = "At most 3 characters permitted in %r"
1080 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001081 # Convert to integer (we know digits are legal)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001082 octet_int = int(octet_str, 10)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001083 # Any octets that look like they *might* be written in octal,
1084 # and which don't look exactly the same in both octal and
1085 # decimal are rejected as ambiguous
1086 if octet_int > 7 and octet_str[0] == '0':
Nick Coghlan07c4e332012-07-08 23:06:45 +10001087 msg = "Ambiguous (octal/decimal) value in %r not permitted"
1088 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001089 if octet_int > 255:
Nick Coghlanb582ecc2012-07-07 22:15:22 +10001090 raise ValueError("Octet %d (> 255) not permitted" % octet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001091 return octet_int
1092
1093 def _string_from_ip_int(self, ip_int):
1094 """Turns a 32-bit integer into dotted decimal notation.
1095
1096 Args:
1097 ip_int: An integer, the IP address.
1098
1099 Returns:
1100 The IP address as a string in dotted decimal notation.
1101
1102 """
Nick Coghlan7319f692012-07-07 21:43:30 +10001103 return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001104
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001105 def _is_valid_netmask(self, netmask):
1106 """Verify that the netmask is valid.
1107
1108 Args:
1109 netmask: A string, either a prefix or dotted decimal
1110 netmask.
1111
1112 Returns:
1113 A boolean, True if the prefix represents a valid IPv4
1114 netmask.
1115
1116 """
1117 mask = netmask.split('.')
1118 if len(mask) == 4:
Nick Coghlan7319f692012-07-07 21:43:30 +10001119 try:
1120 for x in mask:
1121 if int(x) not in self._valid_mask_octets:
1122 return False
1123 except ValueError:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001124 # Found something that isn't an integer or isn't valid
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001125 return False
Nick Coghlan7319f692012-07-07 21:43:30 +10001126 for idx, y in enumerate(mask):
1127 if idx > 0 and y > mask[idx - 1]:
1128 return False
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001129 return True
1130 try:
1131 netmask = int(netmask)
1132 except ValueError:
1133 return False
1134 return 0 <= netmask <= self._max_prefixlen
1135
1136 def _is_hostmask(self, ip_str):
1137 """Test if the IP string is a hostmask (rather than a netmask).
1138
1139 Args:
1140 ip_str: A string, the potential hostmask.
1141
1142 Returns:
1143 A boolean, True if the IP string is a hostmask.
1144
1145 """
1146 bits = ip_str.split('.')
1147 try:
Nick Coghlan7319f692012-07-07 21:43:30 +10001148 parts = [x for x in map(int, bits) if x in self._valid_mask_octets]
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001149 except ValueError:
1150 return False
1151 if len(parts) != len(bits):
1152 return False
1153 if parts[0] < parts[-1]:
1154 return True
1155 return False
1156
Nick Coghlandc9b2552012-05-20 21:01:57 +10001157 @property
1158 def max_prefixlen(self):
1159 return self._max_prefixlen
1160
1161 @property
1162 def version(self):
1163 return self._version
1164
Nick Coghlandc9b2552012-05-20 21:01:57 +10001165
1166class IPv4Address(_BaseV4, _BaseAddress):
1167
1168 """Represent and manipulate single IPv4 Addresses."""
1169
1170 def __init__(self, address):
1171
1172 """
1173 Args:
1174 address: A string or integer representing the IP
1175
1176 Additionally, an integer can be passed, so
1177 IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1178 or, more generally
1179 IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1180 IPv4Address('192.0.2.1')
1181
1182 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001183 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001184
1185 """
1186 _BaseAddress.__init__(self, address)
1187 _BaseV4.__init__(self, address)
1188
1189 # Efficient constructor from integer.
1190 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001191 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001192 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001193 return
1194
1195 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001196 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001197 self._check_packed_address(address, 4)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001198 self._ip = struct.unpack('!I', address)[0]
1199 return
1200
1201 # Assume input argument to be string or any object representation
1202 # which converts into a formatted IP string.
1203 addr_str = str(address)
1204 self._ip = self._ip_int_from_string(addr_str)
1205
1206 @property
1207 def packed(self):
1208 """The binary representation of this address."""
1209 return v4_int_to_packed(self._ip)
1210
Nick Coghlan730f67f2012-08-05 22:02:18 +10001211 @property
1212 def is_reserved(self):
1213 """Test if the address is otherwise IETF reserved.
1214
1215 Returns:
1216 A boolean, True if the address is within the
1217 reserved IPv4 Network range.
1218
1219 """
1220 reserved_network = IPv4Network('240.0.0.0/4')
1221 return self in reserved_network
1222
1223 @property
1224 def is_private(self):
1225 """Test if this address is allocated for private networks.
1226
1227 Returns:
1228 A boolean, True if the address is reserved per RFC 1918.
1229
1230 """
1231 private_10 = IPv4Network('10.0.0.0/8')
1232 private_172 = IPv4Network('172.16.0.0/12')
1233 private_192 = IPv4Network('192.168.0.0/16')
1234 return (self in private_10 or
1235 self in private_172 or
1236 self in private_192)
1237
1238 @property
1239 def is_multicast(self):
1240 """Test if the address is reserved for multicast use.
1241
1242 Returns:
1243 A boolean, True if the address is multicast.
1244 See RFC 3171 for details.
1245
1246 """
1247 multicast_network = IPv4Network('224.0.0.0/4')
1248 return self in multicast_network
1249
1250 @property
1251 def is_unspecified(self):
1252 """Test if the address is unspecified.
1253
1254 Returns:
1255 A boolean, True if this is the unspecified address as defined in
1256 RFC 5735 3.
1257
1258 """
1259 unspecified_address = IPv4Address('0.0.0.0')
1260 return self == unspecified_address
1261
1262 @property
1263 def is_loopback(self):
1264 """Test if the address is a loopback address.
1265
1266 Returns:
1267 A boolean, True if the address is a loopback per RFC 3330.
1268
1269 """
1270 loopback_network = IPv4Network('127.0.0.0/8')
1271 return self in loopback_network
1272
1273 @property
1274 def is_link_local(self):
1275 """Test if the address is reserved for link-local.
1276
1277 Returns:
1278 A boolean, True if the address is link-local per RFC 3927.
1279
1280 """
1281 linklocal_network = IPv4Network('169.254.0.0/16')
1282 return self in linklocal_network
1283
Nick Coghlandc9b2552012-05-20 21:01:57 +10001284
1285class IPv4Interface(IPv4Address):
1286
Nick Coghlandc9b2552012-05-20 21:01:57 +10001287 def __init__(self, address):
1288 if isinstance(address, (bytes, int)):
1289 IPv4Address.__init__(self, address)
1290 self.network = IPv4Network(self._ip)
1291 self._prefixlen = self._max_prefixlen
1292 return
1293
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001294 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001295 IPv4Address.__init__(self, addr[0])
1296
1297 self.network = IPv4Network(address, strict=False)
1298 self._prefixlen = self.network._prefixlen
1299
1300 self.netmask = self.network.netmask
1301 self.hostmask = self.network.hostmask
1302
Nick Coghlandc9b2552012-05-20 21:01:57 +10001303 def __str__(self):
1304 return '%s/%d' % (self._string_from_ip_int(self._ip),
1305 self.network.prefixlen)
1306
1307 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001308 address_equal = IPv4Address.__eq__(self, other)
1309 if not address_equal or address_equal is NotImplemented:
1310 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001311 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001312 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001313 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001314 # An interface with an associated network is NOT the
1315 # same as an unassociated address. That's why the hash
1316 # takes the extra info into account.
1317 return False
1318
1319 def __lt__(self, other):
1320 address_less = IPv4Address.__lt__(self, other)
1321 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001322 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001323 try:
1324 return self.network < other.network
1325 except AttributeError:
1326 # We *do* allow addresses and interfaces to be sorted. The
1327 # unassociated address is considered less than all interfaces.
1328 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001329
1330 def __hash__(self):
1331 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1332
Nick Coghlandc9b2552012-05-20 21:01:57 +10001333 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001334 def ip(self):
1335 return IPv4Address(self._ip)
1336
1337 @property
1338 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10001339 return '%s/%s' % (self._string_from_ip_int(self._ip),
1340 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001341
1342 @property
1343 def with_netmask(self):
1344 return '%s/%s' % (self._string_from_ip_int(self._ip),
1345 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001346
Nick Coghlandc9b2552012-05-20 21:01:57 +10001347 @property
1348 def with_hostmask(self):
1349 return '%s/%s' % (self._string_from_ip_int(self._ip),
1350 self.hostmask)
1351
1352
1353class IPv4Network(_BaseV4, _BaseNetwork):
1354
1355 """This class represents and manipulates 32-bit IPv4 network + addresses..
1356
1357 Attributes: [examples for IPv4Network('192.0.2.0/27')]
1358 .network_address: IPv4Address('192.0.2.0')
1359 .hostmask: IPv4Address('0.0.0.31')
1360 .broadcast_address: IPv4Address('192.0.2.32')
1361 .netmask: IPv4Address('255.255.255.224')
1362 .prefixlen: 27
1363
1364 """
Nick Coghlan51c30672012-05-27 00:25:58 +10001365 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001366 _address_class = IPv4Address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001367
Nick Coghlandc9b2552012-05-20 21:01:57 +10001368 def __init__(self, address, strict=True):
1369
1370 """Instantiate a new IPv4 network object.
1371
1372 Args:
1373 address: A string or integer representing the IP [& network].
1374 '192.0.2.0/24'
1375 '192.0.2.0/255.255.255.0'
1376 '192.0.0.2/0.0.0.255'
1377 are all functionally the same in IPv4. Similarly,
1378 '192.0.2.1'
1379 '192.0.2.1/255.255.255.255'
1380 '192.0.2.1/32'
1381 are also functionaly equivalent. That is to say, failing to
1382 provide a subnetmask will create an object with a mask of /32.
1383
1384 If the mask (portion after the / in the argument) is given in
1385 dotted quad form, it is treated as a netmask if it starts with a
1386 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1387 starts with a zero field (e.g. 0.255.255.255 == /8), with the
1388 single exception of an all-zero mask which is treated as a
1389 netmask == /0. If no mask is given, a default of /32 is used.
1390
1391 Additionally, an integer can be passed, so
1392 IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1393 or, more generally
1394 IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1395 IPv4Interface('192.0.2.1')
1396
1397 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001398 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001399 NetmaskValueError: If the netmask isn't valid for
1400 an IPv4 address.
Sandro Tosib4386d32012-06-02 17:14:22 +02001401 ValueError: If strict is True and a network address is not
Nick Coghlandc9b2552012-05-20 21:01:57 +10001402 supplied.
1403
1404 """
1405
1406 _BaseV4.__init__(self, address)
1407 _BaseNetwork.__init__(self, address)
1408
1409 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001410 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001411 self.network_address = IPv4Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001412 self._prefixlen = self._max_prefixlen
1413 self.netmask = IPv4Address(self._ALL_ONES)
1414 #fixme: address/network test here
1415 return
1416
1417 # Efficient constructor from integer.
1418 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001419 self.network_address = IPv4Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001420 self._prefixlen = self._max_prefixlen
1421 self.netmask = IPv4Address(self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001422 #fixme: address/network test here.
1423 return
1424
1425 # Assume input argument to be string or any object representation
1426 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001427 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001428 self.network_address = IPv4Address(self._ip_int_from_string(addr[0]))
1429
Nick Coghlandc9b2552012-05-20 21:01:57 +10001430 if len(addr) == 2:
1431 mask = addr[1].split('.')
1432
1433 if len(mask) == 4:
1434 # We have dotted decimal netmask.
1435 if self._is_valid_netmask(addr[1]):
1436 self.netmask = IPv4Address(self._ip_int_from_string(
1437 addr[1]))
1438 elif self._is_hostmask(addr[1]):
1439 self.netmask = IPv4Address(
1440 self._ip_int_from_string(addr[1]) ^ self._ALL_ONES)
1441 else:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001442 raise NetmaskValueError('%r is not a valid netmask'
Nick Coghlandc9b2552012-05-20 21:01:57 +10001443 % addr[1])
1444
1445 self._prefixlen = self._prefix_from_ip_int(int(self.netmask))
1446 else:
1447 # We have a netmask in prefix length form.
1448 if not self._is_valid_netmask(addr[1]):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001449 raise NetmaskValueError('%r is not a valid netmask'
1450 % addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001451 self._prefixlen = int(addr[1])
1452 self.netmask = IPv4Address(self._ip_int_from_prefix(
1453 self._prefixlen))
1454 else:
1455 self._prefixlen = self._max_prefixlen
1456 self.netmask = IPv4Address(self._ip_int_from_prefix(
1457 self._prefixlen))
1458
1459 if strict:
1460 if (IPv4Address(int(self.network_address) & int(self.netmask)) !=
1461 self.network_address):
1462 raise ValueError('%s has host bits set' % self)
1463 self.network_address = IPv4Address(int(self.network_address) &
1464 int(self.netmask))
1465
1466 if self._prefixlen == (self._max_prefixlen - 1):
1467 self.hosts = self.__iter__
1468
Nick Coghlandc9b2552012-05-20 21:01:57 +10001469
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001470class _BaseV6:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001471
1472 """Base IPv6 object.
1473
1474 The following methods are used by IPv6 objects in both single IP
1475 addresses and networks.
1476
1477 """
1478
1479 _ALL_ONES = (2**IPV6LENGTH) - 1
1480 _HEXTET_COUNT = 8
1481 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
1482
1483 def __init__(self, address):
1484 self._version = 6
1485 self._max_prefixlen = IPV6LENGTH
1486
1487 def _ip_int_from_string(self, ip_str):
1488 """Turn an IPv6 ip_str into an integer.
1489
1490 Args:
1491 ip_str: A string, the IPv6 ip_str.
1492
1493 Returns:
1494 An int, the IPv6 address
1495
1496 Raises:
1497 AddressValueError: if ip_str isn't a valid IPv6 Address.
1498
1499 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001500 if not ip_str:
1501 raise AddressValueError('Address cannot be empty')
1502
Nick Coghlandc9b2552012-05-20 21:01:57 +10001503 parts = ip_str.split(':')
1504
1505 # An IPv6 address needs at least 2 colons (3 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001506 _min_parts = 3
1507 if len(parts) < _min_parts:
1508 msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
1509 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001510
1511 # If the address has an IPv4-style suffix, convert it to hexadecimal.
1512 if '.' in parts[-1]:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001513 try:
1514 ipv4_int = IPv4Address(parts.pop())._ip
1515 except AddressValueError as exc:
1516 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001517 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1518 parts.append('%x' % (ipv4_int & 0xFFFF))
1519
1520 # An IPv6 address can't have more than 8 colons (9 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001521 # The extra colon comes from using the "::" notation for a single
1522 # leading or trailing zero part.
1523 _max_parts = self._HEXTET_COUNT + 1
1524 if len(parts) > _max_parts:
1525 msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
1526 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001527
1528 # Disregarding the endpoints, find '::' with nothing in between.
1529 # This indicates that a run of zeroes has been skipped.
Nick Coghlan7319f692012-07-07 21:43:30 +10001530 skip_index = None
1531 for i in range(1, len(parts) - 1):
1532 if not parts[i]:
1533 if skip_index is not None:
1534 # Can't have more than one '::'
1535 msg = "At most one '::' permitted in %r" % ip_str
1536 raise AddressValueError(msg)
1537 skip_index = i
Nick Coghlandc9b2552012-05-20 21:01:57 +10001538
1539 # parts_hi is the number of parts to copy from above/before the '::'
1540 # parts_lo is the number of parts to copy from below/after the '::'
1541 if skip_index is not None:
1542 # If we found a '::', then check if it also covers the endpoints.
1543 parts_hi = skip_index
1544 parts_lo = len(parts) - skip_index - 1
1545 if not parts[0]:
1546 parts_hi -= 1
1547 if parts_hi:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001548 msg = "Leading ':' only permitted as part of '::' in %r"
1549 raise AddressValueError(msg % ip_str) # ^: requires ^::
Nick Coghlandc9b2552012-05-20 21:01:57 +10001550 if not parts[-1]:
1551 parts_lo -= 1
1552 if parts_lo:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001553 msg = "Trailing ':' only permitted as part of '::' in %r"
1554 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001555 parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo)
1556 if parts_skipped < 1:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001557 msg = "Expected at most %d other parts with '::' in %r"
1558 raise AddressValueError(msg % (self._HEXTET_COUNT-1, ip_str))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001559 else:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001560 # Otherwise, allocate the entire address to parts_hi. The
1561 # endpoints could still be empty, but _parse_hextet() will check
1562 # for that.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001563 if len(parts) != self._HEXTET_COUNT:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001564 msg = "Exactly %d parts expected without '::' in %r"
1565 raise AddressValueError(msg % (self._HEXTET_COUNT, ip_str))
1566 if not parts[0]:
1567 msg = "Leading ':' only permitted as part of '::' in %r"
1568 raise AddressValueError(msg % ip_str) # ^: requires ^::
1569 if not parts[-1]:
1570 msg = "Trailing ':' only permitted as part of '::' in %r"
1571 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001572 parts_hi = len(parts)
1573 parts_lo = 0
1574 parts_skipped = 0
1575
1576 try:
1577 # Now, parse the hextets into a 128-bit integer.
1578 ip_int = 0
1579 for i in range(parts_hi):
1580 ip_int <<= 16
1581 ip_int |= self._parse_hextet(parts[i])
1582 ip_int <<= 16 * parts_skipped
1583 for i in range(-parts_lo, 0):
1584 ip_int <<= 16
1585 ip_int |= self._parse_hextet(parts[i])
1586 return ip_int
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001587 except ValueError as exc:
1588 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001589
1590 def _parse_hextet(self, hextet_str):
1591 """Convert an IPv6 hextet string into an integer.
1592
1593 Args:
1594 hextet_str: A string, the number to parse.
1595
1596 Returns:
1597 The hextet as an integer.
1598
1599 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001600 ValueError: if the input isn't strictly a hex number from
1601 [0..FFFF].
Nick Coghlandc9b2552012-05-20 21:01:57 +10001602
1603 """
1604 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1605 if not self._HEX_DIGITS.issuperset(hextet_str):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001606 raise ValueError("Only hex digits permitted in %r" % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001607 # We do the length check second, since the invalid character error
1608 # is likely to be more informative for the user
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001609 if len(hextet_str) > 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001610 msg = "At most 4 characters permitted in %r"
1611 raise ValueError(msg % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001612 # Length check means we can skip checking the integer value
1613 return int(hextet_str, 16)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001614
1615 def _compress_hextets(self, hextets):
1616 """Compresses a list of hextets.
1617
1618 Compresses a list of strings, replacing the longest continuous
1619 sequence of "0" in the list with "" and adding empty strings at
1620 the beginning or at the end of the string such that subsequently
1621 calling ":".join(hextets) will produce the compressed version of
1622 the IPv6 address.
1623
1624 Args:
1625 hextets: A list of strings, the hextets to compress.
1626
1627 Returns:
1628 A list of strings.
1629
1630 """
1631 best_doublecolon_start = -1
1632 best_doublecolon_len = 0
1633 doublecolon_start = -1
1634 doublecolon_len = 0
1635 for index in range(len(hextets)):
1636 if hextets[index] == '0':
1637 doublecolon_len += 1
1638 if doublecolon_start == -1:
1639 # Start of a sequence of zeros.
1640 doublecolon_start = index
1641 if doublecolon_len > best_doublecolon_len:
1642 # This is the longest sequence of zeros so far.
1643 best_doublecolon_len = doublecolon_len
1644 best_doublecolon_start = doublecolon_start
1645 else:
1646 doublecolon_len = 0
1647 doublecolon_start = -1
1648
1649 if best_doublecolon_len > 1:
1650 best_doublecolon_end = (best_doublecolon_start +
1651 best_doublecolon_len)
1652 # For zeros at the end of the address.
1653 if best_doublecolon_end == len(hextets):
1654 hextets += ['']
1655 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1656 # For zeros at the beginning of the address.
1657 if best_doublecolon_start == 0:
1658 hextets = [''] + hextets
1659
1660 return hextets
1661
1662 def _string_from_ip_int(self, ip_int=None):
1663 """Turns a 128-bit integer into hexadecimal notation.
1664
1665 Args:
1666 ip_int: An integer, the IP address.
1667
1668 Returns:
1669 A string, the hexadecimal representation of the address.
1670
1671 Raises:
1672 ValueError: The address is bigger than 128 bits of all ones.
1673
1674 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001675 if ip_int is None:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001676 ip_int = int(self._ip)
1677
1678 if ip_int > self._ALL_ONES:
1679 raise ValueError('IPv6 address is too large')
1680
1681 hex_str = '%032x' % ip_int
Nick Coghlan7319f692012-07-07 21:43:30 +10001682 hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001683
1684 hextets = self._compress_hextets(hextets)
1685 return ':'.join(hextets)
1686
1687 def _explode_shorthand_ip_string(self):
1688 """Expand a shortened IPv6 address.
1689
1690 Args:
1691 ip_str: A string, the IPv6 address.
1692
1693 Returns:
1694 A string, the expanded IPv6 address.
1695
1696 """
1697 if isinstance(self, IPv6Network):
1698 ip_str = str(self.network_address)
1699 elif isinstance(self, IPv6Interface):
1700 ip_str = str(self.ip)
1701 else:
1702 ip_str = str(self)
1703
1704 ip_int = self._ip_int_from_string(ip_str)
Nick Coghlan7319f692012-07-07 21:43:30 +10001705 hex_str = '%032x' % ip_int
1706 parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001707 if isinstance(self, (_BaseNetwork, IPv6Interface)):
Nick Coghlane3ded952012-08-05 22:45:22 +10001708 return '%s/%d' % (':'.join(parts), self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001709 return ':'.join(parts)
1710
1711 @property
1712 def max_prefixlen(self):
1713 return self._max_prefixlen
1714
1715 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001716 def version(self):
1717 return self._version
1718
Nick Coghlandc9b2552012-05-20 21:01:57 +10001719
1720class IPv6Address(_BaseV6, _BaseAddress):
1721
Sandro Tosib95c6342012-05-23 23:17:22 +02001722 """Represent and manipulate single IPv6 Addresses."""
Nick Coghlandc9b2552012-05-20 21:01:57 +10001723
1724 def __init__(self, address):
1725 """Instantiate a new IPv6 address object.
1726
1727 Args:
1728 address: A string or integer representing the IP
1729
1730 Additionally, an integer can be passed, so
1731 IPv6Address('2001:db8::') ==
1732 IPv6Address(42540766411282592856903984951653826560)
1733 or, more generally
1734 IPv6Address(int(IPv6Address('2001:db8::'))) ==
1735 IPv6Address('2001:db8::')
1736
1737 Raises:
1738 AddressValueError: If address isn't a valid IPv6 address.
1739
1740 """
1741 _BaseAddress.__init__(self, address)
1742 _BaseV6.__init__(self, address)
1743
1744 # Efficient constructor from integer.
1745 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001746 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001747 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001748 return
1749
1750 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001751 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001752 self._check_packed_address(address, 16)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001753 tmp = struct.unpack('!QQ', address)
1754 self._ip = (tmp[0] << 64) | tmp[1]
1755 return
1756
1757 # Assume input argument to be string or any object representation
1758 # which converts into a formatted IP string.
1759 addr_str = str(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001760 self._ip = self._ip_int_from_string(addr_str)
1761
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001762 @property
1763 def packed(self):
1764 """The binary representation of this address."""
1765 return v6_int_to_packed(self._ip)
1766
Nick Coghlan730f67f2012-08-05 22:02:18 +10001767 @property
1768 def is_multicast(self):
1769 """Test if the address is reserved for multicast use.
1770
1771 Returns:
1772 A boolean, True if the address is a multicast address.
1773 See RFC 2373 2.7 for details.
1774
1775 """
1776 multicast_network = IPv6Network('ff00::/8')
1777 return self in multicast_network
1778
1779 @property
1780 def is_reserved(self):
1781 """Test if the address is otherwise IETF reserved.
1782
1783 Returns:
1784 A boolean, True if the address is within one of the
1785 reserved IPv6 Network ranges.
1786
1787 """
1788 reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'),
1789 IPv6Network('200::/7'), IPv6Network('400::/6'),
1790 IPv6Network('800::/5'), IPv6Network('1000::/4'),
1791 IPv6Network('4000::/3'), IPv6Network('6000::/3'),
1792 IPv6Network('8000::/3'), IPv6Network('A000::/3'),
1793 IPv6Network('C000::/3'), IPv6Network('E000::/4'),
1794 IPv6Network('F000::/5'), IPv6Network('F800::/6'),
1795 IPv6Network('FE00::/9')]
1796
1797 return any(self in x for x in reserved_networks)
1798
1799 @property
1800 def is_link_local(self):
1801 """Test if the address is reserved for link-local.
1802
1803 Returns:
1804 A boolean, True if the address is reserved per RFC 4291.
1805
1806 """
1807 linklocal_network = IPv6Network('fe80::/10')
1808 return self in linklocal_network
1809
1810 @property
1811 def is_site_local(self):
1812 """Test if the address is reserved for site-local.
1813
1814 Note that the site-local address space has been deprecated by RFC 3879.
1815 Use is_private to test if this address is in the space of unique local
1816 addresses as defined by RFC 4193.
1817
1818 Returns:
1819 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1820
1821 """
1822 sitelocal_network = IPv6Network('fec0::/10')
1823 return self in sitelocal_network
1824
1825 @property
1826 def is_private(self):
1827 """Test if this address is allocated for private networks.
1828
1829 Returns:
1830 A boolean, True if the address is reserved per RFC 4193.
1831
1832 """
1833 private_network = IPv6Network('fc00::/7')
1834 return self in private_network
1835
1836 @property
1837 def is_unspecified(self):
1838 """Test if the address is unspecified.
1839
1840 Returns:
1841 A boolean, True if this is the unspecified address as defined in
1842 RFC 2373 2.5.2.
1843
1844 """
1845 return self._ip == 0
1846
1847 @property
1848 def is_loopback(self):
1849 """Test if the address is a loopback address.
1850
1851 Returns:
1852 A boolean, True if the address is a loopback address as defined in
1853 RFC 2373 2.5.3.
1854
1855 """
1856 return self._ip == 1
1857
1858 @property
1859 def ipv4_mapped(self):
1860 """Return the IPv4 mapped address.
1861
1862 Returns:
1863 If the IPv6 address is a v4 mapped address, return the
1864 IPv4 mapped address. Return None otherwise.
1865
1866 """
1867 if (self._ip >> 32) != 0xFFFF:
1868 return None
1869 return IPv4Address(self._ip & 0xFFFFFFFF)
1870
1871 @property
1872 def teredo(self):
1873 """Tuple of embedded teredo IPs.
1874
1875 Returns:
1876 Tuple of the (server, client) IPs or None if the address
1877 doesn't appear to be a teredo address (doesn't start with
1878 2001::/32)
1879
1880 """
1881 if (self._ip >> 96) != 0x20010000:
1882 return None
1883 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
1884 IPv4Address(~self._ip & 0xFFFFFFFF))
1885
1886 @property
1887 def sixtofour(self):
1888 """Return the IPv4 6to4 embedded address.
1889
1890 Returns:
1891 The IPv4 6to4-embedded address if present or None if the
1892 address doesn't appear to contain a 6to4 embedded address.
1893
1894 """
1895 if (self._ip >> 112) != 0x2002:
1896 return None
1897 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
1898
Nick Coghlandc9b2552012-05-20 21:01:57 +10001899
1900class IPv6Interface(IPv6Address):
1901
1902 def __init__(self, address):
1903 if isinstance(address, (bytes, int)):
1904 IPv6Address.__init__(self, address)
1905 self.network = IPv6Network(self._ip)
1906 self._prefixlen = self._max_prefixlen
1907 return
1908
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001909 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001910 IPv6Address.__init__(self, addr[0])
1911 self.network = IPv6Network(address, strict=False)
1912 self.netmask = self.network.netmask
1913 self._prefixlen = self.network._prefixlen
1914 self.hostmask = self.network.hostmask
1915
Nick Coghlandc9b2552012-05-20 21:01:57 +10001916 def __str__(self):
1917 return '%s/%d' % (self._string_from_ip_int(self._ip),
1918 self.network.prefixlen)
1919
1920 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001921 address_equal = IPv6Address.__eq__(self, other)
1922 if not address_equal or address_equal is NotImplemented:
1923 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001924 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001925 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001926 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001927 # An interface with an associated network is NOT the
1928 # same as an unassociated address. That's why the hash
1929 # takes the extra info into account.
1930 return False
1931
1932 def __lt__(self, other):
1933 address_less = IPv6Address.__lt__(self, other)
1934 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001935 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001936 try:
1937 return self.network < other.network
1938 except AttributeError:
1939 # We *do* allow addresses and interfaces to be sorted. The
1940 # unassociated address is considered less than all interfaces.
1941 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001942
1943 def __hash__(self):
1944 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1945
1946 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001947 def ip(self):
1948 return IPv6Address(self._ip)
1949
1950 @property
1951 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10001952 return '%s/%s' % (self._string_from_ip_int(self._ip),
1953 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001954
1955 @property
1956 def with_netmask(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10001957 return '%s/%s' % (self._string_from_ip_int(self._ip),
1958 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001959
Nick Coghlandc9b2552012-05-20 21:01:57 +10001960 @property
1961 def with_hostmask(self):
1962 return '%s/%s' % (self._string_from_ip_int(self._ip),
1963 self.hostmask)
1964
Nick Coghlan730f67f2012-08-05 22:02:18 +10001965 @property
1966 def is_unspecified(self):
1967 return self._ip == 0 and self.network.is_unspecified
1968
1969 @property
1970 def is_loopback(self):
1971 return self._ip == 1 and self.network.is_loopback
1972
Nick Coghlandc9b2552012-05-20 21:01:57 +10001973
1974class IPv6Network(_BaseV6, _BaseNetwork):
1975
1976 """This class represents and manipulates 128-bit IPv6 networks.
1977
1978 Attributes: [examples for IPv6('2001:db8::1000/124')]
1979 .network_address: IPv6Address('2001:db8::1000')
1980 .hostmask: IPv6Address('::f')
1981 .broadcast_address: IPv6Address('2001:db8::100f')
1982 .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
1983 .prefixlen: 124
1984
1985 """
1986
Nick Coghlan51c30672012-05-27 00:25:58 +10001987 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001988 _address_class = IPv6Address
1989
Nick Coghlandc9b2552012-05-20 21:01:57 +10001990 def __init__(self, address, strict=True):
1991 """Instantiate a new IPv6 Network object.
1992
1993 Args:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001994 address: A string or integer representing the IPv6 network or the
1995 IP and prefix/netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001996 '2001:db8::/128'
1997 '2001:db8:0000:0000:0000:0000:0000:0000/128'
1998 '2001:db8::'
1999 are all functionally the same in IPv6. That is to say,
2000 failing to provide a subnetmask will create an object with
2001 a mask of /128.
2002
2003 Additionally, an integer can be passed, so
2004 IPv6Network('2001:db8::') ==
2005 IPv6Network(42540766411282592856903984951653826560)
2006 or, more generally
2007 IPv6Network(int(IPv6Network('2001:db8::'))) ==
2008 IPv6Network('2001:db8::')
2009
2010 strict: A boolean. If true, ensure that we have been passed
2011 A true network address, eg, 2001:db8::1000/124 and not an
2012 IP address on a network, eg, 2001:db8::1/124.
2013
2014 Raises:
2015 AddressValueError: If address isn't a valid IPv6 address.
2016 NetmaskValueError: If the netmask isn't valid for
2017 an IPv6 address.
2018 ValueError: If strict was True and a network address was not
2019 supplied.
2020
2021 """
2022 _BaseV6.__init__(self, address)
2023 _BaseNetwork.__init__(self, address)
2024
2025 # Efficient constructor from integer.
2026 if isinstance(address, int):
Nick Coghlandc9b2552012-05-20 21:01:57 +10002027 self.network_address = IPv6Address(address)
2028 self._prefixlen = self._max_prefixlen
2029 self.netmask = IPv6Address(self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002030 return
2031
2032 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10002033 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10002034 self.network_address = IPv6Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002035 self._prefixlen = self._max_prefixlen
2036 self.netmask = IPv6Address(self._ALL_ONES)
Hynek Schlawacked36b2e2012-06-08 15:21:21 +02002037 return
Nick Coghlandc9b2552012-05-20 21:01:57 +10002038
2039 # Assume input argument to be string or any object representation
2040 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002041 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002042
2043 self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))
2044
2045 if len(addr) == 2:
2046 if self._is_valid_netmask(addr[1]):
2047 self._prefixlen = int(addr[1])
2048 else:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002049 raise NetmaskValueError('%r is not a valid netmask'
2050 % addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10002051 else:
2052 self._prefixlen = self._max_prefixlen
2053
2054 self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen))
2055 if strict:
2056 if (IPv6Address(int(self.network_address) & int(self.netmask)) !=
2057 self.network_address):
Nick Coghlan912238e2012-07-07 13:34:50 +10002058 raise ValueError('%s has host bits set' % self)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002059 self.network_address = IPv6Address(int(self.network_address) &
2060 int(self.netmask))
2061
2062 if self._prefixlen == (self._max_prefixlen - 1):
2063 self.hosts = self.__iter__
2064
Nick Coghlandc9b2552012-05-20 21:01:57 +10002065 def _is_valid_netmask(self, prefixlen):
2066 """Verify that the netmask/prefixlen is valid.
2067
2068 Args:
2069 prefixlen: A string, the netmask in prefix length format.
2070
2071 Returns:
2072 A boolean, True if the prefix represents a valid IPv6
2073 netmask.
2074
2075 """
2076 try:
2077 prefixlen = int(prefixlen)
2078 except ValueError:
2079 return False
2080 return 0 <= prefixlen <= self._max_prefixlen
Nick Coghlan730f67f2012-08-05 22:02:18 +10002081
2082 @property
2083 def is_site_local(self):
2084 """Test if the address is reserved for site-local.
2085
2086 Note that the site-local address space has been deprecated by RFC 3879.
2087 Use is_private to test if this address is in the space of unique local
2088 addresses as defined by RFC 4193.
2089
2090 Returns:
2091 A boolean, True if the address is reserved per RFC 3513 2.5.6.
2092
2093 """
2094 return (self.network_address.is_site_local and
2095 self.broadcast_address.is_site_local)