blob: b1e07fc992e5edecbcbe37428e04e9047cf6fccd [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
15
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
Hynek Schlawackc4b78a32012-06-01 11:48:32 +0200408class _IPAddressBase:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000409
410 """The mother class."""
411
412 @property
413 def exploded(self):
414 """Return the longhand version of the IP address as a string."""
415 return self._explode_shorthand_ip_string()
416
417 @property
418 def compressed(self):
419 """Return the shorthand version of the IP address as a string."""
420 return str(self)
421
Nick Coghland9722652012-06-17 16:33:00 +1000422 @property
423 def version(self):
424 msg = '%200s has no version specified' % (type(self),)
425 raise NotImplementedError(msg)
426
Nick Coghlandc9b2552012-05-20 21:01:57 +1000427 def _ip_int_from_prefix(self, prefixlen=None):
428 """Turn the prefix length netmask into a int for comparison.
429
430 Args:
431 prefixlen: An integer, the prefix length.
432
433 Returns:
434 An integer.
435
436 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +0200437 if prefixlen is None:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000438 prefixlen = self._prefixlen
439 return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen)
440
441 def _prefix_from_ip_int(self, ip_int, mask=32):
442 """Return prefix length from the decimal netmask.
443
444 Args:
445 ip_int: An integer, the IP address.
446 mask: The netmask. Defaults to 32.
447
448 Returns:
449 An integer, the prefix length.
450
451 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000452 return mask - _count_righthand_zero_bits(ip_int, mask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000453
454 def _ip_string_from_prefix(self, prefixlen=None):
455 """Turn a prefix length into a dotted decimal string.
456
457 Args:
458 prefixlen: An integer, the netmask prefix length.
459
460 Returns:
461 A string, the dotted decimal netmask string.
462
463 """
464 if not prefixlen:
465 prefixlen = self._prefixlen
466 return self._string_from_ip_int(self._ip_int_from_prefix(prefixlen))
467
468
469class _BaseAddress(_IPAddressBase):
470
471 """A generic IP object.
472
473 This IP class contains the version independent methods which are
474 used by single IP addresses.
475
476 """
477
478 def __init__(self, address):
479 if (not isinstance(address, bytes)
480 and '/' in str(address)):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000481 raise AddressValueError("Unexpected '/' in %r" % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000482
483 def __index__(self):
484 return self._ip
485
486 def __int__(self):
487 return self._ip
488
Nick Coghlandc9b2552012-05-20 21:01:57 +1000489 def __eq__(self, other):
490 try:
491 return (self._ip == other._ip
492 and self._version == other._version)
493 except AttributeError:
494 return NotImplemented
495
496 def __ne__(self, other):
497 eq = self.__eq__(other)
498 if eq is NotImplemented:
499 return NotImplemented
500 return not eq
501
502 def __le__(self, other):
503 gt = self.__gt__(other)
504 if gt is NotImplemented:
505 return NotImplemented
506 return not gt
507
508 def __ge__(self, other):
509 lt = self.__lt__(other)
510 if lt is NotImplemented:
511 return NotImplemented
512 return not lt
513
514 def __lt__(self, other):
515 if self._version != other._version:
516 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000517 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000518 if not isinstance(other, _BaseAddress):
519 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000520 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000521 if self._ip != other._ip:
522 return self._ip < other._ip
523 return False
524
525 def __gt__(self, other):
526 if self._version != other._version:
527 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000528 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000529 if not isinstance(other, _BaseAddress):
530 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000531 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000532 if self._ip != other._ip:
533 return self._ip > other._ip
534 return False
535
536 # Shorthand for Integer addition and subtraction. This is not
537 # meant to ever support addition/subtraction of addresses.
538 def __add__(self, other):
539 if not isinstance(other, int):
540 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000541 return self.__class__(int(self) + other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000542
543 def __sub__(self, other):
544 if not isinstance(other, int):
545 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000546 return self.__class__(int(self) - other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000547
548 def __repr__(self):
549 return '%s(%r)' % (self.__class__.__name__, str(self))
550
551 def __str__(self):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200552 return str(self._string_from_ip_int(self._ip))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000553
554 def __hash__(self):
555 return hash(hex(int(self._ip)))
556
557 def _get_address_key(self):
558 return (self._version, self)
559
Nick Coghlandc9b2552012-05-20 21:01:57 +1000560
561class _BaseNetwork(_IPAddressBase):
562
Nick Coghlan51c30672012-05-27 00:25:58 +1000563 """A generic IP network object.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000564
565 This IP class contains the version independent methods which are
566 used by networks.
567
568 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000569 def __init__(self, address):
570 self._cache = {}
571
572 def __index__(self):
573 return int(self.network_address) ^ self.prefixlen
574
575 def __int__(self):
576 return int(self.network_address)
577
578 def __repr__(self):
579 return '%s(%r)' % (self.__class__.__name__, str(self))
580
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200581 def __str__(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000582 return '%s/%d' % (self.network_address, self.prefixlen)
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200583
Nick Coghlandc9b2552012-05-20 21:01:57 +1000584 def hosts(self):
585 """Generate Iterator over usable hosts in a network.
586
Sandro Tosib95c6342012-05-23 23:17:22 +0200587 This is like __iter__ except it doesn't return the network
588 or broadcast addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000589
590 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000591 network = int(self.network_address)
592 broadcast = int(self.broadcast_address)
593 for x in range(network + 1, broadcast):
594 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000595
596 def __iter__(self):
Nick Coghlan7319f692012-07-07 21:43:30 +1000597 network = int(self.network_address)
598 broadcast = int(self.broadcast_address)
599 for x in range(network, broadcast + 1):
600 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000601
602 def __getitem__(self, n):
603 network = int(self.network_address)
604 broadcast = int(self.broadcast_address)
605 if n >= 0:
606 if network + n > broadcast:
607 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000608 return self._address_class(network + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000609 else:
610 n += 1
611 if broadcast + n < network:
612 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000613 return self._address_class(broadcast + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000614
615 def __lt__(self, other):
616 if self._version != other._version:
617 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000618 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000619 if not isinstance(other, _BaseNetwork):
620 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000621 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000622 if self.network_address != other.network_address:
623 return self.network_address < other.network_address
624 if self.netmask != other.netmask:
625 return self.netmask < other.netmask
626 return False
627
628 def __gt__(self, other):
629 if self._version != other._version:
630 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000631 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000632 if not isinstance(other, _BaseNetwork):
633 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000634 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000635 if self.network_address != other.network_address:
636 return self.network_address > other.network_address
637 if self.netmask != other.netmask:
638 return self.netmask > other.netmask
639 return False
640
641 def __le__(self, other):
642 gt = self.__gt__(other)
643 if gt is NotImplemented:
644 return NotImplemented
645 return not gt
646
647 def __ge__(self, other):
648 lt = self.__lt__(other)
649 if lt is NotImplemented:
650 return NotImplemented
651 return not lt
652
653 def __eq__(self, other):
Nick Coghlan9a9c28c2012-07-07 23:05:59 +1000654 try:
655 return (self._version == other._version and
656 self.network_address == other.network_address and
657 int(self.netmask) == int(other.netmask))
658 except AttributeError:
659 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000660
661 def __ne__(self, other):
662 eq = self.__eq__(other)
663 if eq is NotImplemented:
664 return NotImplemented
665 return not eq
666
Nick Coghlandc9b2552012-05-20 21:01:57 +1000667 def __hash__(self):
668 return hash(int(self.network_address) ^ int(self.netmask))
669
670 def __contains__(self, other):
671 # always false if one is v4 and the other is v6.
672 if self._version != other._version:
673 return False
674 # dealing with another network.
675 if isinstance(other, _BaseNetwork):
676 return False
677 # dealing with another address
678 else:
679 # address
680 return (int(self.network_address) <= int(other._ip) <=
681 int(self.broadcast_address))
682
683 def overlaps(self, other):
684 """Tell if self is partly contained in other."""
685 return self.network_address in other or (
686 self.broadcast_address in other or (
687 other.network_address in self or (
688 other.broadcast_address in self)))
689
690 @property
691 def broadcast_address(self):
692 x = self._cache.get('broadcast_address')
693 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000694 x = self._address_class(int(self.network_address) |
695 int(self.hostmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000696 self._cache['broadcast_address'] = x
697 return x
698
699 @property
700 def hostmask(self):
701 x = self._cache.get('hostmask')
702 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000703 x = self._address_class(int(self.netmask) ^ self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000704 self._cache['hostmask'] = x
705 return x
706
707 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000708 def with_prefixlen(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000709 return '%s/%d' % (self.network_address, self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000710
711 @property
712 def with_netmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000713 return '%s/%s' % (self.network_address, self.netmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000714
715 @property
716 def with_hostmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000717 return '%s/%s' % (self.network_address, self.hostmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000718
719 @property
720 def num_addresses(self):
721 """Number of hosts in the current subnet."""
722 return int(self.broadcast_address) - int(self.network_address) + 1
723
724 @property
Nick Coghlan51c30672012-05-27 00:25:58 +1000725 def _address_class(self):
Nick Coghland9722652012-06-17 16:33:00 +1000726 # Returning bare address objects (rather than interfaces) allows for
727 # more consistent behaviour across the network address, broadcast
728 # address and individual host addresses.
729 msg = '%200s has no associated address class' % (type(self),)
730 raise NotImplementedError(msg)
Nick Coghlan51c30672012-05-27 00:25:58 +1000731
732 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000733 def prefixlen(self):
734 return self._prefixlen
735
736 def address_exclude(self, other):
737 """Remove an address from a larger block.
738
739 For example:
740
741 addr1 = ip_network('192.0.2.0/28')
742 addr2 = ip_network('192.0.2.1/32')
743 addr1.address_exclude(addr2) =
744 [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
745 IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
746
747 or IPv6:
748
749 addr1 = ip_network('2001:db8::1/32')
750 addr2 = ip_network('2001:db8::1/128')
751 addr1.address_exclude(addr2) =
752 [ip_network('2001:db8::1/128'),
753 ip_network('2001:db8::2/127'),
754 ip_network('2001:db8::4/126'),
755 ip_network('2001:db8::8/125'),
756 ...
757 ip_network('2001:db8:8000::/33')]
758
759 Args:
760 other: An IPv4Network or IPv6Network object of the same type.
761
762 Returns:
763 An iterator of the the IPv(4|6)Network objects which is self
764 minus other.
765
766 Raises:
767 TypeError: If self and other are of difffering address
768 versions, or if other is not a network object.
769 ValueError: If other is not completely contained by self.
770
771 """
772 if not self._version == other._version:
773 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000774 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000775
776 if not isinstance(other, _BaseNetwork):
Nick Coghlan912238e2012-07-07 13:34:50 +1000777 raise TypeError("%s is not a network object" % other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000778
779 if not (other.network_address >= self.network_address and
780 other.broadcast_address <= self.broadcast_address):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200781 raise ValueError('%s not contained in %s' % (other, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000782 if other == self:
783 raise StopIteration
784
Nick Coghlandc9b2552012-05-20 21:01:57 +1000785 # Make sure we're comparing the network of other.
Nick Coghlan912238e2012-07-07 13:34:50 +1000786 other = other.__class__('%s/%s' % (other.network_address,
787 other.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000788
789 s1, s2 = self.subnets()
790 while s1 != other and s2 != other:
791 if (other.network_address >= s1.network_address and
792 other.broadcast_address <= s1.broadcast_address):
793 yield s2
794 s1, s2 = s1.subnets()
795 elif (other.network_address >= s2.network_address and
796 other.broadcast_address <= s2.broadcast_address):
797 yield s1
798 s1, s2 = s2.subnets()
799 else:
800 # If we got here, there's a bug somewhere.
801 raise AssertionError('Error performing exclusion: '
802 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000803 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000804 if s1 == other:
805 yield s2
806 elif s2 == other:
807 yield s1
808 else:
809 # If we got here, there's a bug somewhere.
810 raise AssertionError('Error performing exclusion: '
811 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000812 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000813
814 def compare_networks(self, other):
815 """Compare two IP objects.
816
817 This is only concerned about the comparison of the integer
818 representation of the network addresses. This means that the
819 host bits aren't considered at all in this method. If you want
820 to compare host bits, you can easily enough do a
821 'HostA._ip < HostB._ip'
822
823 Args:
824 other: An IP object.
825
826 Returns:
827 If the IP versions of self and other are the same, returns:
828
829 -1 if self < other:
830 eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
831 IPv6Network('2001:db8::1000/124') <
832 IPv6Network('2001:db8::2000/124')
833 0 if self == other
834 eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
835 IPv6Network('2001:db8::1000/124') ==
836 IPv6Network('2001:db8::1000/124')
837 1 if self > other
838 eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
839 IPv6Network('2001:db8::2000/124') >
840 IPv6Network('2001:db8::1000/124')
841
842 Raises:
843 TypeError if the IP versions are different.
844
845 """
846 # does this need to raise a ValueError?
847 if self._version != other._version:
848 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000849 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000850 # self._version == other._version below here:
851 if self.network_address < other.network_address:
852 return -1
853 if self.network_address > other.network_address:
854 return 1
855 # self.network_address == other.network_address below here:
856 if self.netmask < other.netmask:
857 return -1
858 if self.netmask > other.netmask:
859 return 1
860 return 0
861
862 def _get_networks_key(self):
863 """Network-only key function.
864
865 Returns an object that identifies this address' network and
866 netmask. This function is a suitable "key" argument for sorted()
867 and list.sort().
868
869 """
870 return (self._version, self.network_address, self.netmask)
871
872 def subnets(self, prefixlen_diff=1, new_prefix=None):
873 """The subnets which join to make the current subnet.
874
875 In the case that self contains only one IP
876 (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
877 for IPv6), yield an iterator with just ourself.
878
879 Args:
880 prefixlen_diff: An integer, the amount the prefix length
881 should be increased by. This should not be set if
882 new_prefix is also set.
883 new_prefix: The desired new prefix length. This must be a
884 larger number (smaller prefix) than the existing prefix.
885 This should not be set if prefixlen_diff is also set.
886
887 Returns:
888 An iterator of IPv(4|6) objects.
889
890 Raises:
891 ValueError: The prefixlen_diff is too small or too large.
892 OR
893 prefixlen_diff and new_prefix are both set or new_prefix
894 is a smaller number than the current prefix (smaller
895 number means a larger network)
896
897 """
898 if self._prefixlen == self._max_prefixlen:
899 yield self
900 return
901
902 if new_prefix is not None:
903 if new_prefix < self._prefixlen:
904 raise ValueError('new prefix must be longer')
905 if prefixlen_diff != 1:
906 raise ValueError('cannot set prefixlen_diff and new_prefix')
907 prefixlen_diff = new_prefix - self._prefixlen
908
909 if prefixlen_diff < 0:
910 raise ValueError('prefix length diff must be > 0')
911 new_prefixlen = self._prefixlen + prefixlen_diff
912
913 if not self._is_valid_netmask(str(new_prefixlen)):
914 raise ValueError(
915 'prefix length diff %d is invalid for netblock %s' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000916 new_prefixlen, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000917
Nick Coghlan51c30672012-05-27 00:25:58 +1000918 first = self.__class__('%s/%s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000919 (self.network_address,
920 self._prefixlen + prefixlen_diff))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000921
922 yield first
923 current = first
924 while True:
925 broadcast = current.broadcast_address
926 if broadcast == self.broadcast_address:
927 return
Nick Coghlan51c30672012-05-27 00:25:58 +1000928 new_addr = self._address_class(int(broadcast) + 1)
Nick Coghlan912238e2012-07-07 13:34:50 +1000929 current = self.__class__('%s/%s' % (new_addr,
930 new_prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000931
932 yield current
933
Nick Coghlandc9b2552012-05-20 21:01:57 +1000934 def supernet(self, prefixlen_diff=1, new_prefix=None):
935 """The supernet containing the current network.
936
937 Args:
938 prefixlen_diff: An integer, the amount the prefix length of
939 the network should be decreased by. For example, given a
940 /24 network and a prefixlen_diff of 3, a supernet with a
941 /21 netmask is returned.
942
943 Returns:
944 An IPv4 network object.
945
946 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200947 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
948 a negative prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000949 OR
950 If prefixlen_diff and new_prefix are both set or new_prefix is a
951 larger number than the current prefix (larger number means a
952 smaller network)
953
954 """
955 if self._prefixlen == 0:
956 return self
957
958 if new_prefix is not None:
959 if new_prefix > self._prefixlen:
960 raise ValueError('new prefix must be shorter')
961 if prefixlen_diff != 1:
962 raise ValueError('cannot set prefixlen_diff and new_prefix')
963 prefixlen_diff = self._prefixlen - new_prefix
964
Nick Coghlandc9b2552012-05-20 21:01:57 +1000965 if self.prefixlen - prefixlen_diff < 0:
966 raise ValueError(
967 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
968 (self.prefixlen, prefixlen_diff))
969 # TODO (pmoody): optimize this.
Nick Coghlan912238e2012-07-07 13:34:50 +1000970 t = self.__class__('%s/%d' % (self.network_address,
Nick Coghlan51c30672012-05-27 00:25:58 +1000971 self.prefixlen - prefixlen_diff),
972 strict=False)
Nick Coghlan912238e2012-07-07 13:34:50 +1000973 return t.__class__('%s/%d' % (t.network_address, t.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000974
975
Hynek Schlawackc4b78a32012-06-01 11:48:32 +0200976class _BaseV4:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000977
978 """Base IPv4 object.
979
980 The following methods are used by IPv4 objects in both single IP
981 addresses and networks.
982
983 """
984
985 # Equivalent to 255.255.255.255 or 32 bits of 1's.
986 _ALL_ONES = (2**IPV4LENGTH) - 1
987 _DECIMAL_DIGITS = frozenset('0123456789')
988
Hynek Schlawack91c5a342012-06-05 11:55:58 +0200989 # the valid octets for host and netmasks. only useful for IPv4.
Nick Coghlan7319f692012-07-07 21:43:30 +1000990 _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0))
Hynek Schlawack91c5a342012-06-05 11:55:58 +0200991
Nick Coghlandc9b2552012-05-20 21:01:57 +1000992 def __init__(self, address):
993 self._version = 4
994 self._max_prefixlen = IPV4LENGTH
995
996 def _explode_shorthand_ip_string(self):
997 return str(self)
998
999 def _ip_int_from_string(self, ip_str):
1000 """Turn the given IP string into an integer for comparison.
1001
1002 Args:
1003 ip_str: A string, the IP ip_str.
1004
1005 Returns:
1006 The IP ip_str as an integer.
1007
1008 Raises:
1009 AddressValueError: if ip_str isn't a valid IPv4 Address.
1010
1011 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001012 if not ip_str:
1013 raise AddressValueError('Address cannot be empty')
1014
Nick Coghlandc9b2552012-05-20 21:01:57 +10001015 octets = ip_str.split('.')
1016 if len(octets) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001017 raise AddressValueError("Expected 4 octets in %r" % ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001018
Nick Coghlan7319f692012-07-07 21:43:30 +10001019 try:
1020 return int.from_bytes(map(self._parse_octet, octets), 'big')
1021 except ValueError as exc:
1022 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001023
1024 def _parse_octet(self, octet_str):
1025 """Convert a decimal octet into an integer.
1026
1027 Args:
1028 octet_str: A string, the number to parse.
1029
1030 Returns:
1031 The octet as an integer.
1032
1033 Raises:
1034 ValueError: if the octet isn't strictly a decimal from [0..255].
1035
1036 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001037 if not octet_str:
1038 raise ValueError("Empty octet not permitted")
Nick Coghlandc9b2552012-05-20 21:01:57 +10001039 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1040 if not self._DECIMAL_DIGITS.issuperset(octet_str):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001041 raise ValueError("Only decimal digits permitted in %r" % octet_str)
1042 # Convert to integer (we know digits are legal)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001043 octet_int = int(octet_str, 10)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001044 # Any octets that look like they *might* be written in octal,
1045 # and which don't look exactly the same in both octal and
1046 # decimal are rejected as ambiguous
1047 if octet_int > 7 and octet_str[0] == '0':
1048 raise ValueError("Ambiguous leading zero in %r not permitted" %
1049 octet_str)
1050 if octet_int > 255:
Nick Coghlanb582ecc2012-07-07 22:15:22 +10001051 raise ValueError("Octet %d (> 255) not permitted" % octet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001052 return octet_int
1053
1054 def _string_from_ip_int(self, ip_int):
1055 """Turns a 32-bit integer into dotted decimal notation.
1056
1057 Args:
1058 ip_int: An integer, the IP address.
1059
1060 Returns:
1061 The IP address as a string in dotted decimal notation.
1062
1063 """
Nick Coghlan7319f692012-07-07 21:43:30 +10001064 return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001065
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001066 def _is_valid_netmask(self, netmask):
1067 """Verify that the netmask is valid.
1068
1069 Args:
1070 netmask: A string, either a prefix or dotted decimal
1071 netmask.
1072
1073 Returns:
1074 A boolean, True if the prefix represents a valid IPv4
1075 netmask.
1076
1077 """
1078 mask = netmask.split('.')
1079 if len(mask) == 4:
Nick Coghlan7319f692012-07-07 21:43:30 +10001080 try:
1081 for x in mask:
1082 if int(x) not in self._valid_mask_octets:
1083 return False
1084 except ValueError:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001085 # Found something that isn't an integer or isn't valid
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001086 return False
Nick Coghlan7319f692012-07-07 21:43:30 +10001087 for idx, y in enumerate(mask):
1088 if idx > 0 and y > mask[idx - 1]:
1089 return False
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001090 return True
1091 try:
1092 netmask = int(netmask)
1093 except ValueError:
1094 return False
1095 return 0 <= netmask <= self._max_prefixlen
1096
1097 def _is_hostmask(self, ip_str):
1098 """Test if the IP string is a hostmask (rather than a netmask).
1099
1100 Args:
1101 ip_str: A string, the potential hostmask.
1102
1103 Returns:
1104 A boolean, True if the IP string is a hostmask.
1105
1106 """
1107 bits = ip_str.split('.')
1108 try:
Nick Coghlan7319f692012-07-07 21:43:30 +10001109 parts = [x for x in map(int, bits) if x in self._valid_mask_octets]
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001110 except ValueError:
1111 return False
1112 if len(parts) != len(bits):
1113 return False
1114 if parts[0] < parts[-1]:
1115 return True
1116 return False
1117
Nick Coghlandc9b2552012-05-20 21:01:57 +10001118 @property
1119 def max_prefixlen(self):
1120 return self._max_prefixlen
1121
1122 @property
1123 def version(self):
1124 return self._version
1125
1126 @property
1127 def is_reserved(self):
1128 """Test if the address is otherwise IETF reserved.
1129
1130 Returns:
1131 A boolean, True if the address is within the
1132 reserved IPv4 Network range.
1133
1134 """
1135 reserved_network = IPv4Network('240.0.0.0/4')
1136 if isinstance(self, _BaseAddress):
1137 return self in reserved_network
1138 return (self.network_address in reserved_network and
1139 self.broadcast_address in reserved_network)
1140
1141 @property
1142 def is_private(self):
1143 """Test if this address is allocated for private networks.
1144
1145 Returns:
1146 A boolean, True if the address is reserved per RFC 1918.
1147
1148 """
1149 private_10 = IPv4Network('10.0.0.0/8')
1150 private_172 = IPv4Network('172.16.0.0/12')
1151 private_192 = IPv4Network('192.168.0.0/16')
1152 if isinstance(self, _BaseAddress):
1153 return (self in private_10 or self in private_172 or
1154 self in private_192)
1155 else:
1156 return ((self.network_address in private_10 and
1157 self.broadcast_address in private_10) or
1158 (self.network_address in private_172 and
1159 self.broadcast_address in private_172) or
1160 (self.network_address in private_192 and
1161 self.broadcast_address in private_192))
1162
1163 @property
1164 def is_multicast(self):
1165 """Test if the address is reserved for multicast use.
1166
1167 Returns:
1168 A boolean, True if the address is multicast.
1169 See RFC 3171 for details.
1170
1171 """
1172 multicast_network = IPv4Network('224.0.0.0/4')
1173 if isinstance(self, _BaseAddress):
1174 return self in IPv4Network('224.0.0.0/4')
1175 return (self.network_address in multicast_network and
1176 self.broadcast_address in multicast_network)
1177
1178 @property
1179 def is_unspecified(self):
1180 """Test if the address is unspecified.
1181
1182 Returns:
1183 A boolean, True if this is the unspecified address as defined in
1184 RFC 5735 3.
1185
1186 """
1187 unspecified_address = IPv4Address('0.0.0.0')
1188 if isinstance(self, _BaseAddress):
Hynek Schlawackbcd30442012-06-04 14:19:39 +02001189 return self == unspecified_address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001190 return (self.network_address == self.broadcast_address ==
1191 unspecified_address)
1192
1193 @property
1194 def is_loopback(self):
1195 """Test if the address is a loopback address.
1196
1197 Returns:
1198 A boolean, True if the address is a loopback per RFC 3330.
1199
1200 """
1201 loopback_address = IPv4Network('127.0.0.0/8')
1202 if isinstance(self, _BaseAddress):
1203 return self in loopback_address
1204
1205 return (self.network_address in loopback_address and
1206 self.broadcast_address in loopback_address)
1207
1208 @property
1209 def is_link_local(self):
1210 """Test if the address is reserved for link-local.
1211
1212 Returns:
1213 A boolean, True if the address is link-local per RFC 3927.
1214
1215 """
1216 linklocal_network = IPv4Network('169.254.0.0/16')
1217 if isinstance(self, _BaseAddress):
1218 return self in linklocal_network
1219 return (self.network_address in linklocal_network and
1220 self.broadcast_address in linklocal_network)
1221
1222
1223class IPv4Address(_BaseV4, _BaseAddress):
1224
1225 """Represent and manipulate single IPv4 Addresses."""
1226
1227 def __init__(self, address):
1228
1229 """
1230 Args:
1231 address: A string or integer representing the IP
1232
1233 Additionally, an integer can be passed, so
1234 IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1235 or, more generally
1236 IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1237 IPv4Address('192.0.2.1')
1238
1239 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001240 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001241
1242 """
1243 _BaseAddress.__init__(self, address)
1244 _BaseV4.__init__(self, address)
1245
1246 # Efficient constructor from integer.
1247 if isinstance(address, int):
1248 self._ip = address
1249 if address < 0 or address > self._ALL_ONES:
1250 raise AddressValueError(address)
1251 return
1252
1253 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001254 if isinstance(address, bytes):
1255 if len(address) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001256 msg = "Packed address %r must be exactly 4 bytes"
1257 raise AddressValueError(msg % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001258 self._ip = struct.unpack('!I', address)[0]
1259 return
1260
1261 # Assume input argument to be string or any object representation
1262 # which converts into a formatted IP string.
1263 addr_str = str(address)
1264 self._ip = self._ip_int_from_string(addr_str)
1265
1266 @property
1267 def packed(self):
1268 """The binary representation of this address."""
1269 return v4_int_to_packed(self._ip)
1270
1271
1272class IPv4Interface(IPv4Address):
1273
Nick Coghlandc9b2552012-05-20 21:01:57 +10001274 def __init__(self, address):
1275 if isinstance(address, (bytes, int)):
1276 IPv4Address.__init__(self, address)
1277 self.network = IPv4Network(self._ip)
1278 self._prefixlen = self._max_prefixlen
1279 return
1280
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001281 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001282 IPv4Address.__init__(self, addr[0])
1283
1284 self.network = IPv4Network(address, strict=False)
1285 self._prefixlen = self.network._prefixlen
1286
1287 self.netmask = self.network.netmask
1288 self.hostmask = self.network.hostmask
1289
Nick Coghlandc9b2552012-05-20 21:01:57 +10001290 def __str__(self):
1291 return '%s/%d' % (self._string_from_ip_int(self._ip),
1292 self.network.prefixlen)
1293
1294 def __eq__(self, other):
1295 try:
1296 return (IPv4Address.__eq__(self, other) and
1297 self.network == other.network)
1298 except AttributeError:
1299 return NotImplemented
1300
1301 def __hash__(self):
1302 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1303
Nick Coghlandc9b2552012-05-20 21:01:57 +10001304 @property
1305 def prefixlen(self):
1306 return self._prefixlen
1307
1308 @property
1309 def ip(self):
1310 return IPv4Address(self._ip)
1311
1312 @property
1313 def with_prefixlen(self):
1314 return self
1315
1316 @property
1317 def with_netmask(self):
1318 return '%s/%s' % (self._string_from_ip_int(self._ip),
1319 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001320
Nick Coghlandc9b2552012-05-20 21:01:57 +10001321 @property
1322 def with_hostmask(self):
1323 return '%s/%s' % (self._string_from_ip_int(self._ip),
1324 self.hostmask)
1325
1326
1327class IPv4Network(_BaseV4, _BaseNetwork):
1328
1329 """This class represents and manipulates 32-bit IPv4 network + addresses..
1330
1331 Attributes: [examples for IPv4Network('192.0.2.0/27')]
1332 .network_address: IPv4Address('192.0.2.0')
1333 .hostmask: IPv4Address('0.0.0.31')
1334 .broadcast_address: IPv4Address('192.0.2.32')
1335 .netmask: IPv4Address('255.255.255.224')
1336 .prefixlen: 27
1337
1338 """
Nick Coghlan51c30672012-05-27 00:25:58 +10001339 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001340 _address_class = IPv4Address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001341
Nick Coghlandc9b2552012-05-20 21:01:57 +10001342 def __init__(self, address, strict=True):
1343
1344 """Instantiate a new IPv4 network object.
1345
1346 Args:
1347 address: A string or integer representing the IP [& network].
1348 '192.0.2.0/24'
1349 '192.0.2.0/255.255.255.0'
1350 '192.0.0.2/0.0.0.255'
1351 are all functionally the same in IPv4. Similarly,
1352 '192.0.2.1'
1353 '192.0.2.1/255.255.255.255'
1354 '192.0.2.1/32'
1355 are also functionaly equivalent. That is to say, failing to
1356 provide a subnetmask will create an object with a mask of /32.
1357
1358 If the mask (portion after the / in the argument) is given in
1359 dotted quad form, it is treated as a netmask if it starts with a
1360 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1361 starts with a zero field (e.g. 0.255.255.255 == /8), with the
1362 single exception of an all-zero mask which is treated as a
1363 netmask == /0. If no mask is given, a default of /32 is used.
1364
1365 Additionally, an integer can be passed, so
1366 IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1367 or, more generally
1368 IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1369 IPv4Interface('192.0.2.1')
1370
1371 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001372 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001373 NetmaskValueError: If the netmask isn't valid for
1374 an IPv4 address.
Sandro Tosib4386d32012-06-02 17:14:22 +02001375 ValueError: If strict is True and a network address is not
Nick Coghlandc9b2552012-05-20 21:01:57 +10001376 supplied.
1377
1378 """
1379
1380 _BaseV4.__init__(self, address)
1381 _BaseNetwork.__init__(self, address)
1382
1383 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001384 if isinstance(address, bytes):
1385 if len(address) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001386 msg = "Packed address %r must be exactly 4 bytes"
1387 raise AddressValueError(msg % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001388 self.network_address = IPv4Address(
1389 struct.unpack('!I', address)[0])
1390 self._prefixlen = self._max_prefixlen
1391 self.netmask = IPv4Address(self._ALL_ONES)
1392 #fixme: address/network test here
1393 return
1394
1395 # Efficient constructor from integer.
1396 if isinstance(address, int):
1397 self._prefixlen = self._max_prefixlen
1398 self.netmask = IPv4Address(self._ALL_ONES)
1399 if address < 0 or address > self._ALL_ONES:
1400 raise AddressValueError(address)
1401 self.network_address = IPv4Address(address)
1402 #fixme: address/network test here.
1403 return
1404
1405 # Assume input argument to be string or any object representation
1406 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001407 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001408 self.network_address = IPv4Address(self._ip_int_from_string(addr[0]))
1409
Nick Coghlandc9b2552012-05-20 21:01:57 +10001410 if len(addr) == 2:
1411 mask = addr[1].split('.')
1412
1413 if len(mask) == 4:
1414 # We have dotted decimal netmask.
1415 if self._is_valid_netmask(addr[1]):
1416 self.netmask = IPv4Address(self._ip_int_from_string(
1417 addr[1]))
1418 elif self._is_hostmask(addr[1]):
1419 self.netmask = IPv4Address(
1420 self._ip_int_from_string(addr[1]) ^ self._ALL_ONES)
1421 else:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001422 raise NetmaskValueError('%r is not a valid netmask'
Nick Coghlandc9b2552012-05-20 21:01:57 +10001423 % addr[1])
1424
1425 self._prefixlen = self._prefix_from_ip_int(int(self.netmask))
1426 else:
1427 # We have a netmask in prefix length form.
1428 if not self._is_valid_netmask(addr[1]):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001429 raise NetmaskValueError('%r is not a valid netmask'
1430 % addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001431 self._prefixlen = int(addr[1])
1432 self.netmask = IPv4Address(self._ip_int_from_prefix(
1433 self._prefixlen))
1434 else:
1435 self._prefixlen = self._max_prefixlen
1436 self.netmask = IPv4Address(self._ip_int_from_prefix(
1437 self._prefixlen))
1438
1439 if strict:
1440 if (IPv4Address(int(self.network_address) & int(self.netmask)) !=
1441 self.network_address):
1442 raise ValueError('%s has host bits set' % self)
1443 self.network_address = IPv4Address(int(self.network_address) &
1444 int(self.netmask))
1445
1446 if self._prefixlen == (self._max_prefixlen - 1):
1447 self.hosts = self.__iter__
1448
Nick Coghlandc9b2552012-05-20 21:01:57 +10001449
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001450class _BaseV6:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001451
1452 """Base IPv6 object.
1453
1454 The following methods are used by IPv6 objects in both single IP
1455 addresses and networks.
1456
1457 """
1458
1459 _ALL_ONES = (2**IPV6LENGTH) - 1
1460 _HEXTET_COUNT = 8
1461 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
1462
1463 def __init__(self, address):
1464 self._version = 6
1465 self._max_prefixlen = IPV6LENGTH
1466
1467 def _ip_int_from_string(self, ip_str):
1468 """Turn an IPv6 ip_str into an integer.
1469
1470 Args:
1471 ip_str: A string, the IPv6 ip_str.
1472
1473 Returns:
1474 An int, the IPv6 address
1475
1476 Raises:
1477 AddressValueError: if ip_str isn't a valid IPv6 Address.
1478
1479 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001480 if not ip_str:
1481 raise AddressValueError('Address cannot be empty')
1482
Nick Coghlandc9b2552012-05-20 21:01:57 +10001483 parts = ip_str.split(':')
1484
1485 # An IPv6 address needs at least 2 colons (3 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001486 _min_parts = 3
1487 if len(parts) < _min_parts:
1488 msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
1489 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001490
1491 # If the address has an IPv4-style suffix, convert it to hexadecimal.
1492 if '.' in parts[-1]:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001493 try:
1494 ipv4_int = IPv4Address(parts.pop())._ip
1495 except AddressValueError as exc:
1496 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001497 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1498 parts.append('%x' % (ipv4_int & 0xFFFF))
1499
1500 # An IPv6 address can't have more than 8 colons (9 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001501 # The extra colon comes from using the "::" notation for a single
1502 # leading or trailing zero part.
1503 _max_parts = self._HEXTET_COUNT + 1
1504 if len(parts) > _max_parts:
1505 msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
1506 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001507
1508 # Disregarding the endpoints, find '::' with nothing in between.
1509 # This indicates that a run of zeroes has been skipped.
Nick Coghlan7319f692012-07-07 21:43:30 +10001510 skip_index = None
1511 for i in range(1, len(parts) - 1):
1512 if not parts[i]:
1513 if skip_index is not None:
1514 # Can't have more than one '::'
1515 msg = "At most one '::' permitted in %r" % ip_str
1516 raise AddressValueError(msg)
1517 skip_index = i
Nick Coghlandc9b2552012-05-20 21:01:57 +10001518
1519 # parts_hi is the number of parts to copy from above/before the '::'
1520 # parts_lo is the number of parts to copy from below/after the '::'
1521 if skip_index is not None:
1522 # If we found a '::', then check if it also covers the endpoints.
1523 parts_hi = skip_index
1524 parts_lo = len(parts) - skip_index - 1
1525 if not parts[0]:
1526 parts_hi -= 1
1527 if parts_hi:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001528 msg = "Leading ':' only permitted as part of '::' in %r"
1529 raise AddressValueError(msg % ip_str) # ^: requires ^::
Nick Coghlandc9b2552012-05-20 21:01:57 +10001530 if not parts[-1]:
1531 parts_lo -= 1
1532 if parts_lo:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001533 msg = "Trailing ':' only permitted as part of '::' in %r"
1534 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001535 parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo)
1536 if parts_skipped < 1:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001537 msg = "Expected at most %d other parts with '::' in %r"
1538 raise AddressValueError(msg % (self._HEXTET_COUNT-1, ip_str))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001539 else:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001540 # Otherwise, allocate the entire address to parts_hi. The
1541 # endpoints could still be empty, but _parse_hextet() will check
1542 # for that.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001543 if len(parts) != self._HEXTET_COUNT:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001544 msg = "Exactly %d parts expected without '::' in %r"
1545 raise AddressValueError(msg % (self._HEXTET_COUNT, ip_str))
1546 if not parts[0]:
1547 msg = "Leading ':' only permitted as part of '::' in %r"
1548 raise AddressValueError(msg % ip_str) # ^: requires ^::
1549 if not parts[-1]:
1550 msg = "Trailing ':' only permitted as part of '::' in %r"
1551 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001552 parts_hi = len(parts)
1553 parts_lo = 0
1554 parts_skipped = 0
1555
1556 try:
1557 # Now, parse the hextets into a 128-bit integer.
1558 ip_int = 0
1559 for i in range(parts_hi):
1560 ip_int <<= 16
1561 ip_int |= self._parse_hextet(parts[i])
1562 ip_int <<= 16 * parts_skipped
1563 for i in range(-parts_lo, 0):
1564 ip_int <<= 16
1565 ip_int |= self._parse_hextet(parts[i])
1566 return ip_int
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001567 except ValueError as exc:
1568 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001569
1570 def _parse_hextet(self, hextet_str):
1571 """Convert an IPv6 hextet string into an integer.
1572
1573 Args:
1574 hextet_str: A string, the number to parse.
1575
1576 Returns:
1577 The hextet as an integer.
1578
1579 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001580 ValueError: if the input isn't strictly a hex number from
1581 [0..FFFF].
Nick Coghlandc9b2552012-05-20 21:01:57 +10001582
1583 """
1584 # Whitelist the characters, since int() allows a lot of bizarre stuff.
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001585 # Higher level wrappers convert these to more informative errors
Nick Coghlandc9b2552012-05-20 21:01:57 +10001586 if not self._HEX_DIGITS.issuperset(hextet_str):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001587 raise ValueError("Only hex digits permitted in %r" % hextet_str)
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001588 if len(hextet_str) > 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001589 msg = "At most 4 characters permitted in %r"
1590 raise ValueError(msg % hextet_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001591 hextet_int = int(hextet_str, 16)
1592 if hextet_int > 0xFFFF:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001593 # This is unreachable due to the string length check above
Nick Coghlanb582ecc2012-07-07 22:15:22 +10001594 msg = "Part 0x%X (> 0xFFFF) not permitted"
1595 raise ValueError(msg % hextet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001596 return hextet_int
1597
1598 def _compress_hextets(self, hextets):
1599 """Compresses a list of hextets.
1600
1601 Compresses a list of strings, replacing the longest continuous
1602 sequence of "0" in the list with "" and adding empty strings at
1603 the beginning or at the end of the string such that subsequently
1604 calling ":".join(hextets) will produce the compressed version of
1605 the IPv6 address.
1606
1607 Args:
1608 hextets: A list of strings, the hextets to compress.
1609
1610 Returns:
1611 A list of strings.
1612
1613 """
1614 best_doublecolon_start = -1
1615 best_doublecolon_len = 0
1616 doublecolon_start = -1
1617 doublecolon_len = 0
1618 for index in range(len(hextets)):
1619 if hextets[index] == '0':
1620 doublecolon_len += 1
1621 if doublecolon_start == -1:
1622 # Start of a sequence of zeros.
1623 doublecolon_start = index
1624 if doublecolon_len > best_doublecolon_len:
1625 # This is the longest sequence of zeros so far.
1626 best_doublecolon_len = doublecolon_len
1627 best_doublecolon_start = doublecolon_start
1628 else:
1629 doublecolon_len = 0
1630 doublecolon_start = -1
1631
1632 if best_doublecolon_len > 1:
1633 best_doublecolon_end = (best_doublecolon_start +
1634 best_doublecolon_len)
1635 # For zeros at the end of the address.
1636 if best_doublecolon_end == len(hextets):
1637 hextets += ['']
1638 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1639 # For zeros at the beginning of the address.
1640 if best_doublecolon_start == 0:
1641 hextets = [''] + hextets
1642
1643 return hextets
1644
1645 def _string_from_ip_int(self, ip_int=None):
1646 """Turns a 128-bit integer into hexadecimal notation.
1647
1648 Args:
1649 ip_int: An integer, the IP address.
1650
1651 Returns:
1652 A string, the hexadecimal representation of the address.
1653
1654 Raises:
1655 ValueError: The address is bigger than 128 bits of all ones.
1656
1657 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001658 if ip_int is None:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001659 ip_int = int(self._ip)
1660
1661 if ip_int > self._ALL_ONES:
1662 raise ValueError('IPv6 address is too large')
1663
1664 hex_str = '%032x' % ip_int
Nick Coghlan7319f692012-07-07 21:43:30 +10001665 hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001666
1667 hextets = self._compress_hextets(hextets)
1668 return ':'.join(hextets)
1669
1670 def _explode_shorthand_ip_string(self):
1671 """Expand a shortened IPv6 address.
1672
1673 Args:
1674 ip_str: A string, the IPv6 address.
1675
1676 Returns:
1677 A string, the expanded IPv6 address.
1678
1679 """
1680 if isinstance(self, IPv6Network):
1681 ip_str = str(self.network_address)
1682 elif isinstance(self, IPv6Interface):
1683 ip_str = str(self.ip)
1684 else:
1685 ip_str = str(self)
1686
1687 ip_int = self._ip_int_from_string(ip_str)
Nick Coghlan7319f692012-07-07 21:43:30 +10001688 hex_str = '%032x' % ip_int
1689 parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001690 if isinstance(self, (_BaseNetwork, IPv6Interface)):
1691 return '%s/%d' % (':'.join(parts), self.prefixlen)
1692 return ':'.join(parts)
1693
1694 @property
1695 def max_prefixlen(self):
1696 return self._max_prefixlen
1697
1698 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001699 def version(self):
1700 return self._version
1701
1702 @property
1703 def is_multicast(self):
1704 """Test if the address is reserved for multicast use.
1705
1706 Returns:
1707 A boolean, True if the address is a multicast address.
1708 See RFC 2373 2.7 for details.
1709
1710 """
1711 multicast_network = IPv6Network('ff00::/8')
1712 if isinstance(self, _BaseAddress):
1713 return self in multicast_network
1714 return (self.network_address in multicast_network and
1715 self.broadcast_address in multicast_network)
1716
1717 @property
1718 def is_reserved(self):
1719 """Test if the address is otherwise IETF reserved.
1720
1721 Returns:
1722 A boolean, True if the address is within one of the
1723 reserved IPv6 Network ranges.
1724
1725 """
1726 reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'),
1727 IPv6Network('200::/7'), IPv6Network('400::/6'),
1728 IPv6Network('800::/5'), IPv6Network('1000::/4'),
1729 IPv6Network('4000::/3'), IPv6Network('6000::/3'),
1730 IPv6Network('8000::/3'), IPv6Network('A000::/3'),
1731 IPv6Network('C000::/3'), IPv6Network('E000::/4'),
1732 IPv6Network('F000::/5'), IPv6Network('F800::/6'),
1733 IPv6Network('FE00::/9')]
1734
1735 if isinstance(self, _BaseAddress):
Nick Coghlan7319f692012-07-07 21:43:30 +10001736 return any(self in x for x in reserved_networks)
1737 return any(self.network_address in x and self.broadcast_address in x
1738 for x in reserved_networks)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001739
1740 @property
1741 def is_link_local(self):
1742 """Test if the address is reserved for link-local.
1743
1744 Returns:
1745 A boolean, True if the address is reserved per RFC 4291.
1746
1747 """
1748 linklocal_network = IPv6Network('fe80::/10')
1749 if isinstance(self, _BaseAddress):
1750 return self in linklocal_network
1751 return (self.network_address in linklocal_network and
1752 self.broadcast_address in linklocal_network)
1753
1754 @property
1755 def is_site_local(self):
1756 """Test if the address is reserved for site-local.
1757
1758 Note that the site-local address space has been deprecated by RFC 3879.
1759 Use is_private to test if this address is in the space of unique local
1760 addresses as defined by RFC 4193.
1761
1762 Returns:
1763 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1764
1765 """
1766 sitelocal_network = IPv6Network('fec0::/10')
1767 if isinstance(self, _BaseAddress):
1768 return self in sitelocal_network
1769 return (self.network_address in sitelocal_network and
1770 self.broadcast_address in sitelocal_network)
1771
1772 @property
1773 def is_private(self):
1774 """Test if this address is allocated for private networks.
1775
1776 Returns:
1777 A boolean, True if the address is reserved per RFC 4193.
1778
1779 """
1780 private_network = IPv6Network('fc00::/7')
1781 if isinstance(self, _BaseAddress):
1782 return self in private_network
1783 return (self.network_address in private_network and
1784 self.broadcast_address in private_network)
1785
Nick Coghlandc9b2552012-05-20 21:01:57 +10001786 @property
1787 def ipv4_mapped(self):
1788 """Return the IPv4 mapped address.
1789
1790 Returns:
1791 If the IPv6 address is a v4 mapped address, return the
1792 IPv4 mapped address. Return None otherwise.
1793
1794 """
1795 if (self._ip >> 32) != 0xFFFF:
1796 return None
1797 return IPv4Address(self._ip & 0xFFFFFFFF)
1798
1799 @property
1800 def teredo(self):
1801 """Tuple of embedded teredo IPs.
1802
1803 Returns:
1804 Tuple of the (server, client) IPs or None if the address
1805 doesn't appear to be a teredo address (doesn't start with
1806 2001::/32)
1807
1808 """
1809 if (self._ip >> 96) != 0x20010000:
1810 return None
1811 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
1812 IPv4Address(~self._ip & 0xFFFFFFFF))
1813
1814 @property
1815 def sixtofour(self):
1816 """Return the IPv4 6to4 embedded address.
1817
1818 Returns:
1819 The IPv4 6to4-embedded address if present or None if the
1820 address doesn't appear to contain a 6to4 embedded address.
1821
1822 """
1823 if (self._ip >> 112) != 0x2002:
1824 return None
1825 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
1826
1827 @property
1828 def is_unspecified(self):
1829 """Test if the address is unspecified.
1830
1831 Returns:
1832 A boolean, True if this is the unspecified address as defined in
1833 RFC 2373 2.5.2.
1834
1835 """
1836 if isinstance(self, (IPv6Network, IPv6Interface)):
1837 return int(self.network_address) == 0 and getattr(
1838 self, '_prefixlen', 128) == 128
1839 return self._ip == 0
1840
1841 @property
1842 def is_loopback(self):
1843 """Test if the address is a loopback address.
1844
1845 Returns:
1846 A boolean, True if the address is a loopback address as defined in
1847 RFC 2373 2.5.3.
1848
1849 """
1850 if isinstance(self, IPv6Network):
Nick Coghlan2c589102012-05-27 01:03:25 +10001851 return int(self) == 1 and getattr(
Nick Coghlandc9b2552012-05-20 21:01:57 +10001852 self, '_prefixlen', 128) == 128
1853 elif isinstance(self, IPv6Interface):
1854 return int(self.network.network_address) == 1 and getattr(
1855 self, '_prefixlen', 128) == 128
1856 return self._ip == 1
1857
1858
1859class IPv6Address(_BaseV6, _BaseAddress):
1860
Sandro Tosib95c6342012-05-23 23:17:22 +02001861 """Represent and manipulate single IPv6 Addresses."""
Nick Coghlandc9b2552012-05-20 21:01:57 +10001862
1863 def __init__(self, address):
1864 """Instantiate a new IPv6 address object.
1865
1866 Args:
1867 address: A string or integer representing the IP
1868
1869 Additionally, an integer can be passed, so
1870 IPv6Address('2001:db8::') ==
1871 IPv6Address(42540766411282592856903984951653826560)
1872 or, more generally
1873 IPv6Address(int(IPv6Address('2001:db8::'))) ==
1874 IPv6Address('2001:db8::')
1875
1876 Raises:
1877 AddressValueError: If address isn't a valid IPv6 address.
1878
1879 """
1880 _BaseAddress.__init__(self, address)
1881 _BaseV6.__init__(self, address)
1882
1883 # Efficient constructor from integer.
1884 if isinstance(address, int):
1885 self._ip = address
1886 if address < 0 or address > self._ALL_ONES:
1887 raise AddressValueError(address)
1888 return
1889
1890 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001891 if isinstance(address, bytes):
1892 if len(address) != 16:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001893 msg = "Packed address %r must be exactly 16 bytes"
1894 raise AddressValueError(msg % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001895 tmp = struct.unpack('!QQ', address)
1896 self._ip = (tmp[0] << 64) | tmp[1]
1897 return
1898
1899 # Assume input argument to be string or any object representation
1900 # which converts into a formatted IP string.
1901 addr_str = str(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001902 self._ip = self._ip_int_from_string(addr_str)
1903
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001904 @property
1905 def packed(self):
1906 """The binary representation of this address."""
1907 return v6_int_to_packed(self._ip)
1908
Nick Coghlandc9b2552012-05-20 21:01:57 +10001909
1910class IPv6Interface(IPv6Address):
1911
1912 def __init__(self, address):
1913 if isinstance(address, (bytes, int)):
1914 IPv6Address.__init__(self, address)
1915 self.network = IPv6Network(self._ip)
1916 self._prefixlen = self._max_prefixlen
1917 return
1918
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001919 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001920 IPv6Address.__init__(self, addr[0])
1921 self.network = IPv6Network(address, strict=False)
1922 self.netmask = self.network.netmask
1923 self._prefixlen = self.network._prefixlen
1924 self.hostmask = self.network.hostmask
1925
Nick Coghlandc9b2552012-05-20 21:01:57 +10001926 def __str__(self):
1927 return '%s/%d' % (self._string_from_ip_int(self._ip),
1928 self.network.prefixlen)
1929
1930 def __eq__(self, other):
1931 try:
1932 return (IPv6Address.__eq__(self, other) and
1933 self.network == other.network)
1934 except AttributeError:
1935 return NotImplemented
1936
1937 def __hash__(self):
1938 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1939
1940 @property
1941 def prefixlen(self):
1942 return self._prefixlen
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001943
Nick Coghlandc9b2552012-05-20 21:01:57 +10001944 @property
1945 def ip(self):
1946 return IPv6Address(self._ip)
1947
1948 @property
1949 def with_prefixlen(self):
1950 return self
1951
1952 @property
1953 def with_netmask(self):
1954 return self.with_prefixlen
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001955
Nick Coghlandc9b2552012-05-20 21:01:57 +10001956 @property
1957 def with_hostmask(self):
1958 return '%s/%s' % (self._string_from_ip_int(self._ip),
1959 self.hostmask)
1960
1961
1962class IPv6Network(_BaseV6, _BaseNetwork):
1963
1964 """This class represents and manipulates 128-bit IPv6 networks.
1965
1966 Attributes: [examples for IPv6('2001:db8::1000/124')]
1967 .network_address: IPv6Address('2001:db8::1000')
1968 .hostmask: IPv6Address('::f')
1969 .broadcast_address: IPv6Address('2001:db8::100f')
1970 .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
1971 .prefixlen: 124
1972
1973 """
1974
Nick Coghlan51c30672012-05-27 00:25:58 +10001975 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001976 _address_class = IPv6Address
1977
Nick Coghlandc9b2552012-05-20 21:01:57 +10001978 def __init__(self, address, strict=True):
1979 """Instantiate a new IPv6 Network object.
1980
1981 Args:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001982 address: A string or integer representing the IPv6 network or the
1983 IP and prefix/netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001984 '2001:db8::/128'
1985 '2001:db8:0000:0000:0000:0000:0000:0000/128'
1986 '2001:db8::'
1987 are all functionally the same in IPv6. That is to say,
1988 failing to provide a subnetmask will create an object with
1989 a mask of /128.
1990
1991 Additionally, an integer can be passed, so
1992 IPv6Network('2001:db8::') ==
1993 IPv6Network(42540766411282592856903984951653826560)
1994 or, more generally
1995 IPv6Network(int(IPv6Network('2001:db8::'))) ==
1996 IPv6Network('2001:db8::')
1997
1998 strict: A boolean. If true, ensure that we have been passed
1999 A true network address, eg, 2001:db8::1000/124 and not an
2000 IP address on a network, eg, 2001:db8::1/124.
2001
2002 Raises:
2003 AddressValueError: If address isn't a valid IPv6 address.
2004 NetmaskValueError: If the netmask isn't valid for
2005 an IPv6 address.
2006 ValueError: If strict was True and a network address was not
2007 supplied.
2008
2009 """
2010 _BaseV6.__init__(self, address)
2011 _BaseNetwork.__init__(self, address)
2012
2013 # Efficient constructor from integer.
2014 if isinstance(address, int):
2015 if address < 0 or address > self._ALL_ONES:
2016 raise AddressValueError(address)
2017 self.network_address = IPv6Address(address)
2018 self._prefixlen = self._max_prefixlen
2019 self.netmask = IPv6Address(self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002020 return
2021
2022 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10002023 if isinstance(address, bytes):
2024 if len(address) != 16:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002025 msg = "Packed address %r must be exactly 16 bytes"
2026 raise AddressValueError(msg % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002027 tmp = struct.unpack('!QQ', address)
2028 self.network_address = IPv6Address((tmp[0] << 64) | tmp[1])
2029 self._prefixlen = self._max_prefixlen
2030 self.netmask = IPv6Address(self._ALL_ONES)
Hynek Schlawacked36b2e2012-06-08 15:21:21 +02002031 return
Nick Coghlandc9b2552012-05-20 21:01:57 +10002032
2033 # Assume input argument to be string or any object representation
2034 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002035 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002036
2037 self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))
2038
2039 if len(addr) == 2:
2040 if self._is_valid_netmask(addr[1]):
2041 self._prefixlen = int(addr[1])
2042 else:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002043 raise NetmaskValueError('%r is not a valid netmask'
2044 % addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10002045 else:
2046 self._prefixlen = self._max_prefixlen
2047
2048 self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen))
2049 if strict:
2050 if (IPv6Address(int(self.network_address) & int(self.netmask)) !=
2051 self.network_address):
Nick Coghlan912238e2012-07-07 13:34:50 +10002052 raise ValueError('%s has host bits set' % self)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002053 self.network_address = IPv6Address(int(self.network_address) &
2054 int(self.netmask))
2055
2056 if self._prefixlen == (self._max_prefixlen - 1):
2057 self.hosts = self.__iter__
2058
Nick Coghlandc9b2552012-05-20 21:01:57 +10002059 def _is_valid_netmask(self, prefixlen):
2060 """Verify that the netmask/prefixlen is valid.
2061
2062 Args:
2063 prefixlen: A string, the netmask in prefix length format.
2064
2065 Returns:
2066 A boolean, True if the prefix represents a valid IPv6
2067 netmask.
2068
2069 """
2070 try:
2071 prefixlen = int(prefixlen)
2072 except ValueError:
2073 return False
2074 return 0 <= prefixlen <= self._max_prefixlen