blob: 201900955172f036da020ae467d9a668aff8621e [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 Coghlandc9b2552012-05-20 21:01:57 +1000166def _find_address_range(addresses):
Sandro Tosi876ecad2012-05-23 22:26:55 +0200167 """Find a sequence of IPv#Address.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000168
169 Args:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200170 addresses: a list of IPv#Address objects.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000171
172 Returns:
173 A tuple containing the first and last IP addresses in the sequence.
174
175 """
176 first = last = addresses[0]
177 for ip in addresses[1:]:
178 if ip._ip == last._ip + 1:
179 last = ip
180 else:
181 break
182 return (first, last)
183
Sandro Tosib95c6342012-05-23 23:17:22 +0200184
Nick Coghlandc9b2552012-05-20 21:01:57 +1000185def _get_prefix_length(number1, number2, bits):
186 """Get the number of leading bits that are same for two numbers.
187
188 Args:
189 number1: an integer.
190 number2: another integer.
191 bits: the maximum number of bits to compare.
192
193 Returns:
194 The number of leading bits that are the same for two numbers.
195
196 """
197 for i in range(bits):
198 if number1 >> i == number2 >> i:
199 return bits - i
200 return 0
201
Sandro Tosib95c6342012-05-23 23:17:22 +0200202
Nick Coghlandc9b2552012-05-20 21:01:57 +1000203def _count_righthand_zero_bits(number, bits):
204 """Count the number of zero bits on the right hand side.
205
206 Args:
207 number: an integer.
208 bits: maximum number of bits to count.
209
210 Returns:
211 The number of zero bits on the right hand side of the number.
212
213 """
214 if number == 0:
215 return bits
216 for i in range(bits):
Nick Coghlan7319f692012-07-07 21:43:30 +1000217 if (number >> i) & 1:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000218 return i
Nick Coghlan7319f692012-07-07 21:43:30 +1000219 # All bits of interest were zero, even if there are more in the number
220 return bits
Nick Coghlandc9b2552012-05-20 21:01:57 +1000221
222
223def summarize_address_range(first, last):
224 """Summarize a network range given the first and last IP addresses.
225
226 Example:
227 >>> summarize_address_range(IPv4Address('192.0.2.0'),
228 IPv4Address('192.0.2.130'))
229 [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'),
230 IPv4Network('192.0.2.130/32')]
231
232 Args:
233 first: the first IPv4Address or IPv6Address in the range.
234 last: the last IPv4Address or IPv6Address in the range.
235
236 Returns:
237 An iterator of the summarized IPv(4|6) network objects.
238
239 Raise:
240 TypeError:
241 If the first and last objects are not IP addresses.
242 If the first and last objects are not the same version.
243 ValueError:
244 If the last object is not greater than the first.
Nick Coghlan51c30672012-05-27 00:25:58 +1000245 If the version of the first address is not 4 or 6.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000246
247 """
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200248 if (not (isinstance(first, _BaseAddress) and
249 isinstance(last, _BaseAddress))):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000250 raise TypeError('first and last must be IP addresses, not networks')
251 if first.version != last.version:
252 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000253 first, last))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000254 if first > last:
255 raise ValueError('last IP address must be greater than first')
256
Nick Coghlandc9b2552012-05-20 21:01:57 +1000257 if first.version == 4:
258 ip = IPv4Network
259 elif first.version == 6:
260 ip = IPv6Network
261 else:
262 raise ValueError('unknown IP version')
263
264 ip_bits = first._max_prefixlen
265 first_int = first._ip
266 last_int = last._ip
267 while first_int <= last_int:
Nick Coghlan7319f692012-07-07 21:43:30 +1000268 nbits = min(_count_righthand_zero_bits(first_int, ip_bits),
269 (last_int - first_int + 1).bit_length() - 1)
270 net = ip('%s/%d' % (first, ip_bits - nbits))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000271 yield net
Nick Coghlan7319f692012-07-07 21:43:30 +1000272 first_int += 1 << nbits
273 if first_int - 1 == ip._ALL_ONES:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000274 break
Nick Coghlan51c30672012-05-27 00:25:58 +1000275 first = first.__class__(first_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000276
Sandro Tosib95c6342012-05-23 23:17:22 +0200277
Nick Coghlandc9b2552012-05-20 21:01:57 +1000278def _collapse_addresses_recursive(addresses):
279 """Loops through the addresses, collapsing concurrent netblocks.
280
281 Example:
282
283 ip1 = IPv4Network('192.0.2.0/26')
284 ip2 = IPv4Network('192.0.2.64/26')
285 ip3 = IPv4Network('192.0.2.128/26')
286 ip4 = IPv4Network('192.0.2.192/26')
287
288 _collapse_addresses_recursive([ip1, ip2, ip3, ip4]) ->
289 [IPv4Network('192.0.2.0/24')]
290
291 This shouldn't be called directly; it is called via
292 collapse_addresses([]).
293
294 Args:
295 addresses: A list of IPv4Network's or IPv6Network's
296
297 Returns:
298 A list of IPv4Network's or IPv6Network's depending on what we were
299 passed.
300
301 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000302 while True:
303 last_addr = None
304 ret_array = []
305 optimized = False
Nick Coghlandc9b2552012-05-20 21:01:57 +1000306
Nick Coghlan7319f692012-07-07 21:43:30 +1000307 for cur_addr in addresses:
308 if not ret_array:
309 last_addr = cur_addr
310 ret_array.append(cur_addr)
311 elif (cur_addr.network_address >= last_addr.network_address and
312 cur_addr.broadcast_address <= last_addr.broadcast_address):
313 optimized = True
314 elif cur_addr == list(last_addr.supernet().subnets())[1]:
315 ret_array[-1] = last_addr = last_addr.supernet()
316 optimized = True
317 else:
318 last_addr = cur_addr
319 ret_array.append(cur_addr)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000320
Nick Coghlan7319f692012-07-07 21:43:30 +1000321 addresses = ret_array
322 if not optimized:
323 return addresses
Nick Coghlandc9b2552012-05-20 21:01:57 +1000324
325
326def collapse_addresses(addresses):
327 """Collapse a list of IP objects.
328
329 Example:
330 collapse_addresses([IPv4Network('192.0.2.0/25'),
331 IPv4Network('192.0.2.128/25')]) ->
332 [IPv4Network('192.0.2.0/24')]
333
334 Args:
335 addresses: An iterator of IPv4Network or IPv6Network objects.
336
337 Returns:
338 An iterator of the collapsed IPv(4|6)Network objects.
339
340 Raises:
341 TypeError: If passed a list of mixed version objects.
342
343 """
344 i = 0
345 addrs = []
346 ips = []
347 nets = []
348
349 # split IP addresses and networks
350 for ip in addresses:
351 if isinstance(ip, _BaseAddress):
352 if ips and ips[-1]._version != ip._version:
353 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000354 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000355 ips.append(ip)
356 elif ip._prefixlen == ip._max_prefixlen:
357 if ips and ips[-1]._version != ip._version:
358 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000359 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000360 try:
361 ips.append(ip.ip)
362 except AttributeError:
363 ips.append(ip.network_address)
364 else:
365 if nets and nets[-1]._version != ip._version:
366 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000367 ip, nets[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000368 nets.append(ip)
369
370 # sort and dedup
371 ips = sorted(set(ips))
372 nets = sorted(set(nets))
373
374 while i < len(ips):
375 (first, last) = _find_address_range(ips[i:])
376 i = ips.index(last) + 1
377 addrs.extend(summarize_address_range(first, last))
378
379 return iter(_collapse_addresses_recursive(sorted(
380 addrs + nets, key=_BaseNetwork._get_networks_key)))
381
382
383def get_mixed_type_key(obj):
384 """Return a key suitable for sorting between networks and addresses.
385
386 Address and Network objects are not sortable by default; they're
387 fundamentally different so the expression
388
389 IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
390
391 doesn't make any sense. There are some times however, where you may wish
392 to have ipaddress sort these for you anyway. If you need to do this, you
393 can use this function as the key= argument to sorted().
394
395 Args:
396 obj: either a Network or Address object.
397 Returns:
398 appropriate key.
399
400 """
401 if isinstance(obj, _BaseNetwork):
402 return obj._get_networks_key()
403 elif isinstance(obj, _BaseAddress):
404 return obj._get_address_key()
405 return NotImplemented
406
407
Nick Coghlan3008ec02012-07-08 00:45:33 +1000408class _TotalOrderingMixin:
409 # Helper that derives the other comparison operations from
410 # __lt__ and __eq__
411 def __eq__(self, other):
412 raise NotImplementedError
413 def __ne__(self, other):
414 equal = self.__eq__(other)
415 if equal is NotImplemented:
416 return NotImplemented
417 return not equal
418 def __lt__(self, other):
419 raise NotImplementedError
420 def __le__(self, other):
421 less = self.__lt__(other)
422 if less is NotImplemented or not less:
423 return self.__eq__(other)
424 return less
425 def __gt__(self, other):
426 less = self.__lt__(other)
427 if less is NotImplemented:
428 return NotImplemented
429 equal = self.__eq__(other)
430 if equal is NotImplemented:
431 return NotImplemented
432 return not (less or equal)
433 def __ge__(self, other):
434 less = self.__lt__(other)
435 if less is NotImplemented:
436 return NotImplemented
437 return not less
438
439class _IPAddressBase(_TotalOrderingMixin):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000440
441 """The mother class."""
442
443 @property
444 def exploded(self):
445 """Return the longhand version of the IP address as a string."""
446 return self._explode_shorthand_ip_string()
447
448 @property
449 def compressed(self):
450 """Return the shorthand version of the IP address as a string."""
451 return str(self)
452
Nick Coghland9722652012-06-17 16:33:00 +1000453 @property
454 def version(self):
455 msg = '%200s has no version specified' % (type(self),)
456 raise NotImplementedError(msg)
457
Nick Coghlandc9b2552012-05-20 21:01:57 +1000458 def _ip_int_from_prefix(self, prefixlen=None):
459 """Turn the prefix length netmask into a int for comparison.
460
461 Args:
462 prefixlen: An integer, the prefix length.
463
464 Returns:
465 An integer.
466
467 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +0200468 if prefixlen is None:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000469 prefixlen = self._prefixlen
470 return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen)
471
472 def _prefix_from_ip_int(self, ip_int, mask=32):
473 """Return prefix length from the decimal netmask.
474
475 Args:
476 ip_int: An integer, the IP address.
477 mask: The netmask. Defaults to 32.
478
479 Returns:
480 An integer, the prefix length.
481
482 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000483 return mask - _count_righthand_zero_bits(ip_int, mask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000484
485 def _ip_string_from_prefix(self, prefixlen=None):
486 """Turn a prefix length into a dotted decimal string.
487
488 Args:
489 prefixlen: An integer, the netmask prefix length.
490
491 Returns:
492 A string, the dotted decimal netmask string.
493
494 """
495 if not prefixlen:
496 prefixlen = self._prefixlen
497 return self._string_from_ip_int(self._ip_int_from_prefix(prefixlen))
498
Nick Coghlandc9b2552012-05-20 21:01:57 +1000499class _BaseAddress(_IPAddressBase):
500
501 """A generic IP object.
502
503 This IP class contains the version independent methods which are
504 used by single IP addresses.
505
506 """
507
508 def __init__(self, address):
509 if (not isinstance(address, bytes)
510 and '/' in str(address)):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000511 raise AddressValueError("Unexpected '/' in %r" % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000512
513 def __index__(self):
514 return self._ip
515
516 def __int__(self):
517 return self._ip
518
Nick Coghlandc9b2552012-05-20 21:01:57 +1000519 def __eq__(self, other):
520 try:
521 return (self._ip == other._ip
522 and self._version == other._version)
523 except AttributeError:
524 return NotImplemented
525
Nick Coghlandc9b2552012-05-20 21:01:57 +1000526 def __lt__(self, other):
527 if self._version != other._version:
528 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000529 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000530 if not isinstance(other, _BaseAddress):
531 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000532 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000533 if self._ip != other._ip:
534 return self._ip < other._ip
535 return False
536
Nick Coghlandc9b2552012-05-20 21:01:57 +1000537 # Shorthand for Integer addition and subtraction. This is not
538 # meant to ever support addition/subtraction of addresses.
539 def __add__(self, other):
540 if not isinstance(other, int):
541 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000542 return self.__class__(int(self) + other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000543
544 def __sub__(self, other):
545 if not isinstance(other, int):
546 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000547 return self.__class__(int(self) - other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000548
549 def __repr__(self):
550 return '%s(%r)' % (self.__class__.__name__, str(self))
551
552 def __str__(self):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200553 return str(self._string_from_ip_int(self._ip))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000554
555 def __hash__(self):
556 return hash(hex(int(self._ip)))
557
558 def _get_address_key(self):
559 return (self._version, self)
560
Nick Coghlandc9b2552012-05-20 21:01:57 +1000561
562class _BaseNetwork(_IPAddressBase):
563
Nick Coghlan51c30672012-05-27 00:25:58 +1000564 """A generic IP network object.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000565
566 This IP class contains the version independent methods which are
567 used by networks.
568
569 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000570 def __init__(self, address):
571 self._cache = {}
572
573 def __index__(self):
574 return int(self.network_address) ^ self.prefixlen
575
576 def __int__(self):
577 return int(self.network_address)
578
579 def __repr__(self):
580 return '%s(%r)' % (self.__class__.__name__, str(self))
581
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200582 def __str__(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000583 return '%s/%d' % (self.network_address, self.prefixlen)
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200584
Nick Coghlandc9b2552012-05-20 21:01:57 +1000585 def hosts(self):
586 """Generate Iterator over usable hosts in a network.
587
Sandro Tosib95c6342012-05-23 23:17:22 +0200588 This is like __iter__ except it doesn't return the network
589 or broadcast addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000590
591 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000592 network = int(self.network_address)
593 broadcast = int(self.broadcast_address)
594 for x in range(network + 1, broadcast):
595 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000596
597 def __iter__(self):
Nick Coghlan7319f692012-07-07 21:43:30 +1000598 network = int(self.network_address)
599 broadcast = int(self.broadcast_address)
600 for x in range(network, broadcast + 1):
601 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000602
603 def __getitem__(self, n):
604 network = int(self.network_address)
605 broadcast = int(self.broadcast_address)
606 if n >= 0:
607 if network + n > broadcast:
608 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000609 return self._address_class(network + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000610 else:
611 n += 1
612 if broadcast + n < network:
613 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000614 return self._address_class(broadcast + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000615
616 def __lt__(self, other):
617 if self._version != other._version:
618 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000619 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000620 if not isinstance(other, _BaseNetwork):
621 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000622 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000623 if self.network_address != other.network_address:
624 return self.network_address < other.network_address
625 if self.netmask != other.netmask:
626 return self.netmask < other.netmask
627 return False
628
Nick Coghlandc9b2552012-05-20 21:01:57 +1000629 def __eq__(self, other):
Nick Coghlan9a9c28c2012-07-07 23:05:59 +1000630 try:
631 return (self._version == other._version and
632 self.network_address == other.network_address and
633 int(self.netmask) == int(other.netmask))
634 except AttributeError:
635 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000636
Nick Coghlandc9b2552012-05-20 21:01:57 +1000637 def __hash__(self):
638 return hash(int(self.network_address) ^ int(self.netmask))
639
640 def __contains__(self, other):
641 # always false if one is v4 and the other is v6.
642 if self._version != other._version:
643 return False
644 # dealing with another network.
645 if isinstance(other, _BaseNetwork):
646 return False
647 # dealing with another address
648 else:
649 # address
650 return (int(self.network_address) <= int(other._ip) <=
651 int(self.broadcast_address))
652
653 def overlaps(self, other):
654 """Tell if self is partly contained in other."""
655 return self.network_address in other or (
656 self.broadcast_address in other or (
657 other.network_address in self or (
658 other.broadcast_address in self)))
659
660 @property
661 def broadcast_address(self):
662 x = self._cache.get('broadcast_address')
663 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000664 x = self._address_class(int(self.network_address) |
665 int(self.hostmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000666 self._cache['broadcast_address'] = x
667 return x
668
669 @property
670 def hostmask(self):
671 x = self._cache.get('hostmask')
672 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000673 x = self._address_class(int(self.netmask) ^ self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000674 self._cache['hostmask'] = x
675 return x
676
677 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000678 def with_prefixlen(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000679 return '%s/%d' % (self.network_address, self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000680
681 @property
682 def with_netmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000683 return '%s/%s' % (self.network_address, self.netmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000684
685 @property
686 def with_hostmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000687 return '%s/%s' % (self.network_address, self.hostmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000688
689 @property
690 def num_addresses(self):
691 """Number of hosts in the current subnet."""
692 return int(self.broadcast_address) - int(self.network_address) + 1
693
694 @property
Nick Coghlan51c30672012-05-27 00:25:58 +1000695 def _address_class(self):
Nick Coghland9722652012-06-17 16:33:00 +1000696 # Returning bare address objects (rather than interfaces) allows for
697 # more consistent behaviour across the network address, broadcast
698 # address and individual host addresses.
699 msg = '%200s has no associated address class' % (type(self),)
700 raise NotImplementedError(msg)
Nick Coghlan51c30672012-05-27 00:25:58 +1000701
702 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000703 def prefixlen(self):
704 return self._prefixlen
705
706 def address_exclude(self, other):
707 """Remove an address from a larger block.
708
709 For example:
710
711 addr1 = ip_network('192.0.2.0/28')
712 addr2 = ip_network('192.0.2.1/32')
713 addr1.address_exclude(addr2) =
714 [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
715 IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
716
717 or IPv6:
718
719 addr1 = ip_network('2001:db8::1/32')
720 addr2 = ip_network('2001:db8::1/128')
721 addr1.address_exclude(addr2) =
722 [ip_network('2001:db8::1/128'),
723 ip_network('2001:db8::2/127'),
724 ip_network('2001:db8::4/126'),
725 ip_network('2001:db8::8/125'),
726 ...
727 ip_network('2001:db8:8000::/33')]
728
729 Args:
730 other: An IPv4Network or IPv6Network object of the same type.
731
732 Returns:
733 An iterator of the the IPv(4|6)Network objects which is self
734 minus other.
735
736 Raises:
737 TypeError: If self and other are of difffering address
738 versions, or if other is not a network object.
739 ValueError: If other is not completely contained by self.
740
741 """
742 if not self._version == other._version:
743 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000744 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000745
746 if not isinstance(other, _BaseNetwork):
Nick Coghlan912238e2012-07-07 13:34:50 +1000747 raise TypeError("%s is not a network object" % other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000748
749 if not (other.network_address >= self.network_address and
750 other.broadcast_address <= self.broadcast_address):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200751 raise ValueError('%s not contained in %s' % (other, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000752 if other == self:
753 raise StopIteration
754
Nick Coghlandc9b2552012-05-20 21:01:57 +1000755 # Make sure we're comparing the network of other.
Nick Coghlan912238e2012-07-07 13:34:50 +1000756 other = other.__class__('%s/%s' % (other.network_address,
757 other.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000758
759 s1, s2 = self.subnets()
760 while s1 != other and s2 != other:
761 if (other.network_address >= s1.network_address and
762 other.broadcast_address <= s1.broadcast_address):
763 yield s2
764 s1, s2 = s1.subnets()
765 elif (other.network_address >= s2.network_address and
766 other.broadcast_address <= s2.broadcast_address):
767 yield s1
768 s1, s2 = s2.subnets()
769 else:
770 # If we got here, there's a bug somewhere.
771 raise AssertionError('Error performing exclusion: '
772 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000773 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000774 if s1 == other:
775 yield s2
776 elif s2 == other:
777 yield s1
778 else:
779 # If we got here, there's a bug somewhere.
780 raise AssertionError('Error performing exclusion: '
781 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000782 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000783
784 def compare_networks(self, other):
785 """Compare two IP objects.
786
787 This is only concerned about the comparison of the integer
788 representation of the network addresses. This means that the
789 host bits aren't considered at all in this method. If you want
790 to compare host bits, you can easily enough do a
791 'HostA._ip < HostB._ip'
792
793 Args:
794 other: An IP object.
795
796 Returns:
797 If the IP versions of self and other are the same, returns:
798
799 -1 if self < other:
800 eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
801 IPv6Network('2001:db8::1000/124') <
802 IPv6Network('2001:db8::2000/124')
803 0 if self == other
804 eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
805 IPv6Network('2001:db8::1000/124') ==
806 IPv6Network('2001:db8::1000/124')
807 1 if self > other
808 eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
809 IPv6Network('2001:db8::2000/124') >
810 IPv6Network('2001:db8::1000/124')
811
812 Raises:
813 TypeError if the IP versions are different.
814
815 """
816 # does this need to raise a ValueError?
817 if self._version != other._version:
818 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000819 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000820 # self._version == other._version below here:
821 if self.network_address < other.network_address:
822 return -1
823 if self.network_address > other.network_address:
824 return 1
825 # self.network_address == other.network_address below here:
826 if self.netmask < other.netmask:
827 return -1
828 if self.netmask > other.netmask:
829 return 1
830 return 0
831
832 def _get_networks_key(self):
833 """Network-only key function.
834
835 Returns an object that identifies this address' network and
836 netmask. This function is a suitable "key" argument for sorted()
837 and list.sort().
838
839 """
840 return (self._version, self.network_address, self.netmask)
841
842 def subnets(self, prefixlen_diff=1, new_prefix=None):
843 """The subnets which join to make the current subnet.
844
845 In the case that self contains only one IP
846 (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
847 for IPv6), yield an iterator with just ourself.
848
849 Args:
850 prefixlen_diff: An integer, the amount the prefix length
851 should be increased by. This should not be set if
852 new_prefix is also set.
853 new_prefix: The desired new prefix length. This must be a
854 larger number (smaller prefix) than the existing prefix.
855 This should not be set if prefixlen_diff is also set.
856
857 Returns:
858 An iterator of IPv(4|6) objects.
859
860 Raises:
861 ValueError: The prefixlen_diff is too small or too large.
862 OR
863 prefixlen_diff and new_prefix are both set or new_prefix
864 is a smaller number than the current prefix (smaller
865 number means a larger network)
866
867 """
868 if self._prefixlen == self._max_prefixlen:
869 yield self
870 return
871
872 if new_prefix is not None:
873 if new_prefix < self._prefixlen:
874 raise ValueError('new prefix must be longer')
875 if prefixlen_diff != 1:
876 raise ValueError('cannot set prefixlen_diff and new_prefix')
877 prefixlen_diff = new_prefix - self._prefixlen
878
879 if prefixlen_diff < 0:
880 raise ValueError('prefix length diff must be > 0')
881 new_prefixlen = self._prefixlen + prefixlen_diff
882
883 if not self._is_valid_netmask(str(new_prefixlen)):
884 raise ValueError(
885 'prefix length diff %d is invalid for netblock %s' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000886 new_prefixlen, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000887
Nick Coghlan51c30672012-05-27 00:25:58 +1000888 first = self.__class__('%s/%s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000889 (self.network_address,
890 self._prefixlen + prefixlen_diff))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000891
892 yield first
893 current = first
894 while True:
895 broadcast = current.broadcast_address
896 if broadcast == self.broadcast_address:
897 return
Nick Coghlan51c30672012-05-27 00:25:58 +1000898 new_addr = self._address_class(int(broadcast) + 1)
Nick Coghlan912238e2012-07-07 13:34:50 +1000899 current = self.__class__('%s/%s' % (new_addr,
900 new_prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000901
902 yield current
903
Nick Coghlandc9b2552012-05-20 21:01:57 +1000904 def supernet(self, prefixlen_diff=1, new_prefix=None):
905 """The supernet containing the current network.
906
907 Args:
908 prefixlen_diff: An integer, the amount the prefix length of
909 the network should be decreased by. For example, given a
910 /24 network and a prefixlen_diff of 3, a supernet with a
911 /21 netmask is returned.
912
913 Returns:
914 An IPv4 network object.
915
916 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200917 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
918 a negative prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000919 OR
920 If prefixlen_diff and new_prefix are both set or new_prefix is a
921 larger number than the current prefix (larger number means a
922 smaller network)
923
924 """
925 if self._prefixlen == 0:
926 return self
927
928 if new_prefix is not None:
929 if new_prefix > self._prefixlen:
930 raise ValueError('new prefix must be shorter')
931 if prefixlen_diff != 1:
932 raise ValueError('cannot set prefixlen_diff and new_prefix')
933 prefixlen_diff = self._prefixlen - new_prefix
934
Nick Coghlandc9b2552012-05-20 21:01:57 +1000935 if self.prefixlen - prefixlen_diff < 0:
936 raise ValueError(
937 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
938 (self.prefixlen, prefixlen_diff))
939 # TODO (pmoody): optimize this.
Nick Coghlan912238e2012-07-07 13:34:50 +1000940 t = self.__class__('%s/%d' % (self.network_address,
Nick Coghlan51c30672012-05-27 00:25:58 +1000941 self.prefixlen - prefixlen_diff),
942 strict=False)
Nick Coghlan912238e2012-07-07 13:34:50 +1000943 return t.__class__('%s/%d' % (t.network_address, t.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000944
945
Hynek Schlawackc4b78a32012-06-01 11:48:32 +0200946class _BaseV4:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000947
948 """Base IPv4 object.
949
950 The following methods are used by IPv4 objects in both single IP
951 addresses and networks.
952
953 """
954
955 # Equivalent to 255.255.255.255 or 32 bits of 1's.
956 _ALL_ONES = (2**IPV4LENGTH) - 1
957 _DECIMAL_DIGITS = frozenset('0123456789')
958
Hynek Schlawack91c5a342012-06-05 11:55:58 +0200959 # the valid octets for host and netmasks. only useful for IPv4.
Nick Coghlan7319f692012-07-07 21:43:30 +1000960 _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0))
Hynek Schlawack91c5a342012-06-05 11:55:58 +0200961
Nick Coghlandc9b2552012-05-20 21:01:57 +1000962 def __init__(self, address):
963 self._version = 4
964 self._max_prefixlen = IPV4LENGTH
965
966 def _explode_shorthand_ip_string(self):
967 return str(self)
968
969 def _ip_int_from_string(self, ip_str):
970 """Turn the given IP string into an integer for comparison.
971
972 Args:
973 ip_str: A string, the IP ip_str.
974
975 Returns:
976 The IP ip_str as an integer.
977
978 Raises:
979 AddressValueError: if ip_str isn't a valid IPv4 Address.
980
981 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000982 if not ip_str:
983 raise AddressValueError('Address cannot be empty')
984
Nick Coghlandc9b2552012-05-20 21:01:57 +1000985 octets = ip_str.split('.')
986 if len(octets) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000987 raise AddressValueError("Expected 4 octets in %r" % ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000988
Nick Coghlan7319f692012-07-07 21:43:30 +1000989 try:
990 return int.from_bytes(map(self._parse_octet, octets), 'big')
991 except ValueError as exc:
992 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +1000993
994 def _parse_octet(self, octet_str):
995 """Convert a decimal octet into an integer.
996
997 Args:
998 octet_str: A string, the number to parse.
999
1000 Returns:
1001 The octet as an integer.
1002
1003 Raises:
1004 ValueError: if the octet isn't strictly a decimal from [0..255].
1005
1006 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001007 if not octet_str:
1008 raise ValueError("Empty octet not permitted")
Nick Coghlandc9b2552012-05-20 21:01:57 +10001009 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1010 if not self._DECIMAL_DIGITS.issuperset(octet_str):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001011 raise ValueError("Only decimal digits permitted in %r" % octet_str)
1012 # Convert to integer (we know digits are legal)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001013 octet_int = int(octet_str, 10)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001014 # Any octets that look like they *might* be written in octal,
1015 # and which don't look exactly the same in both octal and
1016 # decimal are rejected as ambiguous
1017 if octet_int > 7 and octet_str[0] == '0':
1018 raise ValueError("Ambiguous leading zero in %r not permitted" %
1019 octet_str)
1020 if octet_int > 255:
Nick Coghlanb582ecc2012-07-07 22:15:22 +10001021 raise ValueError("Octet %d (> 255) not permitted" % octet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001022 return octet_int
1023
1024 def _string_from_ip_int(self, ip_int):
1025 """Turns a 32-bit integer into dotted decimal notation.
1026
1027 Args:
1028 ip_int: An integer, the IP address.
1029
1030 Returns:
1031 The IP address as a string in dotted decimal notation.
1032
1033 """
Nick Coghlan7319f692012-07-07 21:43:30 +10001034 return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001035
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001036 def _is_valid_netmask(self, netmask):
1037 """Verify that the netmask is valid.
1038
1039 Args:
1040 netmask: A string, either a prefix or dotted decimal
1041 netmask.
1042
1043 Returns:
1044 A boolean, True if the prefix represents a valid IPv4
1045 netmask.
1046
1047 """
1048 mask = netmask.split('.')
1049 if len(mask) == 4:
Nick Coghlan7319f692012-07-07 21:43:30 +10001050 try:
1051 for x in mask:
1052 if int(x) not in self._valid_mask_octets:
1053 return False
1054 except ValueError:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001055 # Found something that isn't an integer or isn't valid
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001056 return False
Nick Coghlan7319f692012-07-07 21:43:30 +10001057 for idx, y in enumerate(mask):
1058 if idx > 0 and y > mask[idx - 1]:
1059 return False
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001060 return True
1061 try:
1062 netmask = int(netmask)
1063 except ValueError:
1064 return False
1065 return 0 <= netmask <= self._max_prefixlen
1066
1067 def _is_hostmask(self, ip_str):
1068 """Test if the IP string is a hostmask (rather than a netmask).
1069
1070 Args:
1071 ip_str: A string, the potential hostmask.
1072
1073 Returns:
1074 A boolean, True if the IP string is a hostmask.
1075
1076 """
1077 bits = ip_str.split('.')
1078 try:
Nick Coghlan7319f692012-07-07 21:43:30 +10001079 parts = [x for x in map(int, bits) if x in self._valid_mask_octets]
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001080 except ValueError:
1081 return False
1082 if len(parts) != len(bits):
1083 return False
1084 if parts[0] < parts[-1]:
1085 return True
1086 return False
1087
Nick Coghlandc9b2552012-05-20 21:01:57 +10001088 @property
1089 def max_prefixlen(self):
1090 return self._max_prefixlen
1091
1092 @property
1093 def version(self):
1094 return self._version
1095
1096 @property
1097 def is_reserved(self):
1098 """Test if the address is otherwise IETF reserved.
1099
1100 Returns:
1101 A boolean, True if the address is within the
1102 reserved IPv4 Network range.
1103
1104 """
1105 reserved_network = IPv4Network('240.0.0.0/4')
1106 if isinstance(self, _BaseAddress):
1107 return self in reserved_network
1108 return (self.network_address in reserved_network and
1109 self.broadcast_address in reserved_network)
1110
1111 @property
1112 def is_private(self):
1113 """Test if this address is allocated for private networks.
1114
1115 Returns:
1116 A boolean, True if the address is reserved per RFC 1918.
1117
1118 """
1119 private_10 = IPv4Network('10.0.0.0/8')
1120 private_172 = IPv4Network('172.16.0.0/12')
1121 private_192 = IPv4Network('192.168.0.0/16')
1122 if isinstance(self, _BaseAddress):
1123 return (self in private_10 or self in private_172 or
1124 self in private_192)
1125 else:
1126 return ((self.network_address in private_10 and
1127 self.broadcast_address in private_10) or
1128 (self.network_address in private_172 and
1129 self.broadcast_address in private_172) or
1130 (self.network_address in private_192 and
1131 self.broadcast_address in private_192))
1132
1133 @property
1134 def is_multicast(self):
1135 """Test if the address is reserved for multicast use.
1136
1137 Returns:
1138 A boolean, True if the address is multicast.
1139 See RFC 3171 for details.
1140
1141 """
1142 multicast_network = IPv4Network('224.0.0.0/4')
1143 if isinstance(self, _BaseAddress):
1144 return self in IPv4Network('224.0.0.0/4')
1145 return (self.network_address in multicast_network and
1146 self.broadcast_address in multicast_network)
1147
1148 @property
1149 def is_unspecified(self):
1150 """Test if the address is unspecified.
1151
1152 Returns:
1153 A boolean, True if this is the unspecified address as defined in
1154 RFC 5735 3.
1155
1156 """
1157 unspecified_address = IPv4Address('0.0.0.0')
1158 if isinstance(self, _BaseAddress):
Hynek Schlawackbcd30442012-06-04 14:19:39 +02001159 return self == unspecified_address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001160 return (self.network_address == self.broadcast_address ==
1161 unspecified_address)
1162
1163 @property
1164 def is_loopback(self):
1165 """Test if the address is a loopback address.
1166
1167 Returns:
1168 A boolean, True if the address is a loopback per RFC 3330.
1169
1170 """
1171 loopback_address = IPv4Network('127.0.0.0/8')
1172 if isinstance(self, _BaseAddress):
1173 return self in loopback_address
1174
1175 return (self.network_address in loopback_address and
1176 self.broadcast_address in loopback_address)
1177
1178 @property
1179 def is_link_local(self):
1180 """Test if the address is reserved for link-local.
1181
1182 Returns:
1183 A boolean, True if the address is link-local per RFC 3927.
1184
1185 """
1186 linklocal_network = IPv4Network('169.254.0.0/16')
1187 if isinstance(self, _BaseAddress):
1188 return self in linklocal_network
1189 return (self.network_address in linklocal_network and
1190 self.broadcast_address in linklocal_network)
1191
1192
1193class IPv4Address(_BaseV4, _BaseAddress):
1194
1195 """Represent and manipulate single IPv4 Addresses."""
1196
1197 def __init__(self, address):
1198
1199 """
1200 Args:
1201 address: A string or integer representing the IP
1202
1203 Additionally, an integer can be passed, so
1204 IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1205 or, more generally
1206 IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1207 IPv4Address('192.0.2.1')
1208
1209 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001210 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001211
1212 """
1213 _BaseAddress.__init__(self, address)
1214 _BaseV4.__init__(self, address)
1215
1216 # Efficient constructor from integer.
1217 if isinstance(address, int):
1218 self._ip = address
1219 if address < 0 or address > self._ALL_ONES:
1220 raise AddressValueError(address)
1221 return
1222
1223 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001224 if isinstance(address, bytes):
1225 if len(address) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001226 msg = "Packed address %r must be exactly 4 bytes"
1227 raise AddressValueError(msg % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001228 self._ip = struct.unpack('!I', address)[0]
1229 return
1230
1231 # Assume input argument to be string or any object representation
1232 # which converts into a formatted IP string.
1233 addr_str = str(address)
1234 self._ip = self._ip_int_from_string(addr_str)
1235
1236 @property
1237 def packed(self):
1238 """The binary representation of this address."""
1239 return v4_int_to_packed(self._ip)
1240
1241
1242class IPv4Interface(IPv4Address):
1243
Nick Coghlandc9b2552012-05-20 21:01:57 +10001244 def __init__(self, address):
1245 if isinstance(address, (bytes, int)):
1246 IPv4Address.__init__(self, address)
1247 self.network = IPv4Network(self._ip)
1248 self._prefixlen = self._max_prefixlen
1249 return
1250
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001251 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001252 IPv4Address.__init__(self, addr[0])
1253
1254 self.network = IPv4Network(address, strict=False)
1255 self._prefixlen = self.network._prefixlen
1256
1257 self.netmask = self.network.netmask
1258 self.hostmask = self.network.hostmask
1259
Nick Coghlandc9b2552012-05-20 21:01:57 +10001260 def __str__(self):
1261 return '%s/%d' % (self._string_from_ip_int(self._ip),
1262 self.network.prefixlen)
1263
1264 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001265 address_equal = IPv4Address.__eq__(self, other)
1266 if not address_equal or address_equal is NotImplemented:
1267 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001268 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001269 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001270 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001271 # An interface with an associated network is NOT the
1272 # same as an unassociated address. That's why the hash
1273 # takes the extra info into account.
1274 return False
1275
1276 def __lt__(self, other):
1277 address_less = IPv4Address.__lt__(self, other)
1278 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001279 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001280 try:
1281 return self.network < other.network
1282 except AttributeError:
1283 # We *do* allow addresses and interfaces to be sorted. The
1284 # unassociated address is considered less than all interfaces.
1285 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001286
1287 def __hash__(self):
1288 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1289
Nick Coghlandc9b2552012-05-20 21:01:57 +10001290 @property
1291 def prefixlen(self):
1292 return self._prefixlen
1293
1294 @property
1295 def ip(self):
1296 return IPv4Address(self._ip)
1297
1298 @property
1299 def with_prefixlen(self):
1300 return self
1301
1302 @property
1303 def with_netmask(self):
1304 return '%s/%s' % (self._string_from_ip_int(self._ip),
1305 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001306
Nick Coghlandc9b2552012-05-20 21:01:57 +10001307 @property
1308 def with_hostmask(self):
1309 return '%s/%s' % (self._string_from_ip_int(self._ip),
1310 self.hostmask)
1311
1312
1313class IPv4Network(_BaseV4, _BaseNetwork):
1314
1315 """This class represents and manipulates 32-bit IPv4 network + addresses..
1316
1317 Attributes: [examples for IPv4Network('192.0.2.0/27')]
1318 .network_address: IPv4Address('192.0.2.0')
1319 .hostmask: IPv4Address('0.0.0.31')
1320 .broadcast_address: IPv4Address('192.0.2.32')
1321 .netmask: IPv4Address('255.255.255.224')
1322 .prefixlen: 27
1323
1324 """
Nick Coghlan51c30672012-05-27 00:25:58 +10001325 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001326 _address_class = IPv4Address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001327
Nick Coghlandc9b2552012-05-20 21:01:57 +10001328 def __init__(self, address, strict=True):
1329
1330 """Instantiate a new IPv4 network object.
1331
1332 Args:
1333 address: A string or integer representing the IP [& network].
1334 '192.0.2.0/24'
1335 '192.0.2.0/255.255.255.0'
1336 '192.0.0.2/0.0.0.255'
1337 are all functionally the same in IPv4. Similarly,
1338 '192.0.2.1'
1339 '192.0.2.1/255.255.255.255'
1340 '192.0.2.1/32'
1341 are also functionaly equivalent. That is to say, failing to
1342 provide a subnetmask will create an object with a mask of /32.
1343
1344 If the mask (portion after the / in the argument) is given in
1345 dotted quad form, it is treated as a netmask if it starts with a
1346 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1347 starts with a zero field (e.g. 0.255.255.255 == /8), with the
1348 single exception of an all-zero mask which is treated as a
1349 netmask == /0. If no mask is given, a default of /32 is used.
1350
1351 Additionally, an integer can be passed, so
1352 IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1353 or, more generally
1354 IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1355 IPv4Interface('192.0.2.1')
1356
1357 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001358 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001359 NetmaskValueError: If the netmask isn't valid for
1360 an IPv4 address.
Sandro Tosib4386d32012-06-02 17:14:22 +02001361 ValueError: If strict is True and a network address is not
Nick Coghlandc9b2552012-05-20 21:01:57 +10001362 supplied.
1363
1364 """
1365
1366 _BaseV4.__init__(self, address)
1367 _BaseNetwork.__init__(self, address)
1368
1369 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001370 if isinstance(address, bytes):
1371 if len(address) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001372 msg = "Packed address %r must be exactly 4 bytes"
1373 raise AddressValueError(msg % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001374 self.network_address = IPv4Address(
1375 struct.unpack('!I', address)[0])
1376 self._prefixlen = self._max_prefixlen
1377 self.netmask = IPv4Address(self._ALL_ONES)
1378 #fixme: address/network test here
1379 return
1380
1381 # Efficient constructor from integer.
1382 if isinstance(address, int):
1383 self._prefixlen = self._max_prefixlen
1384 self.netmask = IPv4Address(self._ALL_ONES)
1385 if address < 0 or address > self._ALL_ONES:
1386 raise AddressValueError(address)
1387 self.network_address = IPv4Address(address)
1388 #fixme: address/network test here.
1389 return
1390
1391 # Assume input argument to be string or any object representation
1392 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001393 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001394 self.network_address = IPv4Address(self._ip_int_from_string(addr[0]))
1395
Nick Coghlandc9b2552012-05-20 21:01:57 +10001396 if len(addr) == 2:
1397 mask = addr[1].split('.')
1398
1399 if len(mask) == 4:
1400 # We have dotted decimal netmask.
1401 if self._is_valid_netmask(addr[1]):
1402 self.netmask = IPv4Address(self._ip_int_from_string(
1403 addr[1]))
1404 elif self._is_hostmask(addr[1]):
1405 self.netmask = IPv4Address(
1406 self._ip_int_from_string(addr[1]) ^ self._ALL_ONES)
1407 else:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001408 raise NetmaskValueError('%r is not a valid netmask'
Nick Coghlandc9b2552012-05-20 21:01:57 +10001409 % addr[1])
1410
1411 self._prefixlen = self._prefix_from_ip_int(int(self.netmask))
1412 else:
1413 # We have a netmask in prefix length form.
1414 if not self._is_valid_netmask(addr[1]):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001415 raise NetmaskValueError('%r is not a valid netmask'
1416 % addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001417 self._prefixlen = int(addr[1])
1418 self.netmask = IPv4Address(self._ip_int_from_prefix(
1419 self._prefixlen))
1420 else:
1421 self._prefixlen = self._max_prefixlen
1422 self.netmask = IPv4Address(self._ip_int_from_prefix(
1423 self._prefixlen))
1424
1425 if strict:
1426 if (IPv4Address(int(self.network_address) & int(self.netmask)) !=
1427 self.network_address):
1428 raise ValueError('%s has host bits set' % self)
1429 self.network_address = IPv4Address(int(self.network_address) &
1430 int(self.netmask))
1431
1432 if self._prefixlen == (self._max_prefixlen - 1):
1433 self.hosts = self.__iter__
1434
Nick Coghlandc9b2552012-05-20 21:01:57 +10001435
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001436class _BaseV6:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001437
1438 """Base IPv6 object.
1439
1440 The following methods are used by IPv6 objects in both single IP
1441 addresses and networks.
1442
1443 """
1444
1445 _ALL_ONES = (2**IPV6LENGTH) - 1
1446 _HEXTET_COUNT = 8
1447 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
1448
1449 def __init__(self, address):
1450 self._version = 6
1451 self._max_prefixlen = IPV6LENGTH
1452
1453 def _ip_int_from_string(self, ip_str):
1454 """Turn an IPv6 ip_str into an integer.
1455
1456 Args:
1457 ip_str: A string, the IPv6 ip_str.
1458
1459 Returns:
1460 An int, the IPv6 address
1461
1462 Raises:
1463 AddressValueError: if ip_str isn't a valid IPv6 Address.
1464
1465 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001466 if not ip_str:
1467 raise AddressValueError('Address cannot be empty')
1468
Nick Coghlandc9b2552012-05-20 21:01:57 +10001469 parts = ip_str.split(':')
1470
1471 # An IPv6 address needs at least 2 colons (3 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001472 _min_parts = 3
1473 if len(parts) < _min_parts:
1474 msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
1475 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001476
1477 # If the address has an IPv4-style suffix, convert it to hexadecimal.
1478 if '.' in parts[-1]:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001479 try:
1480 ipv4_int = IPv4Address(parts.pop())._ip
1481 except AddressValueError as exc:
1482 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001483 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1484 parts.append('%x' % (ipv4_int & 0xFFFF))
1485
1486 # An IPv6 address can't have more than 8 colons (9 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001487 # The extra colon comes from using the "::" notation for a single
1488 # leading or trailing zero part.
1489 _max_parts = self._HEXTET_COUNT + 1
1490 if len(parts) > _max_parts:
1491 msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
1492 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001493
1494 # Disregarding the endpoints, find '::' with nothing in between.
1495 # This indicates that a run of zeroes has been skipped.
Nick Coghlan7319f692012-07-07 21:43:30 +10001496 skip_index = None
1497 for i in range(1, len(parts) - 1):
1498 if not parts[i]:
1499 if skip_index is not None:
1500 # Can't have more than one '::'
1501 msg = "At most one '::' permitted in %r" % ip_str
1502 raise AddressValueError(msg)
1503 skip_index = i
Nick Coghlandc9b2552012-05-20 21:01:57 +10001504
1505 # parts_hi is the number of parts to copy from above/before the '::'
1506 # parts_lo is the number of parts to copy from below/after the '::'
1507 if skip_index is not None:
1508 # If we found a '::', then check if it also covers the endpoints.
1509 parts_hi = skip_index
1510 parts_lo = len(parts) - skip_index - 1
1511 if not parts[0]:
1512 parts_hi -= 1
1513 if parts_hi:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001514 msg = "Leading ':' only permitted as part of '::' in %r"
1515 raise AddressValueError(msg % ip_str) # ^: requires ^::
Nick Coghlandc9b2552012-05-20 21:01:57 +10001516 if not parts[-1]:
1517 parts_lo -= 1
1518 if parts_lo:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001519 msg = "Trailing ':' only permitted as part of '::' in %r"
1520 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001521 parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo)
1522 if parts_skipped < 1:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001523 msg = "Expected at most %d other parts with '::' in %r"
1524 raise AddressValueError(msg % (self._HEXTET_COUNT-1, ip_str))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001525 else:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001526 # Otherwise, allocate the entire address to parts_hi. The
1527 # endpoints could still be empty, but _parse_hextet() will check
1528 # for that.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001529 if len(parts) != self._HEXTET_COUNT:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001530 msg = "Exactly %d parts expected without '::' in %r"
1531 raise AddressValueError(msg % (self._HEXTET_COUNT, ip_str))
1532 if not parts[0]:
1533 msg = "Leading ':' only permitted as part of '::' in %r"
1534 raise AddressValueError(msg % ip_str) # ^: requires ^::
1535 if not parts[-1]:
1536 msg = "Trailing ':' only permitted as part of '::' in %r"
1537 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001538 parts_hi = len(parts)
1539 parts_lo = 0
1540 parts_skipped = 0
1541
1542 try:
1543 # Now, parse the hextets into a 128-bit integer.
1544 ip_int = 0
1545 for i in range(parts_hi):
1546 ip_int <<= 16
1547 ip_int |= self._parse_hextet(parts[i])
1548 ip_int <<= 16 * parts_skipped
1549 for i in range(-parts_lo, 0):
1550 ip_int <<= 16
1551 ip_int |= self._parse_hextet(parts[i])
1552 return ip_int
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001553 except ValueError as exc:
1554 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001555
1556 def _parse_hextet(self, hextet_str):
1557 """Convert an IPv6 hextet string into an integer.
1558
1559 Args:
1560 hextet_str: A string, the number to parse.
1561
1562 Returns:
1563 The hextet as an integer.
1564
1565 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001566 ValueError: if the input isn't strictly a hex number from
1567 [0..FFFF].
Nick Coghlandc9b2552012-05-20 21:01:57 +10001568
1569 """
1570 # Whitelist the characters, since int() allows a lot of bizarre stuff.
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001571 # Higher level wrappers convert these to more informative errors
Nick Coghlandc9b2552012-05-20 21:01:57 +10001572 if not self._HEX_DIGITS.issuperset(hextet_str):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001573 raise ValueError("Only hex digits permitted in %r" % hextet_str)
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001574 if len(hextet_str) > 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001575 msg = "At most 4 characters permitted in %r"
1576 raise ValueError(msg % hextet_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001577 hextet_int = int(hextet_str, 16)
1578 if hextet_int > 0xFFFF:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001579 # This is unreachable due to the string length check above
Nick Coghlanb582ecc2012-07-07 22:15:22 +10001580 msg = "Part 0x%X (> 0xFFFF) not permitted"
1581 raise ValueError(msg % hextet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001582 return hextet_int
1583
1584 def _compress_hextets(self, hextets):
1585 """Compresses a list of hextets.
1586
1587 Compresses a list of strings, replacing the longest continuous
1588 sequence of "0" in the list with "" and adding empty strings at
1589 the beginning or at the end of the string such that subsequently
1590 calling ":".join(hextets) will produce the compressed version of
1591 the IPv6 address.
1592
1593 Args:
1594 hextets: A list of strings, the hextets to compress.
1595
1596 Returns:
1597 A list of strings.
1598
1599 """
1600 best_doublecolon_start = -1
1601 best_doublecolon_len = 0
1602 doublecolon_start = -1
1603 doublecolon_len = 0
1604 for index in range(len(hextets)):
1605 if hextets[index] == '0':
1606 doublecolon_len += 1
1607 if doublecolon_start == -1:
1608 # Start of a sequence of zeros.
1609 doublecolon_start = index
1610 if doublecolon_len > best_doublecolon_len:
1611 # This is the longest sequence of zeros so far.
1612 best_doublecolon_len = doublecolon_len
1613 best_doublecolon_start = doublecolon_start
1614 else:
1615 doublecolon_len = 0
1616 doublecolon_start = -1
1617
1618 if best_doublecolon_len > 1:
1619 best_doublecolon_end = (best_doublecolon_start +
1620 best_doublecolon_len)
1621 # For zeros at the end of the address.
1622 if best_doublecolon_end == len(hextets):
1623 hextets += ['']
1624 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1625 # For zeros at the beginning of the address.
1626 if best_doublecolon_start == 0:
1627 hextets = [''] + hextets
1628
1629 return hextets
1630
1631 def _string_from_ip_int(self, ip_int=None):
1632 """Turns a 128-bit integer into hexadecimal notation.
1633
1634 Args:
1635 ip_int: An integer, the IP address.
1636
1637 Returns:
1638 A string, the hexadecimal representation of the address.
1639
1640 Raises:
1641 ValueError: The address is bigger than 128 bits of all ones.
1642
1643 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001644 if ip_int is None:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001645 ip_int = int(self._ip)
1646
1647 if ip_int > self._ALL_ONES:
1648 raise ValueError('IPv6 address is too large')
1649
1650 hex_str = '%032x' % ip_int
Nick Coghlan7319f692012-07-07 21:43:30 +10001651 hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001652
1653 hextets = self._compress_hextets(hextets)
1654 return ':'.join(hextets)
1655
1656 def _explode_shorthand_ip_string(self):
1657 """Expand a shortened IPv6 address.
1658
1659 Args:
1660 ip_str: A string, the IPv6 address.
1661
1662 Returns:
1663 A string, the expanded IPv6 address.
1664
1665 """
1666 if isinstance(self, IPv6Network):
1667 ip_str = str(self.network_address)
1668 elif isinstance(self, IPv6Interface):
1669 ip_str = str(self.ip)
1670 else:
1671 ip_str = str(self)
1672
1673 ip_int = self._ip_int_from_string(ip_str)
Nick Coghlan7319f692012-07-07 21:43:30 +10001674 hex_str = '%032x' % ip_int
1675 parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001676 if isinstance(self, (_BaseNetwork, IPv6Interface)):
1677 return '%s/%d' % (':'.join(parts), self.prefixlen)
1678 return ':'.join(parts)
1679
1680 @property
1681 def max_prefixlen(self):
1682 return self._max_prefixlen
1683
1684 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001685 def version(self):
1686 return self._version
1687
1688 @property
1689 def is_multicast(self):
1690 """Test if the address is reserved for multicast use.
1691
1692 Returns:
1693 A boolean, True if the address is a multicast address.
1694 See RFC 2373 2.7 for details.
1695
1696 """
1697 multicast_network = IPv6Network('ff00::/8')
1698 if isinstance(self, _BaseAddress):
1699 return self in multicast_network
1700 return (self.network_address in multicast_network and
1701 self.broadcast_address in multicast_network)
1702
1703 @property
1704 def is_reserved(self):
1705 """Test if the address is otherwise IETF reserved.
1706
1707 Returns:
1708 A boolean, True if the address is within one of the
1709 reserved IPv6 Network ranges.
1710
1711 """
1712 reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'),
1713 IPv6Network('200::/7'), IPv6Network('400::/6'),
1714 IPv6Network('800::/5'), IPv6Network('1000::/4'),
1715 IPv6Network('4000::/3'), IPv6Network('6000::/3'),
1716 IPv6Network('8000::/3'), IPv6Network('A000::/3'),
1717 IPv6Network('C000::/3'), IPv6Network('E000::/4'),
1718 IPv6Network('F000::/5'), IPv6Network('F800::/6'),
1719 IPv6Network('FE00::/9')]
1720
1721 if isinstance(self, _BaseAddress):
Nick Coghlan7319f692012-07-07 21:43:30 +10001722 return any(self in x for x in reserved_networks)
1723 return any(self.network_address in x and self.broadcast_address in x
1724 for x in reserved_networks)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001725
1726 @property
1727 def is_link_local(self):
1728 """Test if the address is reserved for link-local.
1729
1730 Returns:
1731 A boolean, True if the address is reserved per RFC 4291.
1732
1733 """
1734 linklocal_network = IPv6Network('fe80::/10')
1735 if isinstance(self, _BaseAddress):
1736 return self in linklocal_network
1737 return (self.network_address in linklocal_network and
1738 self.broadcast_address in linklocal_network)
1739
1740 @property
1741 def is_site_local(self):
1742 """Test if the address is reserved for site-local.
1743
1744 Note that the site-local address space has been deprecated by RFC 3879.
1745 Use is_private to test if this address is in the space of unique local
1746 addresses as defined by RFC 4193.
1747
1748 Returns:
1749 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1750
1751 """
1752 sitelocal_network = IPv6Network('fec0::/10')
1753 if isinstance(self, _BaseAddress):
1754 return self in sitelocal_network
1755 return (self.network_address in sitelocal_network and
1756 self.broadcast_address in sitelocal_network)
1757
1758 @property
1759 def is_private(self):
1760 """Test if this address is allocated for private networks.
1761
1762 Returns:
1763 A boolean, True if the address is reserved per RFC 4193.
1764
1765 """
1766 private_network = IPv6Network('fc00::/7')
1767 if isinstance(self, _BaseAddress):
1768 return self in private_network
1769 return (self.network_address in private_network and
1770 self.broadcast_address in private_network)
1771
Nick Coghlandc9b2552012-05-20 21:01:57 +10001772 @property
1773 def ipv4_mapped(self):
1774 """Return the IPv4 mapped address.
1775
1776 Returns:
1777 If the IPv6 address is a v4 mapped address, return the
1778 IPv4 mapped address. Return None otherwise.
1779
1780 """
1781 if (self._ip >> 32) != 0xFFFF:
1782 return None
1783 return IPv4Address(self._ip & 0xFFFFFFFF)
1784
1785 @property
1786 def teredo(self):
1787 """Tuple of embedded teredo IPs.
1788
1789 Returns:
1790 Tuple of the (server, client) IPs or None if the address
1791 doesn't appear to be a teredo address (doesn't start with
1792 2001::/32)
1793
1794 """
1795 if (self._ip >> 96) != 0x20010000:
1796 return None
1797 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
1798 IPv4Address(~self._ip & 0xFFFFFFFF))
1799
1800 @property
1801 def sixtofour(self):
1802 """Return the IPv4 6to4 embedded address.
1803
1804 Returns:
1805 The IPv4 6to4-embedded address if present or None if the
1806 address doesn't appear to contain a 6to4 embedded address.
1807
1808 """
1809 if (self._ip >> 112) != 0x2002:
1810 return None
1811 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
1812
1813 @property
1814 def is_unspecified(self):
1815 """Test if the address is unspecified.
1816
1817 Returns:
1818 A boolean, True if this is the unspecified address as defined in
1819 RFC 2373 2.5.2.
1820
1821 """
1822 if isinstance(self, (IPv6Network, IPv6Interface)):
1823 return int(self.network_address) == 0 and getattr(
1824 self, '_prefixlen', 128) == 128
1825 return self._ip == 0
1826
1827 @property
1828 def is_loopback(self):
1829 """Test if the address is a loopback address.
1830
1831 Returns:
1832 A boolean, True if the address is a loopback address as defined in
1833 RFC 2373 2.5.3.
1834
1835 """
1836 if isinstance(self, IPv6Network):
Nick Coghlan2c589102012-05-27 01:03:25 +10001837 return int(self) == 1 and getattr(
Nick Coghlandc9b2552012-05-20 21:01:57 +10001838 self, '_prefixlen', 128) == 128
1839 elif isinstance(self, IPv6Interface):
1840 return int(self.network.network_address) == 1 and getattr(
1841 self, '_prefixlen', 128) == 128
1842 return self._ip == 1
1843
1844
1845class IPv6Address(_BaseV6, _BaseAddress):
1846
Sandro Tosib95c6342012-05-23 23:17:22 +02001847 """Represent and manipulate single IPv6 Addresses."""
Nick Coghlandc9b2552012-05-20 21:01:57 +10001848
1849 def __init__(self, address):
1850 """Instantiate a new IPv6 address object.
1851
1852 Args:
1853 address: A string or integer representing the IP
1854
1855 Additionally, an integer can be passed, so
1856 IPv6Address('2001:db8::') ==
1857 IPv6Address(42540766411282592856903984951653826560)
1858 or, more generally
1859 IPv6Address(int(IPv6Address('2001:db8::'))) ==
1860 IPv6Address('2001:db8::')
1861
1862 Raises:
1863 AddressValueError: If address isn't a valid IPv6 address.
1864
1865 """
1866 _BaseAddress.__init__(self, address)
1867 _BaseV6.__init__(self, address)
1868
1869 # Efficient constructor from integer.
1870 if isinstance(address, int):
1871 self._ip = address
1872 if address < 0 or address > self._ALL_ONES:
1873 raise AddressValueError(address)
1874 return
1875
1876 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001877 if isinstance(address, bytes):
1878 if len(address) != 16:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001879 msg = "Packed address %r must be exactly 16 bytes"
1880 raise AddressValueError(msg % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001881 tmp = struct.unpack('!QQ', address)
1882 self._ip = (tmp[0] << 64) | tmp[1]
1883 return
1884
1885 # Assume input argument to be string or any object representation
1886 # which converts into a formatted IP string.
1887 addr_str = str(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001888 self._ip = self._ip_int_from_string(addr_str)
1889
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001890 @property
1891 def packed(self):
1892 """The binary representation of this address."""
1893 return v6_int_to_packed(self._ip)
1894
Nick Coghlandc9b2552012-05-20 21:01:57 +10001895
1896class IPv6Interface(IPv6Address):
1897
1898 def __init__(self, address):
1899 if isinstance(address, (bytes, int)):
1900 IPv6Address.__init__(self, address)
1901 self.network = IPv6Network(self._ip)
1902 self._prefixlen = self._max_prefixlen
1903 return
1904
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001905 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001906 IPv6Address.__init__(self, addr[0])
1907 self.network = IPv6Network(address, strict=False)
1908 self.netmask = self.network.netmask
1909 self._prefixlen = self.network._prefixlen
1910 self.hostmask = self.network.hostmask
1911
Nick Coghlandc9b2552012-05-20 21:01:57 +10001912 def __str__(self):
1913 return '%s/%d' % (self._string_from_ip_int(self._ip),
1914 self.network.prefixlen)
1915
1916 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001917 address_equal = IPv6Address.__eq__(self, other)
1918 if not address_equal or address_equal is NotImplemented:
1919 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001920 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001921 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001922 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001923 # An interface with an associated network is NOT the
1924 # same as an unassociated address. That's why the hash
1925 # takes the extra info into account.
1926 return False
1927
1928 def __lt__(self, other):
1929 address_less = IPv6Address.__lt__(self, other)
1930 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001931 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001932 try:
1933 return self.network < other.network
1934 except AttributeError:
1935 # We *do* allow addresses and interfaces to be sorted. The
1936 # unassociated address is considered less than all interfaces.
1937 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001938
1939 def __hash__(self):
1940 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1941
1942 @property
1943 def prefixlen(self):
1944 return self._prefixlen
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001945
Nick Coghlandc9b2552012-05-20 21:01:57 +10001946 @property
1947 def ip(self):
1948 return IPv6Address(self._ip)
1949
1950 @property
1951 def with_prefixlen(self):
1952 return self
1953
1954 @property
1955 def with_netmask(self):
1956 return self.with_prefixlen
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001957
Nick Coghlandc9b2552012-05-20 21:01:57 +10001958 @property
1959 def with_hostmask(self):
1960 return '%s/%s' % (self._string_from_ip_int(self._ip),
1961 self.hostmask)
1962
1963
1964class IPv6Network(_BaseV6, _BaseNetwork):
1965
1966 """This class represents and manipulates 128-bit IPv6 networks.
1967
1968 Attributes: [examples for IPv6('2001:db8::1000/124')]
1969 .network_address: IPv6Address('2001:db8::1000')
1970 .hostmask: IPv6Address('::f')
1971 .broadcast_address: IPv6Address('2001:db8::100f')
1972 .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
1973 .prefixlen: 124
1974
1975 """
1976
Nick Coghlan51c30672012-05-27 00:25:58 +10001977 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001978 _address_class = IPv6Address
1979
Nick Coghlandc9b2552012-05-20 21:01:57 +10001980 def __init__(self, address, strict=True):
1981 """Instantiate a new IPv6 Network object.
1982
1983 Args:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001984 address: A string or integer representing the IPv6 network or the
1985 IP and prefix/netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001986 '2001:db8::/128'
1987 '2001:db8:0000:0000:0000:0000:0000:0000/128'
1988 '2001:db8::'
1989 are all functionally the same in IPv6. That is to say,
1990 failing to provide a subnetmask will create an object with
1991 a mask of /128.
1992
1993 Additionally, an integer can be passed, so
1994 IPv6Network('2001:db8::') ==
1995 IPv6Network(42540766411282592856903984951653826560)
1996 or, more generally
1997 IPv6Network(int(IPv6Network('2001:db8::'))) ==
1998 IPv6Network('2001:db8::')
1999
2000 strict: A boolean. If true, ensure that we have been passed
2001 A true network address, eg, 2001:db8::1000/124 and not an
2002 IP address on a network, eg, 2001:db8::1/124.
2003
2004 Raises:
2005 AddressValueError: If address isn't a valid IPv6 address.
2006 NetmaskValueError: If the netmask isn't valid for
2007 an IPv6 address.
2008 ValueError: If strict was True and a network address was not
2009 supplied.
2010
2011 """
2012 _BaseV6.__init__(self, address)
2013 _BaseNetwork.__init__(self, address)
2014
2015 # Efficient constructor from integer.
2016 if isinstance(address, int):
2017 if address < 0 or address > self._ALL_ONES:
2018 raise AddressValueError(address)
2019 self.network_address = IPv6Address(address)
2020 self._prefixlen = self._max_prefixlen
2021 self.netmask = IPv6Address(self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002022 return
2023
2024 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10002025 if isinstance(address, bytes):
2026 if len(address) != 16:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002027 msg = "Packed address %r must be exactly 16 bytes"
2028 raise AddressValueError(msg % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002029 tmp = struct.unpack('!QQ', address)
2030 self.network_address = IPv6Address((tmp[0] << 64) | tmp[1])
2031 self._prefixlen = self._max_prefixlen
2032 self.netmask = IPv6Address(self._ALL_ONES)
Hynek Schlawacked36b2e2012-06-08 15:21:21 +02002033 return
Nick Coghlandc9b2552012-05-20 21:01:57 +10002034
2035 # Assume input argument to be string or any object representation
2036 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002037 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002038
2039 self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))
2040
2041 if len(addr) == 2:
2042 if self._is_valid_netmask(addr[1]):
2043 self._prefixlen = int(addr[1])
2044 else:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002045 raise NetmaskValueError('%r is not a valid netmask'
2046 % addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10002047 else:
2048 self._prefixlen = self._max_prefixlen
2049
2050 self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen))
2051 if strict:
2052 if (IPv6Address(int(self.network_address) & int(self.netmask)) !=
2053 self.network_address):
Nick Coghlan912238e2012-07-07 13:34:50 +10002054 raise ValueError('%s has host bits set' % self)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002055 self.network_address = IPv6Address(int(self.network_address) &
2056 int(self.netmask))
2057
2058 if self._prefixlen == (self._max_prefixlen - 1):
2059 self.hosts = self.__iter__
2060
Nick Coghlandc9b2552012-05-20 21:01:57 +10002061 def _is_valid_netmask(self, prefixlen):
2062 """Verify that the netmask/prefixlen is valid.
2063
2064 Args:
2065 prefixlen: A string, the netmask in prefix length format.
2066
2067 Returns:
2068 A boolean, True if the prefix represents a valid IPv6
2069 netmask.
2070
2071 """
2072 try:
2073 prefixlen = int(prefixlen)
2074 except ValueError:
2075 return False
2076 return 0 <= prefixlen <= self._max_prefixlen