blob: bd79e2a1dde80ec92183ee986029428404f8b504 [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):
654 if not isinstance(other, _BaseNetwork):
655 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000656 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000657 return (self._version == other._version and
658 self.network_address == other.network_address and
659 int(self.netmask) == int(other.netmask))
660
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:
1051 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
1594 raise ValueError("Part %d > 0xFFFF not permitted" % hextet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001595 return hextet_int
1596
1597 def _compress_hextets(self, hextets):
1598 """Compresses a list of hextets.
1599
1600 Compresses a list of strings, replacing the longest continuous
1601 sequence of "0" in the list with "" and adding empty strings at
1602 the beginning or at the end of the string such that subsequently
1603 calling ":".join(hextets) will produce the compressed version of
1604 the IPv6 address.
1605
1606 Args:
1607 hextets: A list of strings, the hextets to compress.
1608
1609 Returns:
1610 A list of strings.
1611
1612 """
1613 best_doublecolon_start = -1
1614 best_doublecolon_len = 0
1615 doublecolon_start = -1
1616 doublecolon_len = 0
1617 for index in range(len(hextets)):
1618 if hextets[index] == '0':
1619 doublecolon_len += 1
1620 if doublecolon_start == -1:
1621 # Start of a sequence of zeros.
1622 doublecolon_start = index
1623 if doublecolon_len > best_doublecolon_len:
1624 # This is the longest sequence of zeros so far.
1625 best_doublecolon_len = doublecolon_len
1626 best_doublecolon_start = doublecolon_start
1627 else:
1628 doublecolon_len = 0
1629 doublecolon_start = -1
1630
1631 if best_doublecolon_len > 1:
1632 best_doublecolon_end = (best_doublecolon_start +
1633 best_doublecolon_len)
1634 # For zeros at the end of the address.
1635 if best_doublecolon_end == len(hextets):
1636 hextets += ['']
1637 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1638 # For zeros at the beginning of the address.
1639 if best_doublecolon_start == 0:
1640 hextets = [''] + hextets
1641
1642 return hextets
1643
1644 def _string_from_ip_int(self, ip_int=None):
1645 """Turns a 128-bit integer into hexadecimal notation.
1646
1647 Args:
1648 ip_int: An integer, the IP address.
1649
1650 Returns:
1651 A string, the hexadecimal representation of the address.
1652
1653 Raises:
1654 ValueError: The address is bigger than 128 bits of all ones.
1655
1656 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001657 if ip_int is None:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001658 ip_int = int(self._ip)
1659
1660 if ip_int > self._ALL_ONES:
1661 raise ValueError('IPv6 address is too large')
1662
1663 hex_str = '%032x' % ip_int
Nick Coghlan7319f692012-07-07 21:43:30 +10001664 hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001665
1666 hextets = self._compress_hextets(hextets)
1667 return ':'.join(hextets)
1668
1669 def _explode_shorthand_ip_string(self):
1670 """Expand a shortened IPv6 address.
1671
1672 Args:
1673 ip_str: A string, the IPv6 address.
1674
1675 Returns:
1676 A string, the expanded IPv6 address.
1677
1678 """
1679 if isinstance(self, IPv6Network):
1680 ip_str = str(self.network_address)
1681 elif isinstance(self, IPv6Interface):
1682 ip_str = str(self.ip)
1683 else:
1684 ip_str = str(self)
1685
1686 ip_int = self._ip_int_from_string(ip_str)
Nick Coghlan7319f692012-07-07 21:43:30 +10001687 hex_str = '%032x' % ip_int
1688 parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001689 if isinstance(self, (_BaseNetwork, IPv6Interface)):
1690 return '%s/%d' % (':'.join(parts), self.prefixlen)
1691 return ':'.join(parts)
1692
1693 @property
1694 def max_prefixlen(self):
1695 return self._max_prefixlen
1696
1697 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001698 def version(self):
1699 return self._version
1700
1701 @property
1702 def is_multicast(self):
1703 """Test if the address is reserved for multicast use.
1704
1705 Returns:
1706 A boolean, True if the address is a multicast address.
1707 See RFC 2373 2.7 for details.
1708
1709 """
1710 multicast_network = IPv6Network('ff00::/8')
1711 if isinstance(self, _BaseAddress):
1712 return self in multicast_network
1713 return (self.network_address in multicast_network and
1714 self.broadcast_address in multicast_network)
1715
1716 @property
1717 def is_reserved(self):
1718 """Test if the address is otherwise IETF reserved.
1719
1720 Returns:
1721 A boolean, True if the address is within one of the
1722 reserved IPv6 Network ranges.
1723
1724 """
1725 reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'),
1726 IPv6Network('200::/7'), IPv6Network('400::/6'),
1727 IPv6Network('800::/5'), IPv6Network('1000::/4'),
1728 IPv6Network('4000::/3'), IPv6Network('6000::/3'),
1729 IPv6Network('8000::/3'), IPv6Network('A000::/3'),
1730 IPv6Network('C000::/3'), IPv6Network('E000::/4'),
1731 IPv6Network('F000::/5'), IPv6Network('F800::/6'),
1732 IPv6Network('FE00::/9')]
1733
1734 if isinstance(self, _BaseAddress):
Nick Coghlan7319f692012-07-07 21:43:30 +10001735 return any(self in x for x in reserved_networks)
1736 return any(self.network_address in x and self.broadcast_address in x
1737 for x in reserved_networks)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001738
1739 @property
1740 def is_link_local(self):
1741 """Test if the address is reserved for link-local.
1742
1743 Returns:
1744 A boolean, True if the address is reserved per RFC 4291.
1745
1746 """
1747 linklocal_network = IPv6Network('fe80::/10')
1748 if isinstance(self, _BaseAddress):
1749 return self in linklocal_network
1750 return (self.network_address in linklocal_network and
1751 self.broadcast_address in linklocal_network)
1752
1753 @property
1754 def is_site_local(self):
1755 """Test if the address is reserved for site-local.
1756
1757 Note that the site-local address space has been deprecated by RFC 3879.
1758 Use is_private to test if this address is in the space of unique local
1759 addresses as defined by RFC 4193.
1760
1761 Returns:
1762 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1763
1764 """
1765 sitelocal_network = IPv6Network('fec0::/10')
1766 if isinstance(self, _BaseAddress):
1767 return self in sitelocal_network
1768 return (self.network_address in sitelocal_network and
1769 self.broadcast_address in sitelocal_network)
1770
1771 @property
1772 def is_private(self):
1773 """Test if this address is allocated for private networks.
1774
1775 Returns:
1776 A boolean, True if the address is reserved per RFC 4193.
1777
1778 """
1779 private_network = IPv6Network('fc00::/7')
1780 if isinstance(self, _BaseAddress):
1781 return self in private_network
1782 return (self.network_address in private_network and
1783 self.broadcast_address in private_network)
1784
Nick Coghlandc9b2552012-05-20 21:01:57 +10001785 @property
1786 def ipv4_mapped(self):
1787 """Return the IPv4 mapped address.
1788
1789 Returns:
1790 If the IPv6 address is a v4 mapped address, return the
1791 IPv4 mapped address. Return None otherwise.
1792
1793 """
1794 if (self._ip >> 32) != 0xFFFF:
1795 return None
1796 return IPv4Address(self._ip & 0xFFFFFFFF)
1797
1798 @property
1799 def teredo(self):
1800 """Tuple of embedded teredo IPs.
1801
1802 Returns:
1803 Tuple of the (server, client) IPs or None if the address
1804 doesn't appear to be a teredo address (doesn't start with
1805 2001::/32)
1806
1807 """
1808 if (self._ip >> 96) != 0x20010000:
1809 return None
1810 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
1811 IPv4Address(~self._ip & 0xFFFFFFFF))
1812
1813 @property
1814 def sixtofour(self):
1815 """Return the IPv4 6to4 embedded address.
1816
1817 Returns:
1818 The IPv4 6to4-embedded address if present or None if the
1819 address doesn't appear to contain a 6to4 embedded address.
1820
1821 """
1822 if (self._ip >> 112) != 0x2002:
1823 return None
1824 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
1825
1826 @property
1827 def is_unspecified(self):
1828 """Test if the address is unspecified.
1829
1830 Returns:
1831 A boolean, True if this is the unspecified address as defined in
1832 RFC 2373 2.5.2.
1833
1834 """
1835 if isinstance(self, (IPv6Network, IPv6Interface)):
1836 return int(self.network_address) == 0 and getattr(
1837 self, '_prefixlen', 128) == 128
1838 return self._ip == 0
1839
1840 @property
1841 def is_loopback(self):
1842 """Test if the address is a loopback address.
1843
1844 Returns:
1845 A boolean, True if the address is a loopback address as defined in
1846 RFC 2373 2.5.3.
1847
1848 """
1849 if isinstance(self, IPv6Network):
Nick Coghlan2c589102012-05-27 01:03:25 +10001850 return int(self) == 1 and getattr(
Nick Coghlandc9b2552012-05-20 21:01:57 +10001851 self, '_prefixlen', 128) == 128
1852 elif isinstance(self, IPv6Interface):
1853 return int(self.network.network_address) == 1 and getattr(
1854 self, '_prefixlen', 128) == 128
1855 return self._ip == 1
1856
1857
1858class IPv6Address(_BaseV6, _BaseAddress):
1859
Sandro Tosib95c6342012-05-23 23:17:22 +02001860 """Represent and manipulate single IPv6 Addresses."""
Nick Coghlandc9b2552012-05-20 21:01:57 +10001861
1862 def __init__(self, address):
1863 """Instantiate a new IPv6 address object.
1864
1865 Args:
1866 address: A string or integer representing the IP
1867
1868 Additionally, an integer can be passed, so
1869 IPv6Address('2001:db8::') ==
1870 IPv6Address(42540766411282592856903984951653826560)
1871 or, more generally
1872 IPv6Address(int(IPv6Address('2001:db8::'))) ==
1873 IPv6Address('2001:db8::')
1874
1875 Raises:
1876 AddressValueError: If address isn't a valid IPv6 address.
1877
1878 """
1879 _BaseAddress.__init__(self, address)
1880 _BaseV6.__init__(self, address)
1881
1882 # Efficient constructor from integer.
1883 if isinstance(address, int):
1884 self._ip = address
1885 if address < 0 or address > self._ALL_ONES:
1886 raise AddressValueError(address)
1887 return
1888
1889 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001890 if isinstance(address, bytes):
1891 if len(address) != 16:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001892 msg = "Packed address %r must be exactly 16 bytes"
1893 raise AddressValueError(msg % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001894 tmp = struct.unpack('!QQ', address)
1895 self._ip = (tmp[0] << 64) | tmp[1]
1896 return
1897
1898 # Assume input argument to be string or any object representation
1899 # which converts into a formatted IP string.
1900 addr_str = str(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001901 self._ip = self._ip_int_from_string(addr_str)
1902
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001903 @property
1904 def packed(self):
1905 """The binary representation of this address."""
1906 return v6_int_to_packed(self._ip)
1907
Nick Coghlandc9b2552012-05-20 21:01:57 +10001908
1909class IPv6Interface(IPv6Address):
1910
1911 def __init__(self, address):
1912 if isinstance(address, (bytes, int)):
1913 IPv6Address.__init__(self, address)
1914 self.network = IPv6Network(self._ip)
1915 self._prefixlen = self._max_prefixlen
1916 return
1917
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001918 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001919 IPv6Address.__init__(self, addr[0])
1920 self.network = IPv6Network(address, strict=False)
1921 self.netmask = self.network.netmask
1922 self._prefixlen = self.network._prefixlen
1923 self.hostmask = self.network.hostmask
1924
Nick Coghlandc9b2552012-05-20 21:01:57 +10001925 def __str__(self):
1926 return '%s/%d' % (self._string_from_ip_int(self._ip),
1927 self.network.prefixlen)
1928
1929 def __eq__(self, other):
1930 try:
1931 return (IPv6Address.__eq__(self, other) and
1932 self.network == other.network)
1933 except AttributeError:
1934 return NotImplemented
1935
1936 def __hash__(self):
1937 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1938
1939 @property
1940 def prefixlen(self):
1941 return self._prefixlen
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001942
Nick Coghlandc9b2552012-05-20 21:01:57 +10001943 @property
1944 def ip(self):
1945 return IPv6Address(self._ip)
1946
1947 @property
1948 def with_prefixlen(self):
1949 return self
1950
1951 @property
1952 def with_netmask(self):
1953 return self.with_prefixlen
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001954
Nick Coghlandc9b2552012-05-20 21:01:57 +10001955 @property
1956 def with_hostmask(self):
1957 return '%s/%s' % (self._string_from_ip_int(self._ip),
1958 self.hostmask)
1959
1960
1961class IPv6Network(_BaseV6, _BaseNetwork):
1962
1963 """This class represents and manipulates 128-bit IPv6 networks.
1964
1965 Attributes: [examples for IPv6('2001:db8::1000/124')]
1966 .network_address: IPv6Address('2001:db8::1000')
1967 .hostmask: IPv6Address('::f')
1968 .broadcast_address: IPv6Address('2001:db8::100f')
1969 .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
1970 .prefixlen: 124
1971
1972 """
1973
Nick Coghlan51c30672012-05-27 00:25:58 +10001974 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001975 _address_class = IPv6Address
1976
Nick Coghlandc9b2552012-05-20 21:01:57 +10001977 def __init__(self, address, strict=True):
1978 """Instantiate a new IPv6 Network object.
1979
1980 Args:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001981 address: A string or integer representing the IPv6 network or the
1982 IP and prefix/netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001983 '2001:db8::/128'
1984 '2001:db8:0000:0000:0000:0000:0000:0000/128'
1985 '2001:db8::'
1986 are all functionally the same in IPv6. That is to say,
1987 failing to provide a subnetmask will create an object with
1988 a mask of /128.
1989
1990 Additionally, an integer can be passed, so
1991 IPv6Network('2001:db8::') ==
1992 IPv6Network(42540766411282592856903984951653826560)
1993 or, more generally
1994 IPv6Network(int(IPv6Network('2001:db8::'))) ==
1995 IPv6Network('2001:db8::')
1996
1997 strict: A boolean. If true, ensure that we have been passed
1998 A true network address, eg, 2001:db8::1000/124 and not an
1999 IP address on a network, eg, 2001:db8::1/124.
2000
2001 Raises:
2002 AddressValueError: If address isn't a valid IPv6 address.
2003 NetmaskValueError: If the netmask isn't valid for
2004 an IPv6 address.
2005 ValueError: If strict was True and a network address was not
2006 supplied.
2007
2008 """
2009 _BaseV6.__init__(self, address)
2010 _BaseNetwork.__init__(self, address)
2011
2012 # Efficient constructor from integer.
2013 if isinstance(address, int):
2014 if address < 0 or address > self._ALL_ONES:
2015 raise AddressValueError(address)
2016 self.network_address = IPv6Address(address)
2017 self._prefixlen = self._max_prefixlen
2018 self.netmask = IPv6Address(self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002019 return
2020
2021 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10002022 if isinstance(address, bytes):
2023 if len(address) != 16:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002024 msg = "Packed address %r must be exactly 16 bytes"
2025 raise AddressValueError(msg % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002026 tmp = struct.unpack('!QQ', address)
2027 self.network_address = IPv6Address((tmp[0] << 64) | tmp[1])
2028 self._prefixlen = self._max_prefixlen
2029 self.netmask = IPv6Address(self._ALL_ONES)
Hynek Schlawacked36b2e2012-06-08 15:21:21 +02002030 return
Nick Coghlandc9b2552012-05-20 21:01:57 +10002031
2032 # Assume input argument to be string or any object representation
2033 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002034 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002035
2036 self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))
2037
2038 if len(addr) == 2:
2039 if self._is_valid_netmask(addr[1]):
2040 self._prefixlen = int(addr[1])
2041 else:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002042 raise NetmaskValueError('%r is not a valid netmask'
2043 % addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10002044 else:
2045 self._prefixlen = self._max_prefixlen
2046
2047 self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen))
2048 if strict:
2049 if (IPv6Address(int(self.network_address) & int(self.netmask)) !=
2050 self.network_address):
Nick Coghlan912238e2012-07-07 13:34:50 +10002051 raise ValueError('%s has host bits set' % self)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002052 self.network_address = IPv6Address(int(self.network_address) &
2053 int(self.netmask))
2054
2055 if self._prefixlen == (self._max_prefixlen - 1):
2056 self.hosts = self.__iter__
2057
Nick Coghlandc9b2552012-05-20 21:01:57 +10002058 def _is_valid_netmask(self, prefixlen):
2059 """Verify that the netmask/prefixlen is valid.
2060
2061 Args:
2062 prefixlen: A string, the netmask in prefix length format.
2063
2064 Returns:
2065 A boolean, True if the prefix represents a valid IPv6
2066 netmask.
2067
2068 """
2069 try:
2070 prefixlen = int(prefixlen)
2071 except ValueError:
2072 return False
2073 return 0 <= prefixlen <= self._max_prefixlen