blob: c0b0cb2788c8dfd8075c499957cb840f9fdeb62c [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 _get_prefix_length(number1, number2, bits):
187 """Get the number of leading bits that are same for two numbers.
188
189 Args:
190 number1: an integer.
191 number2: another integer.
192 bits: the maximum number of bits to compare.
193
194 Returns:
195 The number of leading bits that are the same for two numbers.
196
197 """
198 for i in range(bits):
199 if number1 >> i == number2 >> i:
200 return bits - i
201 return 0
202
Sandro Tosib95c6342012-05-23 23:17:22 +0200203
Nick Coghlandc9b2552012-05-20 21:01:57 +1000204def _count_righthand_zero_bits(number, bits):
205 """Count the number of zero bits on the right hand side.
206
207 Args:
208 number: an integer.
209 bits: maximum number of bits to count.
210
211 Returns:
212 The number of zero bits on the right hand side of the number.
213
214 """
215 if number == 0:
216 return bits
217 for i in range(bits):
Nick Coghlan7319f692012-07-07 21:43:30 +1000218 if (number >> i) & 1:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000219 return i
Nick Coghlan7319f692012-07-07 21:43:30 +1000220 # All bits of interest were zero, even if there are more in the number
221 return bits
Nick Coghlandc9b2552012-05-20 21:01:57 +1000222
223
224def summarize_address_range(first, last):
225 """Summarize a network range given the first and last IP addresses.
226
227 Example:
228 >>> summarize_address_range(IPv4Address('192.0.2.0'),
229 IPv4Address('192.0.2.130'))
230 [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'),
231 IPv4Network('192.0.2.130/32')]
232
233 Args:
234 first: the first IPv4Address or IPv6Address in the range.
235 last: the last IPv4Address or IPv6Address in the range.
236
237 Returns:
238 An iterator of the summarized IPv(4|6) network objects.
239
240 Raise:
241 TypeError:
242 If the first and last objects are not IP addresses.
243 If the first and last objects are not the same version.
244 ValueError:
245 If the last object is not greater than the first.
Nick Coghlan51c30672012-05-27 00:25:58 +1000246 If the version of the first address is not 4 or 6.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000247
248 """
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200249 if (not (isinstance(first, _BaseAddress) and
250 isinstance(last, _BaseAddress))):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000251 raise TypeError('first and last must be IP addresses, not networks')
252 if first.version != last.version:
253 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000254 first, last))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000255 if first > last:
256 raise ValueError('last IP address must be greater than first')
257
Nick Coghlandc9b2552012-05-20 21:01:57 +1000258 if first.version == 4:
259 ip = IPv4Network
260 elif first.version == 6:
261 ip = IPv6Network
262 else:
263 raise ValueError('unknown IP version')
264
265 ip_bits = first._max_prefixlen
266 first_int = first._ip
267 last_int = last._ip
268 while first_int <= last_int:
Nick Coghlan7319f692012-07-07 21:43:30 +1000269 nbits = min(_count_righthand_zero_bits(first_int, ip_bits),
270 (last_int - first_int + 1).bit_length() - 1)
271 net = ip('%s/%d' % (first, ip_bits - nbits))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000272 yield net
Nick Coghlan7319f692012-07-07 21:43:30 +1000273 first_int += 1 << nbits
274 if first_int - 1 == ip._ALL_ONES:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000275 break
Nick Coghlan51c30672012-05-27 00:25:58 +1000276 first = first.__class__(first_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000277
Sandro Tosib95c6342012-05-23 23:17:22 +0200278
Nick Coghlandc9b2552012-05-20 21:01:57 +1000279def _collapse_addresses_recursive(addresses):
280 """Loops through the addresses, collapsing concurrent netblocks.
281
282 Example:
283
284 ip1 = IPv4Network('192.0.2.0/26')
285 ip2 = IPv4Network('192.0.2.64/26')
286 ip3 = IPv4Network('192.0.2.128/26')
287 ip4 = IPv4Network('192.0.2.192/26')
288
289 _collapse_addresses_recursive([ip1, ip2, ip3, ip4]) ->
290 [IPv4Network('192.0.2.0/24')]
291
292 This shouldn't be called directly; it is called via
293 collapse_addresses([]).
294
295 Args:
296 addresses: A list of IPv4Network's or IPv6Network's
297
298 Returns:
299 A list of IPv4Network's or IPv6Network's depending on what we were
300 passed.
301
302 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000303 while True:
304 last_addr = None
305 ret_array = []
306 optimized = False
Nick Coghlandc9b2552012-05-20 21:01:57 +1000307
Nick Coghlan7319f692012-07-07 21:43:30 +1000308 for cur_addr in addresses:
309 if not ret_array:
310 last_addr = cur_addr
311 ret_array.append(cur_addr)
312 elif (cur_addr.network_address >= last_addr.network_address and
313 cur_addr.broadcast_address <= last_addr.broadcast_address):
314 optimized = True
315 elif cur_addr == list(last_addr.supernet().subnets())[1]:
316 ret_array[-1] = last_addr = last_addr.supernet()
317 optimized = True
318 else:
319 last_addr = cur_addr
320 ret_array.append(cur_addr)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000321
Nick Coghlan7319f692012-07-07 21:43:30 +1000322 addresses = ret_array
323 if not optimized:
324 return addresses
Nick Coghlandc9b2552012-05-20 21:01:57 +1000325
326
327def collapse_addresses(addresses):
328 """Collapse a list of IP objects.
329
330 Example:
331 collapse_addresses([IPv4Network('192.0.2.0/25'),
332 IPv4Network('192.0.2.128/25')]) ->
333 [IPv4Network('192.0.2.0/24')]
334
335 Args:
336 addresses: An iterator of IPv4Network or IPv6Network objects.
337
338 Returns:
339 An iterator of the collapsed IPv(4|6)Network objects.
340
341 Raises:
342 TypeError: If passed a list of mixed version objects.
343
344 """
345 i = 0
346 addrs = []
347 ips = []
348 nets = []
349
350 # split IP addresses and networks
351 for ip in addresses:
352 if isinstance(ip, _BaseAddress):
353 if ips and ips[-1]._version != ip._version:
354 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000355 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000356 ips.append(ip)
357 elif ip._prefixlen == ip._max_prefixlen:
358 if ips and ips[-1]._version != ip._version:
359 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000360 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000361 try:
362 ips.append(ip.ip)
363 except AttributeError:
364 ips.append(ip.network_address)
365 else:
366 if nets and nets[-1]._version != ip._version:
367 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000368 ip, nets[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000369 nets.append(ip)
370
371 # sort and dedup
372 ips = sorted(set(ips))
373 nets = sorted(set(nets))
374
375 while i < len(ips):
376 (first, last) = _find_address_range(ips[i:])
377 i = ips.index(last) + 1
378 addrs.extend(summarize_address_range(first, last))
379
380 return iter(_collapse_addresses_recursive(sorted(
381 addrs + nets, key=_BaseNetwork._get_networks_key)))
382
383
384def get_mixed_type_key(obj):
385 """Return a key suitable for sorting between networks and addresses.
386
387 Address and Network objects are not sortable by default; they're
388 fundamentally different so the expression
389
390 IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
391
392 doesn't make any sense. There are some times however, where you may wish
393 to have ipaddress sort these for you anyway. If you need to do this, you
394 can use this function as the key= argument to sorted().
395
396 Args:
397 obj: either a Network or Address object.
398 Returns:
399 appropriate key.
400
401 """
402 if isinstance(obj, _BaseNetwork):
403 return obj._get_networks_key()
404 elif isinstance(obj, _BaseAddress):
405 return obj._get_address_key()
406 return NotImplemented
407
408
Nick Coghlan3008ec02012-07-08 00:45:33 +1000409class _TotalOrderingMixin:
410 # Helper that derives the other comparison operations from
411 # __lt__ and __eq__
Nick Coghlan297b1432012-07-08 17:11:04 +1000412 # We avoid functools.total_ordering because it doesn't handle
413 # NotImplemented correctly yet (http://bugs.python.org/issue10042)
Nick Coghlan3008ec02012-07-08 00:45:33 +1000414 def __eq__(self, other):
415 raise NotImplementedError
416 def __ne__(self, other):
417 equal = self.__eq__(other)
418 if equal is NotImplemented:
419 return NotImplemented
420 return not equal
421 def __lt__(self, other):
422 raise NotImplementedError
423 def __le__(self, other):
424 less = self.__lt__(other)
425 if less is NotImplemented or not less:
426 return self.__eq__(other)
427 return less
428 def __gt__(self, other):
429 less = self.__lt__(other)
430 if less is NotImplemented:
431 return NotImplemented
432 equal = self.__eq__(other)
433 if equal is NotImplemented:
434 return NotImplemented
435 return not (less or equal)
436 def __ge__(self, other):
437 less = self.__lt__(other)
438 if less is NotImplemented:
439 return NotImplemented
440 return not less
441
442class _IPAddressBase(_TotalOrderingMixin):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000443
444 """The mother class."""
445
446 @property
447 def exploded(self):
448 """Return the longhand version of the IP address as a string."""
449 return self._explode_shorthand_ip_string()
450
451 @property
452 def compressed(self):
453 """Return the shorthand version of the IP address as a string."""
454 return str(self)
455
Nick Coghland9722652012-06-17 16:33:00 +1000456 @property
457 def version(self):
458 msg = '%200s has no version specified' % (type(self),)
459 raise NotImplementedError(msg)
460
Nick Coghlan297b1432012-07-08 17:11:04 +1000461 def _check_int_address(self, address):
462 if address < 0:
463 msg = "%d (< 0) is not permitted as an IPv%d address"
464 raise AddressValueError(msg % (address, self._version))
465 if address > self._ALL_ONES:
466 msg = "%d (>= 2**%d) is not permitted as an IPv%d address"
467 raise AddressValueError(msg % (address, self._max_prefixlen,
468 self._version))
469
470 def _check_packed_address(self, address, expected_len):
471 address_len = len(address)
472 if address_len != expected_len:
473 msg = "%r (len %d != %d) is not permitted as an IPv%d address"
474 raise AddressValueError(msg % (address, address_len,
475 expected_len, self._version))
476
Nick Coghlandc9b2552012-05-20 21:01:57 +1000477 def _ip_int_from_prefix(self, prefixlen=None):
478 """Turn the prefix length netmask into a int for comparison.
479
480 Args:
481 prefixlen: An integer, the prefix length.
482
483 Returns:
484 An integer.
485
486 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +0200487 if prefixlen is None:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000488 prefixlen = self._prefixlen
489 return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen)
490
491 def _prefix_from_ip_int(self, ip_int, mask=32):
492 """Return prefix length from the decimal netmask.
493
494 Args:
495 ip_int: An integer, the IP address.
496 mask: The netmask. Defaults to 32.
497
498 Returns:
499 An integer, the prefix length.
500
501 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000502 return mask - _count_righthand_zero_bits(ip_int, mask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000503
504 def _ip_string_from_prefix(self, prefixlen=None):
505 """Turn a prefix length into a dotted decimal string.
506
507 Args:
508 prefixlen: An integer, the netmask prefix length.
509
510 Returns:
511 A string, the dotted decimal netmask string.
512
513 """
514 if not prefixlen:
515 prefixlen = self._prefixlen
516 return self._string_from_ip_int(self._ip_int_from_prefix(prefixlen))
517
Nick Coghlandc9b2552012-05-20 21:01:57 +1000518class _BaseAddress(_IPAddressBase):
519
520 """A generic IP object.
521
522 This IP class contains the version independent methods which are
523 used by single IP addresses.
524
525 """
526
527 def __init__(self, address):
528 if (not isinstance(address, bytes)
529 and '/' in str(address)):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000530 raise AddressValueError("Unexpected '/' in %r" % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000531
532 def __index__(self):
533 return self._ip
534
535 def __int__(self):
536 return self._ip
537
Nick Coghlandc9b2552012-05-20 21:01:57 +1000538 def __eq__(self, other):
539 try:
540 return (self._ip == other._ip
541 and self._version == other._version)
542 except AttributeError:
543 return NotImplemented
544
Nick Coghlandc9b2552012-05-20 21:01:57 +1000545 def __lt__(self, other):
546 if self._version != other._version:
547 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000548 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000549 if not isinstance(other, _BaseAddress):
550 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000551 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000552 if self._ip != other._ip:
553 return self._ip < other._ip
554 return False
555
Nick Coghlandc9b2552012-05-20 21:01:57 +1000556 # Shorthand for Integer addition and subtraction. This is not
557 # meant to ever support addition/subtraction of addresses.
558 def __add__(self, other):
559 if not isinstance(other, int):
560 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000561 return self.__class__(int(self) + other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000562
563 def __sub__(self, other):
564 if not isinstance(other, int):
565 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000566 return self.__class__(int(self) - other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000567
568 def __repr__(self):
569 return '%s(%r)' % (self.__class__.__name__, str(self))
570
571 def __str__(self):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200572 return str(self._string_from_ip_int(self._ip))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000573
574 def __hash__(self):
575 return hash(hex(int(self._ip)))
576
577 def _get_address_key(self):
578 return (self._version, self)
579
Nick Coghlandc9b2552012-05-20 21:01:57 +1000580
581class _BaseNetwork(_IPAddressBase):
582
Nick Coghlan51c30672012-05-27 00:25:58 +1000583 """A generic IP network object.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000584
585 This IP class contains the version independent methods which are
586 used by networks.
587
588 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000589 def __init__(self, address):
590 self._cache = {}
591
592 def __index__(self):
593 return int(self.network_address) ^ self.prefixlen
594
595 def __int__(self):
596 return int(self.network_address)
597
598 def __repr__(self):
599 return '%s(%r)' % (self.__class__.__name__, str(self))
600
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200601 def __str__(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000602 return '%s/%d' % (self.network_address, self.prefixlen)
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200603
Nick Coghlandc9b2552012-05-20 21:01:57 +1000604 def hosts(self):
605 """Generate Iterator over usable hosts in a network.
606
Sandro Tosib95c6342012-05-23 23:17:22 +0200607 This is like __iter__ except it doesn't return the network
608 or broadcast addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000609
610 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000611 network = int(self.network_address)
612 broadcast = int(self.broadcast_address)
613 for x in range(network + 1, broadcast):
614 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000615
616 def __iter__(self):
Nick Coghlan7319f692012-07-07 21:43:30 +1000617 network = int(self.network_address)
618 broadcast = int(self.broadcast_address)
619 for x in range(network, broadcast + 1):
620 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000621
622 def __getitem__(self, n):
623 network = int(self.network_address)
624 broadcast = int(self.broadcast_address)
625 if n >= 0:
626 if network + n > broadcast:
627 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000628 return self._address_class(network + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000629 else:
630 n += 1
631 if broadcast + n < network:
632 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000633 return self._address_class(broadcast + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000634
635 def __lt__(self, other):
636 if self._version != other._version:
637 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000638 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000639 if not isinstance(other, _BaseNetwork):
640 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000641 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000642 if self.network_address != other.network_address:
643 return self.network_address < other.network_address
644 if self.netmask != other.netmask:
645 return self.netmask < other.netmask
646 return False
647
Nick Coghlandc9b2552012-05-20 21:01:57 +1000648 def __eq__(self, other):
Nick Coghlan9a9c28c2012-07-07 23:05:59 +1000649 try:
650 return (self._version == other._version and
651 self.network_address == other.network_address and
652 int(self.netmask) == int(other.netmask))
653 except AttributeError:
654 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000655
Nick Coghlandc9b2552012-05-20 21:01:57 +1000656 def __hash__(self):
657 return hash(int(self.network_address) ^ int(self.netmask))
658
659 def __contains__(self, other):
660 # always false if one is v4 and the other is v6.
661 if self._version != other._version:
662 return False
663 # dealing with another network.
664 if isinstance(other, _BaseNetwork):
665 return False
666 # dealing with another address
667 else:
668 # address
669 return (int(self.network_address) <= int(other._ip) <=
670 int(self.broadcast_address))
671
672 def overlaps(self, other):
673 """Tell if self is partly contained in other."""
674 return self.network_address in other or (
675 self.broadcast_address in other or (
676 other.network_address in self or (
677 other.broadcast_address in self)))
678
679 @property
680 def broadcast_address(self):
681 x = self._cache.get('broadcast_address')
682 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000683 x = self._address_class(int(self.network_address) |
684 int(self.hostmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000685 self._cache['broadcast_address'] = x
686 return x
687
688 @property
689 def hostmask(self):
690 x = self._cache.get('hostmask')
691 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000692 x = self._address_class(int(self.netmask) ^ self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000693 self._cache['hostmask'] = x
694 return x
695
696 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000697 def with_prefixlen(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000698 return '%s/%d' % (self.network_address, self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000699
700 @property
701 def with_netmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000702 return '%s/%s' % (self.network_address, self.netmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000703
704 @property
705 def with_hostmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000706 return '%s/%s' % (self.network_address, self.hostmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000707
708 @property
709 def num_addresses(self):
710 """Number of hosts in the current subnet."""
711 return int(self.broadcast_address) - int(self.network_address) + 1
712
713 @property
Nick Coghlan51c30672012-05-27 00:25:58 +1000714 def _address_class(self):
Nick Coghland9722652012-06-17 16:33:00 +1000715 # Returning bare address objects (rather than interfaces) allows for
716 # more consistent behaviour across the network address, broadcast
717 # address and individual host addresses.
718 msg = '%200s has no associated address class' % (type(self),)
719 raise NotImplementedError(msg)
Nick Coghlan51c30672012-05-27 00:25:58 +1000720
721 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000722 def prefixlen(self):
723 return self._prefixlen
724
725 def address_exclude(self, other):
726 """Remove an address from a larger block.
727
728 For example:
729
730 addr1 = ip_network('192.0.2.0/28')
731 addr2 = ip_network('192.0.2.1/32')
732 addr1.address_exclude(addr2) =
733 [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
734 IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
735
736 or IPv6:
737
738 addr1 = ip_network('2001:db8::1/32')
739 addr2 = ip_network('2001:db8::1/128')
740 addr1.address_exclude(addr2) =
741 [ip_network('2001:db8::1/128'),
742 ip_network('2001:db8::2/127'),
743 ip_network('2001:db8::4/126'),
744 ip_network('2001:db8::8/125'),
745 ...
746 ip_network('2001:db8:8000::/33')]
747
748 Args:
749 other: An IPv4Network or IPv6Network object of the same type.
750
751 Returns:
752 An iterator of the the IPv(4|6)Network objects which is self
753 minus other.
754
755 Raises:
756 TypeError: If self and other are of difffering address
757 versions, or if other is not a network object.
758 ValueError: If other is not completely contained by self.
759
760 """
761 if not self._version == other._version:
762 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000763 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000764
765 if not isinstance(other, _BaseNetwork):
Nick Coghlan912238e2012-07-07 13:34:50 +1000766 raise TypeError("%s is not a network object" % other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000767
768 if not (other.network_address >= self.network_address and
769 other.broadcast_address <= self.broadcast_address):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200770 raise ValueError('%s not contained in %s' % (other, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000771 if other == self:
772 raise StopIteration
773
Nick Coghlandc9b2552012-05-20 21:01:57 +1000774 # Make sure we're comparing the network of other.
Nick Coghlan912238e2012-07-07 13:34:50 +1000775 other = other.__class__('%s/%s' % (other.network_address,
776 other.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000777
778 s1, s2 = self.subnets()
779 while s1 != other and s2 != other:
780 if (other.network_address >= s1.network_address and
781 other.broadcast_address <= s1.broadcast_address):
782 yield s2
783 s1, s2 = s1.subnets()
784 elif (other.network_address >= s2.network_address and
785 other.broadcast_address <= s2.broadcast_address):
786 yield s1
787 s1, s2 = s2.subnets()
788 else:
789 # If we got here, there's a bug somewhere.
790 raise AssertionError('Error performing exclusion: '
791 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000792 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000793 if s1 == other:
794 yield s2
795 elif s2 == other:
796 yield s1
797 else:
798 # If we got here, there's a bug somewhere.
799 raise AssertionError('Error performing exclusion: '
800 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000801 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000802
803 def compare_networks(self, other):
804 """Compare two IP objects.
805
806 This is only concerned about the comparison of the integer
807 representation of the network addresses. This means that the
808 host bits aren't considered at all in this method. If you want
809 to compare host bits, you can easily enough do a
810 'HostA._ip < HostB._ip'
811
812 Args:
813 other: An IP object.
814
815 Returns:
816 If the IP versions of self and other are the same, returns:
817
818 -1 if self < other:
819 eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
820 IPv6Network('2001:db8::1000/124') <
821 IPv6Network('2001:db8::2000/124')
822 0 if self == other
823 eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
824 IPv6Network('2001:db8::1000/124') ==
825 IPv6Network('2001:db8::1000/124')
826 1 if self > other
827 eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
828 IPv6Network('2001:db8::2000/124') >
829 IPv6Network('2001:db8::1000/124')
830
831 Raises:
832 TypeError if the IP versions are different.
833
834 """
835 # does this need to raise a ValueError?
836 if self._version != other._version:
837 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000838 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000839 # self._version == other._version below here:
840 if self.network_address < other.network_address:
841 return -1
842 if self.network_address > other.network_address:
843 return 1
844 # self.network_address == other.network_address below here:
845 if self.netmask < other.netmask:
846 return -1
847 if self.netmask > other.netmask:
848 return 1
849 return 0
850
851 def _get_networks_key(self):
852 """Network-only key function.
853
854 Returns an object that identifies this address' network and
855 netmask. This function is a suitable "key" argument for sorted()
856 and list.sort().
857
858 """
859 return (self._version, self.network_address, self.netmask)
860
861 def subnets(self, prefixlen_diff=1, new_prefix=None):
862 """The subnets which join to make the current subnet.
863
864 In the case that self contains only one IP
865 (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
866 for IPv6), yield an iterator with just ourself.
867
868 Args:
869 prefixlen_diff: An integer, the amount the prefix length
870 should be increased by. This should not be set if
871 new_prefix is also set.
872 new_prefix: The desired new prefix length. This must be a
873 larger number (smaller prefix) than the existing prefix.
874 This should not be set if prefixlen_diff is also set.
875
876 Returns:
877 An iterator of IPv(4|6) objects.
878
879 Raises:
880 ValueError: The prefixlen_diff is too small or too large.
881 OR
882 prefixlen_diff and new_prefix are both set or new_prefix
883 is a smaller number than the current prefix (smaller
884 number means a larger network)
885
886 """
887 if self._prefixlen == self._max_prefixlen:
888 yield self
889 return
890
891 if new_prefix is not None:
892 if new_prefix < self._prefixlen:
893 raise ValueError('new prefix must be longer')
894 if prefixlen_diff != 1:
895 raise ValueError('cannot set prefixlen_diff and new_prefix')
896 prefixlen_diff = new_prefix - self._prefixlen
897
898 if prefixlen_diff < 0:
899 raise ValueError('prefix length diff must be > 0')
900 new_prefixlen = self._prefixlen + prefixlen_diff
901
902 if not self._is_valid_netmask(str(new_prefixlen)):
903 raise ValueError(
904 'prefix length diff %d is invalid for netblock %s' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000905 new_prefixlen, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000906
Nick Coghlan51c30672012-05-27 00:25:58 +1000907 first = self.__class__('%s/%s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000908 (self.network_address,
909 self._prefixlen + prefixlen_diff))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000910
911 yield first
912 current = first
913 while True:
914 broadcast = current.broadcast_address
915 if broadcast == self.broadcast_address:
916 return
Nick Coghlan51c30672012-05-27 00:25:58 +1000917 new_addr = self._address_class(int(broadcast) + 1)
Nick Coghlan912238e2012-07-07 13:34:50 +1000918 current = self.__class__('%s/%s' % (new_addr,
919 new_prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000920
921 yield current
922
Nick Coghlandc9b2552012-05-20 21:01:57 +1000923 def supernet(self, prefixlen_diff=1, new_prefix=None):
924 """The supernet containing the current network.
925
926 Args:
927 prefixlen_diff: An integer, the amount the prefix length of
928 the network should be decreased by. For example, given a
929 /24 network and a prefixlen_diff of 3, a supernet with a
930 /21 netmask is returned.
931
932 Returns:
933 An IPv4 network object.
934
935 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200936 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
937 a negative prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000938 OR
939 If prefixlen_diff and new_prefix are both set or new_prefix is a
940 larger number than the current prefix (larger number means a
941 smaller network)
942
943 """
944 if self._prefixlen == 0:
945 return self
946
947 if new_prefix is not None:
948 if new_prefix > self._prefixlen:
949 raise ValueError('new prefix must be shorter')
950 if prefixlen_diff != 1:
951 raise ValueError('cannot set prefixlen_diff and new_prefix')
952 prefixlen_diff = self._prefixlen - new_prefix
953
Nick Coghlandc9b2552012-05-20 21:01:57 +1000954 if self.prefixlen - prefixlen_diff < 0:
955 raise ValueError(
956 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
957 (self.prefixlen, prefixlen_diff))
958 # TODO (pmoody): optimize this.
Nick Coghlan912238e2012-07-07 13:34:50 +1000959 t = self.__class__('%s/%d' % (self.network_address,
Nick Coghlan51c30672012-05-27 00:25:58 +1000960 self.prefixlen - prefixlen_diff),
961 strict=False)
Nick Coghlan912238e2012-07-07 13:34:50 +1000962 return t.__class__('%s/%d' % (t.network_address, t.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000963
964
Hynek Schlawackc4b78a32012-06-01 11:48:32 +0200965class _BaseV4:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000966
967 """Base IPv4 object.
968
969 The following methods are used by IPv4 objects in both single IP
970 addresses and networks.
971
972 """
973
974 # Equivalent to 255.255.255.255 or 32 bits of 1's.
975 _ALL_ONES = (2**IPV4LENGTH) - 1
976 _DECIMAL_DIGITS = frozenset('0123456789')
977
Hynek Schlawack91c5a342012-06-05 11:55:58 +0200978 # the valid octets for host and netmasks. only useful for IPv4.
Nick Coghlan7319f692012-07-07 21:43:30 +1000979 _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0))
Hynek Schlawack91c5a342012-06-05 11:55:58 +0200980
Nick Coghlandc9b2552012-05-20 21:01:57 +1000981 def __init__(self, address):
982 self._version = 4
983 self._max_prefixlen = IPV4LENGTH
984
985 def _explode_shorthand_ip_string(self):
986 return str(self)
987
988 def _ip_int_from_string(self, ip_str):
989 """Turn the given IP string into an integer for comparison.
990
991 Args:
992 ip_str: A string, the IP ip_str.
993
994 Returns:
995 The IP ip_str as an integer.
996
997 Raises:
998 AddressValueError: if ip_str isn't a valid IPv4 Address.
999
1000 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001001 if not ip_str:
1002 raise AddressValueError('Address cannot be empty')
1003
Nick Coghlandc9b2552012-05-20 21:01:57 +10001004 octets = ip_str.split('.')
1005 if len(octets) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001006 raise AddressValueError("Expected 4 octets in %r" % ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001007
Nick Coghlan7319f692012-07-07 21:43:30 +10001008 try:
1009 return int.from_bytes(map(self._parse_octet, octets), 'big')
1010 except ValueError as exc:
1011 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001012
1013 def _parse_octet(self, octet_str):
1014 """Convert a decimal octet into an integer.
1015
1016 Args:
1017 octet_str: A string, the number to parse.
1018
1019 Returns:
1020 The octet as an integer.
1021
1022 Raises:
1023 ValueError: if the octet isn't strictly a decimal from [0..255].
1024
1025 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001026 if not octet_str:
1027 raise ValueError("Empty octet not permitted")
Nick Coghlandc9b2552012-05-20 21:01:57 +10001028 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1029 if not self._DECIMAL_DIGITS.issuperset(octet_str):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001030 raise ValueError("Only decimal digits permitted in %r" % octet_str)
1031 # Convert to integer (we know digits are legal)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001032 octet_int = int(octet_str, 10)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001033 # Any octets that look like they *might* be written in octal,
1034 # and which don't look exactly the same in both octal and
1035 # decimal are rejected as ambiguous
1036 if octet_int > 7 and octet_str[0] == '0':
1037 raise ValueError("Ambiguous leading zero in %r not permitted" %
1038 octet_str)
1039 if octet_int > 255:
Nick Coghlanb582ecc2012-07-07 22:15:22 +10001040 raise ValueError("Octet %d (> 255) not permitted" % octet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001041 return octet_int
1042
1043 def _string_from_ip_int(self, ip_int):
1044 """Turns a 32-bit integer into dotted decimal notation.
1045
1046 Args:
1047 ip_int: An integer, the IP address.
1048
1049 Returns:
1050 The IP address as a string in dotted decimal notation.
1051
1052 """
Nick Coghlan7319f692012-07-07 21:43:30 +10001053 return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001054
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001055 def _is_valid_netmask(self, netmask):
1056 """Verify that the netmask is valid.
1057
1058 Args:
1059 netmask: A string, either a prefix or dotted decimal
1060 netmask.
1061
1062 Returns:
1063 A boolean, True if the prefix represents a valid IPv4
1064 netmask.
1065
1066 """
1067 mask = netmask.split('.')
1068 if len(mask) == 4:
Nick Coghlan7319f692012-07-07 21:43:30 +10001069 try:
1070 for x in mask:
1071 if int(x) not in self._valid_mask_octets:
1072 return False
1073 except ValueError:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001074 # Found something that isn't an integer or isn't valid
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001075 return False
Nick Coghlan7319f692012-07-07 21:43:30 +10001076 for idx, y in enumerate(mask):
1077 if idx > 0 and y > mask[idx - 1]:
1078 return False
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001079 return True
1080 try:
1081 netmask = int(netmask)
1082 except ValueError:
1083 return False
1084 return 0 <= netmask <= self._max_prefixlen
1085
1086 def _is_hostmask(self, ip_str):
1087 """Test if the IP string is a hostmask (rather than a netmask).
1088
1089 Args:
1090 ip_str: A string, the potential hostmask.
1091
1092 Returns:
1093 A boolean, True if the IP string is a hostmask.
1094
1095 """
1096 bits = ip_str.split('.')
1097 try:
Nick Coghlan7319f692012-07-07 21:43:30 +10001098 parts = [x for x in map(int, bits) if x in self._valid_mask_octets]
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001099 except ValueError:
1100 return False
1101 if len(parts) != len(bits):
1102 return False
1103 if parts[0] < parts[-1]:
1104 return True
1105 return False
1106
Nick Coghlandc9b2552012-05-20 21:01:57 +10001107 @property
1108 def max_prefixlen(self):
1109 return self._max_prefixlen
1110
1111 @property
1112 def version(self):
1113 return self._version
1114
1115 @property
1116 def is_reserved(self):
1117 """Test if the address is otherwise IETF reserved.
1118
1119 Returns:
1120 A boolean, True if the address is within the
1121 reserved IPv4 Network range.
1122
1123 """
1124 reserved_network = IPv4Network('240.0.0.0/4')
1125 if isinstance(self, _BaseAddress):
1126 return self in reserved_network
1127 return (self.network_address in reserved_network and
1128 self.broadcast_address in reserved_network)
1129
1130 @property
1131 def is_private(self):
1132 """Test if this address is allocated for private networks.
1133
1134 Returns:
1135 A boolean, True if the address is reserved per RFC 1918.
1136
1137 """
1138 private_10 = IPv4Network('10.0.0.0/8')
1139 private_172 = IPv4Network('172.16.0.0/12')
1140 private_192 = IPv4Network('192.168.0.0/16')
1141 if isinstance(self, _BaseAddress):
1142 return (self in private_10 or self in private_172 or
1143 self in private_192)
1144 else:
1145 return ((self.network_address in private_10 and
1146 self.broadcast_address in private_10) or
1147 (self.network_address in private_172 and
1148 self.broadcast_address in private_172) or
1149 (self.network_address in private_192 and
1150 self.broadcast_address in private_192))
1151
1152 @property
1153 def is_multicast(self):
1154 """Test if the address is reserved for multicast use.
1155
1156 Returns:
1157 A boolean, True if the address is multicast.
1158 See RFC 3171 for details.
1159
1160 """
1161 multicast_network = IPv4Network('224.0.0.0/4')
1162 if isinstance(self, _BaseAddress):
1163 return self in IPv4Network('224.0.0.0/4')
1164 return (self.network_address in multicast_network and
1165 self.broadcast_address in multicast_network)
1166
1167 @property
1168 def is_unspecified(self):
1169 """Test if the address is unspecified.
1170
1171 Returns:
1172 A boolean, True if this is the unspecified address as defined in
1173 RFC 5735 3.
1174
1175 """
1176 unspecified_address = IPv4Address('0.0.0.0')
1177 if isinstance(self, _BaseAddress):
Hynek Schlawackbcd30442012-06-04 14:19:39 +02001178 return self == unspecified_address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001179 return (self.network_address == self.broadcast_address ==
1180 unspecified_address)
1181
1182 @property
1183 def is_loopback(self):
1184 """Test if the address is a loopback address.
1185
1186 Returns:
1187 A boolean, True if the address is a loopback per RFC 3330.
1188
1189 """
1190 loopback_address = IPv4Network('127.0.0.0/8')
1191 if isinstance(self, _BaseAddress):
1192 return self in loopback_address
1193
1194 return (self.network_address in loopback_address and
1195 self.broadcast_address in loopback_address)
1196
1197 @property
1198 def is_link_local(self):
1199 """Test if the address is reserved for link-local.
1200
1201 Returns:
1202 A boolean, True if the address is link-local per RFC 3927.
1203
1204 """
1205 linklocal_network = IPv4Network('169.254.0.0/16')
1206 if isinstance(self, _BaseAddress):
1207 return self in linklocal_network
1208 return (self.network_address in linklocal_network and
1209 self.broadcast_address in linklocal_network)
1210
1211
1212class IPv4Address(_BaseV4, _BaseAddress):
1213
1214 """Represent and manipulate single IPv4 Addresses."""
1215
1216 def __init__(self, address):
1217
1218 """
1219 Args:
1220 address: A string or integer representing the IP
1221
1222 Additionally, an integer can be passed, so
1223 IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1224 or, more generally
1225 IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1226 IPv4Address('192.0.2.1')
1227
1228 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001229 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001230
1231 """
1232 _BaseAddress.__init__(self, address)
1233 _BaseV4.__init__(self, address)
1234
1235 # Efficient constructor from integer.
1236 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001237 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001238 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001239 return
1240
1241 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001242 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001243 self._check_packed_address(address, 4)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001244 self._ip = struct.unpack('!I', address)[0]
1245 return
1246
1247 # Assume input argument to be string or any object representation
1248 # which converts into a formatted IP string.
1249 addr_str = str(address)
1250 self._ip = self._ip_int_from_string(addr_str)
1251
1252 @property
1253 def packed(self):
1254 """The binary representation of this address."""
1255 return v4_int_to_packed(self._ip)
1256
1257
1258class IPv4Interface(IPv4Address):
1259
Nick Coghlandc9b2552012-05-20 21:01:57 +10001260 def __init__(self, address):
1261 if isinstance(address, (bytes, int)):
1262 IPv4Address.__init__(self, address)
1263 self.network = IPv4Network(self._ip)
1264 self._prefixlen = self._max_prefixlen
1265 return
1266
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001267 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001268 IPv4Address.__init__(self, addr[0])
1269
1270 self.network = IPv4Network(address, strict=False)
1271 self._prefixlen = self.network._prefixlen
1272
1273 self.netmask = self.network.netmask
1274 self.hostmask = self.network.hostmask
1275
Nick Coghlandc9b2552012-05-20 21:01:57 +10001276 def __str__(self):
1277 return '%s/%d' % (self._string_from_ip_int(self._ip),
1278 self.network.prefixlen)
1279
1280 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001281 address_equal = IPv4Address.__eq__(self, other)
1282 if not address_equal or address_equal is NotImplemented:
1283 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001284 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001285 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001286 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001287 # An interface with an associated network is NOT the
1288 # same as an unassociated address. That's why the hash
1289 # takes the extra info into account.
1290 return False
1291
1292 def __lt__(self, other):
1293 address_less = IPv4Address.__lt__(self, other)
1294 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001295 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001296 try:
1297 return self.network < other.network
1298 except AttributeError:
1299 # We *do* allow addresses and interfaces to be sorted. The
1300 # unassociated address is considered less than all interfaces.
1301 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001302
1303 def __hash__(self):
1304 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1305
Nick Coghlandc9b2552012-05-20 21:01:57 +10001306 @property
1307 def prefixlen(self):
1308 return self._prefixlen
1309
1310 @property
1311 def ip(self):
1312 return IPv4Address(self._ip)
1313
1314 @property
1315 def with_prefixlen(self):
1316 return self
1317
1318 @property
1319 def with_netmask(self):
1320 return '%s/%s' % (self._string_from_ip_int(self._ip),
1321 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001322
Nick Coghlandc9b2552012-05-20 21:01:57 +10001323 @property
1324 def with_hostmask(self):
1325 return '%s/%s' % (self._string_from_ip_int(self._ip),
1326 self.hostmask)
1327
1328
1329class IPv4Network(_BaseV4, _BaseNetwork):
1330
1331 """This class represents and manipulates 32-bit IPv4 network + addresses..
1332
1333 Attributes: [examples for IPv4Network('192.0.2.0/27')]
1334 .network_address: IPv4Address('192.0.2.0')
1335 .hostmask: IPv4Address('0.0.0.31')
1336 .broadcast_address: IPv4Address('192.0.2.32')
1337 .netmask: IPv4Address('255.255.255.224')
1338 .prefixlen: 27
1339
1340 """
Nick Coghlan51c30672012-05-27 00:25:58 +10001341 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001342 _address_class = IPv4Address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001343
Nick Coghlandc9b2552012-05-20 21:01:57 +10001344 def __init__(self, address, strict=True):
1345
1346 """Instantiate a new IPv4 network object.
1347
1348 Args:
1349 address: A string or integer representing the IP [& network].
1350 '192.0.2.0/24'
1351 '192.0.2.0/255.255.255.0'
1352 '192.0.0.2/0.0.0.255'
1353 are all functionally the same in IPv4. Similarly,
1354 '192.0.2.1'
1355 '192.0.2.1/255.255.255.255'
1356 '192.0.2.1/32'
1357 are also functionaly equivalent. That is to say, failing to
1358 provide a subnetmask will create an object with a mask of /32.
1359
1360 If the mask (portion after the / in the argument) is given in
1361 dotted quad form, it is treated as a netmask if it starts with a
1362 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1363 starts with a zero field (e.g. 0.255.255.255 == /8), with the
1364 single exception of an all-zero mask which is treated as a
1365 netmask == /0. If no mask is given, a default of /32 is used.
1366
1367 Additionally, an integer can be passed, so
1368 IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1369 or, more generally
1370 IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1371 IPv4Interface('192.0.2.1')
1372
1373 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001374 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001375 NetmaskValueError: If the netmask isn't valid for
1376 an IPv4 address.
Sandro Tosib4386d32012-06-02 17:14:22 +02001377 ValueError: If strict is True and a network address is not
Nick Coghlandc9b2552012-05-20 21:01:57 +10001378 supplied.
1379
1380 """
1381
1382 _BaseV4.__init__(self, address)
1383 _BaseNetwork.__init__(self, address)
1384
1385 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001386 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001387 self.network_address = IPv4Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001388 self._prefixlen = self._max_prefixlen
1389 self.netmask = IPv4Address(self._ALL_ONES)
1390 #fixme: address/network test here
1391 return
1392
1393 # Efficient constructor from integer.
1394 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001395 self.network_address = IPv4Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001396 self._prefixlen = self._max_prefixlen
1397 self.netmask = IPv4Address(self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001398 #fixme: address/network test here.
1399 return
1400
1401 # Assume input argument to be string or any object representation
1402 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001403 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001404 self.network_address = IPv4Address(self._ip_int_from_string(addr[0]))
1405
Nick Coghlandc9b2552012-05-20 21:01:57 +10001406 if len(addr) == 2:
1407 mask = addr[1].split('.')
1408
1409 if len(mask) == 4:
1410 # We have dotted decimal netmask.
1411 if self._is_valid_netmask(addr[1]):
1412 self.netmask = IPv4Address(self._ip_int_from_string(
1413 addr[1]))
1414 elif self._is_hostmask(addr[1]):
1415 self.netmask = IPv4Address(
1416 self._ip_int_from_string(addr[1]) ^ self._ALL_ONES)
1417 else:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001418 raise NetmaskValueError('%r is not a valid netmask'
Nick Coghlandc9b2552012-05-20 21:01:57 +10001419 % addr[1])
1420
1421 self._prefixlen = self._prefix_from_ip_int(int(self.netmask))
1422 else:
1423 # We have a netmask in prefix length form.
1424 if not self._is_valid_netmask(addr[1]):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001425 raise NetmaskValueError('%r is not a valid netmask'
1426 % addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001427 self._prefixlen = int(addr[1])
1428 self.netmask = IPv4Address(self._ip_int_from_prefix(
1429 self._prefixlen))
1430 else:
1431 self._prefixlen = self._max_prefixlen
1432 self.netmask = IPv4Address(self._ip_int_from_prefix(
1433 self._prefixlen))
1434
1435 if strict:
1436 if (IPv4Address(int(self.network_address) & int(self.netmask)) !=
1437 self.network_address):
1438 raise ValueError('%s has host bits set' % self)
1439 self.network_address = IPv4Address(int(self.network_address) &
1440 int(self.netmask))
1441
1442 if self._prefixlen == (self._max_prefixlen - 1):
1443 self.hosts = self.__iter__
1444
Nick Coghlandc9b2552012-05-20 21:01:57 +10001445
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001446class _BaseV6:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001447
1448 """Base IPv6 object.
1449
1450 The following methods are used by IPv6 objects in both single IP
1451 addresses and networks.
1452
1453 """
1454
1455 _ALL_ONES = (2**IPV6LENGTH) - 1
1456 _HEXTET_COUNT = 8
1457 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
1458
1459 def __init__(self, address):
1460 self._version = 6
1461 self._max_prefixlen = IPV6LENGTH
1462
1463 def _ip_int_from_string(self, ip_str):
1464 """Turn an IPv6 ip_str into an integer.
1465
1466 Args:
1467 ip_str: A string, the IPv6 ip_str.
1468
1469 Returns:
1470 An int, the IPv6 address
1471
1472 Raises:
1473 AddressValueError: if ip_str isn't a valid IPv6 Address.
1474
1475 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001476 if not ip_str:
1477 raise AddressValueError('Address cannot be empty')
1478
Nick Coghlandc9b2552012-05-20 21:01:57 +10001479 parts = ip_str.split(':')
1480
1481 # An IPv6 address needs at least 2 colons (3 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001482 _min_parts = 3
1483 if len(parts) < _min_parts:
1484 msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
1485 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001486
1487 # If the address has an IPv4-style suffix, convert it to hexadecimal.
1488 if '.' in parts[-1]:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001489 try:
1490 ipv4_int = IPv4Address(parts.pop())._ip
1491 except AddressValueError as exc:
1492 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001493 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1494 parts.append('%x' % (ipv4_int & 0xFFFF))
1495
1496 # An IPv6 address can't have more than 8 colons (9 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001497 # The extra colon comes from using the "::" notation for a single
1498 # leading or trailing zero part.
1499 _max_parts = self._HEXTET_COUNT + 1
1500 if len(parts) > _max_parts:
1501 msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
1502 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001503
1504 # Disregarding the endpoints, find '::' with nothing in between.
1505 # This indicates that a run of zeroes has been skipped.
Nick Coghlan7319f692012-07-07 21:43:30 +10001506 skip_index = None
1507 for i in range(1, len(parts) - 1):
1508 if not parts[i]:
1509 if skip_index is not None:
1510 # Can't have more than one '::'
1511 msg = "At most one '::' permitted in %r" % ip_str
1512 raise AddressValueError(msg)
1513 skip_index = i
Nick Coghlandc9b2552012-05-20 21:01:57 +10001514
1515 # parts_hi is the number of parts to copy from above/before the '::'
1516 # parts_lo is the number of parts to copy from below/after the '::'
1517 if skip_index is not None:
1518 # If we found a '::', then check if it also covers the endpoints.
1519 parts_hi = skip_index
1520 parts_lo = len(parts) - skip_index - 1
1521 if not parts[0]:
1522 parts_hi -= 1
1523 if parts_hi:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001524 msg = "Leading ':' only permitted as part of '::' in %r"
1525 raise AddressValueError(msg % ip_str) # ^: requires ^::
Nick Coghlandc9b2552012-05-20 21:01:57 +10001526 if not parts[-1]:
1527 parts_lo -= 1
1528 if parts_lo:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001529 msg = "Trailing ':' only permitted as part of '::' in %r"
1530 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001531 parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo)
1532 if parts_skipped < 1:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001533 msg = "Expected at most %d other parts with '::' in %r"
1534 raise AddressValueError(msg % (self._HEXTET_COUNT-1, ip_str))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001535 else:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001536 # Otherwise, allocate the entire address to parts_hi. The
1537 # endpoints could still be empty, but _parse_hextet() will check
1538 # for that.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001539 if len(parts) != self._HEXTET_COUNT:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001540 msg = "Exactly %d parts expected without '::' in %r"
1541 raise AddressValueError(msg % (self._HEXTET_COUNT, ip_str))
1542 if not parts[0]:
1543 msg = "Leading ':' only permitted as part of '::' in %r"
1544 raise AddressValueError(msg % ip_str) # ^: requires ^::
1545 if not parts[-1]:
1546 msg = "Trailing ':' only permitted as part of '::' in %r"
1547 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001548 parts_hi = len(parts)
1549 parts_lo = 0
1550 parts_skipped = 0
1551
1552 try:
1553 # Now, parse the hextets into a 128-bit integer.
1554 ip_int = 0
1555 for i in range(parts_hi):
1556 ip_int <<= 16
1557 ip_int |= self._parse_hextet(parts[i])
1558 ip_int <<= 16 * parts_skipped
1559 for i in range(-parts_lo, 0):
1560 ip_int <<= 16
1561 ip_int |= self._parse_hextet(parts[i])
1562 return ip_int
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001563 except ValueError as exc:
1564 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001565
1566 def _parse_hextet(self, hextet_str):
1567 """Convert an IPv6 hextet string into an integer.
1568
1569 Args:
1570 hextet_str: A string, the number to parse.
1571
1572 Returns:
1573 The hextet as an integer.
1574
1575 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001576 ValueError: if the input isn't strictly a hex number from
1577 [0..FFFF].
Nick Coghlandc9b2552012-05-20 21:01:57 +10001578
1579 """
1580 # Whitelist the characters, since int() allows a lot of bizarre stuff.
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001581 # Higher level wrappers convert these to more informative errors
Nick Coghlandc9b2552012-05-20 21:01:57 +10001582 if not self._HEX_DIGITS.issuperset(hextet_str):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001583 raise ValueError("Only hex digits permitted in %r" % hextet_str)
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001584 if len(hextet_str) > 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001585 msg = "At most 4 characters permitted in %r"
1586 raise ValueError(msg % hextet_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001587 hextet_int = int(hextet_str, 16)
1588 if hextet_int > 0xFFFF:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001589 # This is unreachable due to the string length check above
Nick Coghlanb582ecc2012-07-07 22:15:22 +10001590 msg = "Part 0x%X (> 0xFFFF) not permitted"
1591 raise ValueError(msg % hextet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001592 return hextet_int
1593
1594 def _compress_hextets(self, hextets):
1595 """Compresses a list of hextets.
1596
1597 Compresses a list of strings, replacing the longest continuous
1598 sequence of "0" in the list with "" and adding empty strings at
1599 the beginning or at the end of the string such that subsequently
1600 calling ":".join(hextets) will produce the compressed version of
1601 the IPv6 address.
1602
1603 Args:
1604 hextets: A list of strings, the hextets to compress.
1605
1606 Returns:
1607 A list of strings.
1608
1609 """
1610 best_doublecolon_start = -1
1611 best_doublecolon_len = 0
1612 doublecolon_start = -1
1613 doublecolon_len = 0
1614 for index in range(len(hextets)):
1615 if hextets[index] == '0':
1616 doublecolon_len += 1
1617 if doublecolon_start == -1:
1618 # Start of a sequence of zeros.
1619 doublecolon_start = index
1620 if doublecolon_len > best_doublecolon_len:
1621 # This is the longest sequence of zeros so far.
1622 best_doublecolon_len = doublecolon_len
1623 best_doublecolon_start = doublecolon_start
1624 else:
1625 doublecolon_len = 0
1626 doublecolon_start = -1
1627
1628 if best_doublecolon_len > 1:
1629 best_doublecolon_end = (best_doublecolon_start +
1630 best_doublecolon_len)
1631 # For zeros at the end of the address.
1632 if best_doublecolon_end == len(hextets):
1633 hextets += ['']
1634 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1635 # For zeros at the beginning of the address.
1636 if best_doublecolon_start == 0:
1637 hextets = [''] + hextets
1638
1639 return hextets
1640
1641 def _string_from_ip_int(self, ip_int=None):
1642 """Turns a 128-bit integer into hexadecimal notation.
1643
1644 Args:
1645 ip_int: An integer, the IP address.
1646
1647 Returns:
1648 A string, the hexadecimal representation of the address.
1649
1650 Raises:
1651 ValueError: The address is bigger than 128 bits of all ones.
1652
1653 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001654 if ip_int is None:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001655 ip_int = int(self._ip)
1656
1657 if ip_int > self._ALL_ONES:
1658 raise ValueError('IPv6 address is too large')
1659
1660 hex_str = '%032x' % ip_int
Nick Coghlan7319f692012-07-07 21:43:30 +10001661 hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001662
1663 hextets = self._compress_hextets(hextets)
1664 return ':'.join(hextets)
1665
1666 def _explode_shorthand_ip_string(self):
1667 """Expand a shortened IPv6 address.
1668
1669 Args:
1670 ip_str: A string, the IPv6 address.
1671
1672 Returns:
1673 A string, the expanded IPv6 address.
1674
1675 """
1676 if isinstance(self, IPv6Network):
1677 ip_str = str(self.network_address)
1678 elif isinstance(self, IPv6Interface):
1679 ip_str = str(self.ip)
1680 else:
1681 ip_str = str(self)
1682
1683 ip_int = self._ip_int_from_string(ip_str)
Nick Coghlan7319f692012-07-07 21:43:30 +10001684 hex_str = '%032x' % ip_int
1685 parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001686 if isinstance(self, (_BaseNetwork, IPv6Interface)):
1687 return '%s/%d' % (':'.join(parts), self.prefixlen)
1688 return ':'.join(parts)
1689
1690 @property
1691 def max_prefixlen(self):
1692 return self._max_prefixlen
1693
1694 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001695 def version(self):
1696 return self._version
1697
1698 @property
1699 def is_multicast(self):
1700 """Test if the address is reserved for multicast use.
1701
1702 Returns:
1703 A boolean, True if the address is a multicast address.
1704 See RFC 2373 2.7 for details.
1705
1706 """
1707 multicast_network = IPv6Network('ff00::/8')
1708 if isinstance(self, _BaseAddress):
1709 return self in multicast_network
1710 return (self.network_address in multicast_network and
1711 self.broadcast_address in multicast_network)
1712
1713 @property
1714 def is_reserved(self):
1715 """Test if the address is otherwise IETF reserved.
1716
1717 Returns:
1718 A boolean, True if the address is within one of the
1719 reserved IPv6 Network ranges.
1720
1721 """
1722 reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'),
1723 IPv6Network('200::/7'), IPv6Network('400::/6'),
1724 IPv6Network('800::/5'), IPv6Network('1000::/4'),
1725 IPv6Network('4000::/3'), IPv6Network('6000::/3'),
1726 IPv6Network('8000::/3'), IPv6Network('A000::/3'),
1727 IPv6Network('C000::/3'), IPv6Network('E000::/4'),
1728 IPv6Network('F000::/5'), IPv6Network('F800::/6'),
1729 IPv6Network('FE00::/9')]
1730
1731 if isinstance(self, _BaseAddress):
Nick Coghlan7319f692012-07-07 21:43:30 +10001732 return any(self in x for x in reserved_networks)
1733 return any(self.network_address in x and self.broadcast_address in x
1734 for x in reserved_networks)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001735
1736 @property
1737 def is_link_local(self):
1738 """Test if the address is reserved for link-local.
1739
1740 Returns:
1741 A boolean, True if the address is reserved per RFC 4291.
1742
1743 """
1744 linklocal_network = IPv6Network('fe80::/10')
1745 if isinstance(self, _BaseAddress):
1746 return self in linklocal_network
1747 return (self.network_address in linklocal_network and
1748 self.broadcast_address in linklocal_network)
1749
1750 @property
1751 def is_site_local(self):
1752 """Test if the address is reserved for site-local.
1753
1754 Note that the site-local address space has been deprecated by RFC 3879.
1755 Use is_private to test if this address is in the space of unique local
1756 addresses as defined by RFC 4193.
1757
1758 Returns:
1759 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1760
1761 """
1762 sitelocal_network = IPv6Network('fec0::/10')
1763 if isinstance(self, _BaseAddress):
1764 return self in sitelocal_network
1765 return (self.network_address in sitelocal_network and
1766 self.broadcast_address in sitelocal_network)
1767
1768 @property
1769 def is_private(self):
1770 """Test if this address is allocated for private networks.
1771
1772 Returns:
1773 A boolean, True if the address is reserved per RFC 4193.
1774
1775 """
1776 private_network = IPv6Network('fc00::/7')
1777 if isinstance(self, _BaseAddress):
1778 return self in private_network
1779 return (self.network_address in private_network and
1780 self.broadcast_address in private_network)
1781
Nick Coghlandc9b2552012-05-20 21:01:57 +10001782 @property
1783 def ipv4_mapped(self):
1784 """Return the IPv4 mapped address.
1785
1786 Returns:
1787 If the IPv6 address is a v4 mapped address, return the
1788 IPv4 mapped address. Return None otherwise.
1789
1790 """
1791 if (self._ip >> 32) != 0xFFFF:
1792 return None
1793 return IPv4Address(self._ip & 0xFFFFFFFF)
1794
1795 @property
1796 def teredo(self):
1797 """Tuple of embedded teredo IPs.
1798
1799 Returns:
1800 Tuple of the (server, client) IPs or None if the address
1801 doesn't appear to be a teredo address (doesn't start with
1802 2001::/32)
1803
1804 """
1805 if (self._ip >> 96) != 0x20010000:
1806 return None
1807 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
1808 IPv4Address(~self._ip & 0xFFFFFFFF))
1809
1810 @property
1811 def sixtofour(self):
1812 """Return the IPv4 6to4 embedded address.
1813
1814 Returns:
1815 The IPv4 6to4-embedded address if present or None if the
1816 address doesn't appear to contain a 6to4 embedded address.
1817
1818 """
1819 if (self._ip >> 112) != 0x2002:
1820 return None
1821 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
1822
1823 @property
1824 def is_unspecified(self):
1825 """Test if the address is unspecified.
1826
1827 Returns:
1828 A boolean, True if this is the unspecified address as defined in
1829 RFC 2373 2.5.2.
1830
1831 """
1832 if isinstance(self, (IPv6Network, IPv6Interface)):
1833 return int(self.network_address) == 0 and getattr(
1834 self, '_prefixlen', 128) == 128
1835 return self._ip == 0
1836
1837 @property
1838 def is_loopback(self):
1839 """Test if the address is a loopback address.
1840
1841 Returns:
1842 A boolean, True if the address is a loopback address as defined in
1843 RFC 2373 2.5.3.
1844
1845 """
1846 if isinstance(self, IPv6Network):
Nick Coghlan2c589102012-05-27 01:03:25 +10001847 return int(self) == 1 and getattr(
Nick Coghlandc9b2552012-05-20 21:01:57 +10001848 self, '_prefixlen', 128) == 128
1849 elif isinstance(self, IPv6Interface):
1850 return int(self.network.network_address) == 1 and getattr(
1851 self, '_prefixlen', 128) == 128
1852 return self._ip == 1
1853
1854
1855class IPv6Address(_BaseV6, _BaseAddress):
1856
Sandro Tosib95c6342012-05-23 23:17:22 +02001857 """Represent and manipulate single IPv6 Addresses."""
Nick Coghlandc9b2552012-05-20 21:01:57 +10001858
1859 def __init__(self, address):
1860 """Instantiate a new IPv6 address object.
1861
1862 Args:
1863 address: A string or integer representing the IP
1864
1865 Additionally, an integer can be passed, so
1866 IPv6Address('2001:db8::') ==
1867 IPv6Address(42540766411282592856903984951653826560)
1868 or, more generally
1869 IPv6Address(int(IPv6Address('2001:db8::'))) ==
1870 IPv6Address('2001:db8::')
1871
1872 Raises:
1873 AddressValueError: If address isn't a valid IPv6 address.
1874
1875 """
1876 _BaseAddress.__init__(self, address)
1877 _BaseV6.__init__(self, address)
1878
1879 # Efficient constructor from integer.
1880 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001881 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001882 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001883 return
1884
1885 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001886 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001887 self._check_packed_address(address, 16)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001888 tmp = struct.unpack('!QQ', address)
1889 self._ip = (tmp[0] << 64) | tmp[1]
1890 return
1891
1892 # Assume input argument to be string or any object representation
1893 # which converts into a formatted IP string.
1894 addr_str = str(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001895 self._ip = self._ip_int_from_string(addr_str)
1896
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001897 @property
1898 def packed(self):
1899 """The binary representation of this address."""
1900 return v6_int_to_packed(self._ip)
1901
Nick Coghlandc9b2552012-05-20 21:01:57 +10001902
1903class IPv6Interface(IPv6Address):
1904
1905 def __init__(self, address):
1906 if isinstance(address, (bytes, int)):
1907 IPv6Address.__init__(self, address)
1908 self.network = IPv6Network(self._ip)
1909 self._prefixlen = self._max_prefixlen
1910 return
1911
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001912 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001913 IPv6Address.__init__(self, addr[0])
1914 self.network = IPv6Network(address, strict=False)
1915 self.netmask = self.network.netmask
1916 self._prefixlen = self.network._prefixlen
1917 self.hostmask = self.network.hostmask
1918
Nick Coghlandc9b2552012-05-20 21:01:57 +10001919 def __str__(self):
1920 return '%s/%d' % (self._string_from_ip_int(self._ip),
1921 self.network.prefixlen)
1922
1923 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001924 address_equal = IPv6Address.__eq__(self, other)
1925 if not address_equal or address_equal is NotImplemented:
1926 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001927 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001928 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001929 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001930 # An interface with an associated network is NOT the
1931 # same as an unassociated address. That's why the hash
1932 # takes the extra info into account.
1933 return False
1934
1935 def __lt__(self, other):
1936 address_less = IPv6Address.__lt__(self, other)
1937 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001938 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001939 try:
1940 return self.network < other.network
1941 except AttributeError:
1942 # We *do* allow addresses and interfaces to be sorted. The
1943 # unassociated address is considered less than all interfaces.
1944 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001945
1946 def __hash__(self):
1947 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1948
1949 @property
1950 def prefixlen(self):
1951 return self._prefixlen
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001952
Nick Coghlandc9b2552012-05-20 21:01:57 +10001953 @property
1954 def ip(self):
1955 return IPv6Address(self._ip)
1956
1957 @property
1958 def with_prefixlen(self):
1959 return self
1960
1961 @property
1962 def with_netmask(self):
1963 return self.with_prefixlen
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001964
Nick Coghlandc9b2552012-05-20 21:01:57 +10001965 @property
1966 def with_hostmask(self):
1967 return '%s/%s' % (self._string_from_ip_int(self._ip),
1968 self.hostmask)
1969
1970
1971class IPv6Network(_BaseV6, _BaseNetwork):
1972
1973 """This class represents and manipulates 128-bit IPv6 networks.
1974
1975 Attributes: [examples for IPv6('2001:db8::1000/124')]
1976 .network_address: IPv6Address('2001:db8::1000')
1977 .hostmask: IPv6Address('::f')
1978 .broadcast_address: IPv6Address('2001:db8::100f')
1979 .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
1980 .prefixlen: 124
1981
1982 """
1983
Nick Coghlan51c30672012-05-27 00:25:58 +10001984 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001985 _address_class = IPv6Address
1986
Nick Coghlandc9b2552012-05-20 21:01:57 +10001987 def __init__(self, address, strict=True):
1988 """Instantiate a new IPv6 Network object.
1989
1990 Args:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001991 address: A string or integer representing the IPv6 network or the
1992 IP and prefix/netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001993 '2001:db8::/128'
1994 '2001:db8:0000:0000:0000:0000:0000:0000/128'
1995 '2001:db8::'
1996 are all functionally the same in IPv6. That is to say,
1997 failing to provide a subnetmask will create an object with
1998 a mask of /128.
1999
2000 Additionally, an integer can be passed, so
2001 IPv6Network('2001:db8::') ==
2002 IPv6Network(42540766411282592856903984951653826560)
2003 or, more generally
2004 IPv6Network(int(IPv6Network('2001:db8::'))) ==
2005 IPv6Network('2001:db8::')
2006
2007 strict: A boolean. If true, ensure that we have been passed
2008 A true network address, eg, 2001:db8::1000/124 and not an
2009 IP address on a network, eg, 2001:db8::1/124.
2010
2011 Raises:
2012 AddressValueError: If address isn't a valid IPv6 address.
2013 NetmaskValueError: If the netmask isn't valid for
2014 an IPv6 address.
2015 ValueError: If strict was True and a network address was not
2016 supplied.
2017
2018 """
2019 _BaseV6.__init__(self, address)
2020 _BaseNetwork.__init__(self, address)
2021
2022 # Efficient constructor from integer.
2023 if isinstance(address, int):
Nick Coghlandc9b2552012-05-20 21:01:57 +10002024 self.network_address = IPv6Address(address)
2025 self._prefixlen = self._max_prefixlen
2026 self.netmask = IPv6Address(self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002027 return
2028
2029 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10002030 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10002031 self.network_address = IPv6Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002032 self._prefixlen = self._max_prefixlen
2033 self.netmask = IPv6Address(self._ALL_ONES)
Hynek Schlawacked36b2e2012-06-08 15:21:21 +02002034 return
Nick Coghlandc9b2552012-05-20 21:01:57 +10002035
2036 # Assume input argument to be string or any object representation
2037 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002038 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002039
2040 self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))
2041
2042 if len(addr) == 2:
2043 if self._is_valid_netmask(addr[1]):
2044 self._prefixlen = int(addr[1])
2045 else:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002046 raise NetmaskValueError('%r is not a valid netmask'
2047 % addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10002048 else:
2049 self._prefixlen = self._max_prefixlen
2050
2051 self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen))
2052 if strict:
2053 if (IPv6Address(int(self.network_address) & int(self.netmask)) !=
2054 self.network_address):
Nick Coghlan912238e2012-07-07 13:34:50 +10002055 raise ValueError('%s has host bits set' % self)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002056 self.network_address = IPv6Address(int(self.network_address) &
2057 int(self.netmask))
2058
2059 if self._prefixlen == (self._max_prefixlen - 1):
2060 self.hosts = self.__iter__
2061
Nick Coghlandc9b2552012-05-20 21:01:57 +10002062 def _is_valid_netmask(self, prefixlen):
2063 """Verify that the netmask/prefixlen is valid.
2064
2065 Args:
2066 prefixlen: A string, the netmask in prefix length format.
2067
2068 Returns:
2069 A boolean, True if the prefix represents a valid IPv6
2070 netmask.
2071
2072 """
2073 try:
2074 prefixlen = int(prefixlen)
2075 except ValueError:
2076 return False
2077 return 0 <= prefixlen <= self._max_prefixlen