blob: 1e451f887372908a931d0fbb674997d8db0fa95c [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 Coghlan3008ec02012-07-08 00:45:33 +100014import functools
Hynek Schlawack91c5a342012-06-05 11:55:58 +020015
Nick Coghlandc9b2552012-05-20 21:01:57 +100016IPV4LENGTH = 32
17IPV6LENGTH = 128
18
Nick Coghlandc9b2552012-05-20 21:01:57 +100019class AddressValueError(ValueError):
20 """A Value Error related to the address."""
21
22
23class NetmaskValueError(ValueError):
24 """A Value Error related to the netmask."""
25
26
Nick Coghlan51c30672012-05-27 00:25:58 +100027def ip_address(address):
Nick Coghlandc9b2552012-05-20 21:01:57 +100028 """Take an IP string/int and return an object of the correct type.
29
30 Args:
31 address: A string or integer, the IP address. Either IPv4 or
32 IPv6 addresses may be supplied; integers less than 2**32 will
33 be considered to be IPv4 by default.
Nick Coghlandc9b2552012-05-20 21:01:57 +100034
35 Returns:
36 An IPv4Address or IPv6Address object.
37
38 Raises:
Sandro Tosi876ecad2012-05-23 22:26:55 +020039 ValueError: if the *address* passed isn't either a v4 or a v6
Nick Coghlan51c30672012-05-27 00:25:58 +100040 address
Nick Coghlandc9b2552012-05-20 21:01:57 +100041
42 """
Nick Coghlandc9b2552012-05-20 21:01:57 +100043 try:
44 return IPv4Address(address)
45 except (AddressValueError, NetmaskValueError):
46 pass
47
48 try:
49 return IPv6Address(address)
50 except (AddressValueError, NetmaskValueError):
51 pass
52
53 raise ValueError('%r does not appear to be an IPv4 or IPv6 address' %
54 address)
55
56
Nick Coghlan51c30672012-05-27 00:25:58 +100057def ip_network(address, strict=True):
Nick Coghlandc9b2552012-05-20 21:01:57 +100058 """Take an IP string/int and return an object of the correct type.
59
60 Args:
61 address: A string or integer, the IP network. Either IPv4 or
62 IPv6 networks may be supplied; integers less than 2**32 will
63 be considered to be IPv4 by default.
Nick Coghlandc9b2552012-05-20 21:01:57 +100064
65 Returns:
66 An IPv4Network or IPv6Network object.
67
68 Raises:
69 ValueError: if the string passed isn't either a v4 or a v6
Nick Coghlan51c30672012-05-27 00:25:58 +100070 address. Or if the network has host bits set.
Nick Coghlandc9b2552012-05-20 21:01:57 +100071
72 """
Nick Coghlandc9b2552012-05-20 21:01:57 +100073 try:
74 return IPv4Network(address, strict)
75 except (AddressValueError, NetmaskValueError):
76 pass
77
78 try:
79 return IPv6Network(address, strict)
80 except (AddressValueError, NetmaskValueError):
81 pass
82
83 raise ValueError('%r does not appear to be an IPv4 or IPv6 network' %
84 address)
85
86
Nick Coghlan51c30672012-05-27 00:25:58 +100087def ip_interface(address):
Nick Coghlandc9b2552012-05-20 21:01:57 +100088 """Take an IP string/int and return an object of the correct type.
89
90 Args:
91 address: A string or integer, the IP address. Either IPv4 or
92 IPv6 addresses may be supplied; integers less than 2**32 will
93 be considered to be IPv4 by default.
Nick Coghlandc9b2552012-05-20 21:01:57 +100094
95 Returns:
Sandro Tosi876ecad2012-05-23 22:26:55 +020096 An IPv4Interface or IPv6Interface object.
Nick Coghlandc9b2552012-05-20 21:01:57 +100097
98 Raises:
99 ValueError: if the string passed isn't either a v4 or a v6
Nick Coghlan51c30672012-05-27 00:25:58 +1000100 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000101
102 Notes:
103 The IPv?Interface classes describe an Address on a particular
104 Network, so they're basically a combination of both the Address
105 and Network classes.
Sandro Tosib95c6342012-05-23 23:17:22 +0200106
Nick Coghlandc9b2552012-05-20 21:01:57 +1000107 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000108 try:
109 return IPv4Interface(address)
110 except (AddressValueError, NetmaskValueError):
111 pass
112
113 try:
114 return IPv6Interface(address)
115 except (AddressValueError, NetmaskValueError):
116 pass
117
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000118 raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' %
Nick Coghlandc9b2552012-05-20 21:01:57 +1000119 address)
120
121
122def v4_int_to_packed(address):
Sandro Tosi876ecad2012-05-23 22:26:55 +0200123 """Represent an address as 4 packed bytes in network (big-endian) order.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000124
125 Args:
126 address: An integer representation of an IPv4 IP address.
127
128 Returns:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200129 The integer address packed as 4 bytes in network (big-endian) order.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000130
131 Raises:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200132 ValueError: If the integer is negative or too large to be an
133 IPv4 IP address.
Sandro Tosib95c6342012-05-23 23:17:22 +0200134
Nick Coghlandc9b2552012-05-20 21:01:57 +1000135 """
Sandro Tosi876ecad2012-05-23 22:26:55 +0200136 try:
Nick Coghlandb7920b2012-08-20 10:19:12 +1000137 return address.to_bytes(4, 'big')
Sandro Tosi876ecad2012-05-23 22:26:55 +0200138 except:
139 raise ValueError("Address negative or too large for IPv4")
Nick Coghlandc9b2552012-05-20 21:01:57 +1000140
141
142def v6_int_to_packed(address):
Sandro Tosi876ecad2012-05-23 22:26:55 +0200143 """Represent an address as 16 packed bytes in network (big-endian) order.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000144
145 Args:
Sandro Tosib4386d32012-06-02 17:14:22 +0200146 address: An integer representation of an IPv6 IP address.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000147
148 Returns:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200149 The integer address packed as 16 bytes in network (big-endian) order.
Sandro Tosib95c6342012-05-23 23:17:22 +0200150
Nick Coghlandc9b2552012-05-20 21:01:57 +1000151 """
Sandro Tosi876ecad2012-05-23 22:26:55 +0200152 try:
Nick Coghlandb7920b2012-08-20 10:19:12 +1000153 return address.to_bytes(16, 'big')
Sandro Tosi876ecad2012-05-23 22:26:55 +0200154 except:
155 raise ValueError("Address negative or too large for IPv6")
Nick Coghlandc9b2552012-05-20 21:01:57 +1000156
157
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000158def _split_optional_netmask(address):
159 """Helper to split the netmask and raise AddressValueError if needed"""
160 addr = str(address).split('/')
161 if len(addr) > 2:
162 raise AddressValueError("Only one '/' permitted in %r" % address)
163 return addr
164
Nick Coghlan297b1432012-07-08 17:11:04 +1000165
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 _count_righthand_zero_bits(number, bits):
186 """Count the number of zero bits on the right hand side.
187
188 Args:
189 number: an integer.
190 bits: maximum number of bits to count.
191
192 Returns:
193 The number of zero bits on the right hand side of the number.
194
195 """
196 if number == 0:
197 return bits
198 for i in range(bits):
Nick Coghlan7319f692012-07-07 21:43:30 +1000199 if (number >> i) & 1:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000200 return i
Nick Coghlan7319f692012-07-07 21:43:30 +1000201 # All bits of interest were zero, even if there are more in the number
202 return bits
Nick Coghlandc9b2552012-05-20 21:01:57 +1000203
204
205def summarize_address_range(first, last):
206 """Summarize a network range given the first and last IP addresses.
207
208 Example:
Eli Bendersky948af232012-10-07 07:23:50 -0700209 >>> list(summarize_address_range(IPv4Address('192.0.2.0'),
210 ... IPv4Address('192.0.2.130')))
211 ... #doctest: +NORMALIZE_WHITESPACE
Nick Coghlandc9b2552012-05-20 21:01:57 +1000212 [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'),
Eli Bendersky948af232012-10-07 07:23:50 -0700213 IPv4Network('192.0.2.130/32')]
Nick Coghlandc9b2552012-05-20 21:01:57 +1000214
215 Args:
216 first: the first IPv4Address or IPv6Address in the range.
217 last: the last IPv4Address or IPv6Address in the range.
218
219 Returns:
220 An iterator of the summarized IPv(4|6) network objects.
221
222 Raise:
223 TypeError:
224 If the first and last objects are not IP addresses.
225 If the first and last objects are not the same version.
226 ValueError:
227 If the last object is not greater than the first.
Nick Coghlan51c30672012-05-27 00:25:58 +1000228 If the version of the first address is not 4 or 6.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000229
230 """
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200231 if (not (isinstance(first, _BaseAddress) and
232 isinstance(last, _BaseAddress))):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000233 raise TypeError('first and last must be IP addresses, not networks')
234 if first.version != last.version:
235 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000236 first, last))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000237 if first > last:
238 raise ValueError('last IP address must be greater than first')
239
Nick Coghlandc9b2552012-05-20 21:01:57 +1000240 if first.version == 4:
241 ip = IPv4Network
242 elif first.version == 6:
243 ip = IPv6Network
244 else:
245 raise ValueError('unknown IP version')
246
247 ip_bits = first._max_prefixlen
248 first_int = first._ip
249 last_int = last._ip
250 while first_int <= last_int:
Nick Coghlan7319f692012-07-07 21:43:30 +1000251 nbits = min(_count_righthand_zero_bits(first_int, ip_bits),
252 (last_int - first_int + 1).bit_length() - 1)
253 net = ip('%s/%d' % (first, ip_bits - nbits))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000254 yield net
Nick Coghlan7319f692012-07-07 21:43:30 +1000255 first_int += 1 << nbits
256 if first_int - 1 == ip._ALL_ONES:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000257 break
Nick Coghlan51c30672012-05-27 00:25:58 +1000258 first = first.__class__(first_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000259
Sandro Tosib95c6342012-05-23 23:17:22 +0200260
Nick Coghlandc9b2552012-05-20 21:01:57 +1000261def _collapse_addresses_recursive(addresses):
262 """Loops through the addresses, collapsing concurrent netblocks.
263
264 Example:
265
266 ip1 = IPv4Network('192.0.2.0/26')
267 ip2 = IPv4Network('192.0.2.64/26')
268 ip3 = IPv4Network('192.0.2.128/26')
269 ip4 = IPv4Network('192.0.2.192/26')
270
271 _collapse_addresses_recursive([ip1, ip2, ip3, ip4]) ->
272 [IPv4Network('192.0.2.0/24')]
273
274 This shouldn't be called directly; it is called via
275 collapse_addresses([]).
276
277 Args:
278 addresses: A list of IPv4Network's or IPv6Network's
279
280 Returns:
281 A list of IPv4Network's or IPv6Network's depending on what we were
282 passed.
283
284 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000285 while True:
286 last_addr = None
287 ret_array = []
288 optimized = False
Nick Coghlandc9b2552012-05-20 21:01:57 +1000289
Nick Coghlan7319f692012-07-07 21:43:30 +1000290 for cur_addr in addresses:
291 if not ret_array:
292 last_addr = cur_addr
293 ret_array.append(cur_addr)
294 elif (cur_addr.network_address >= last_addr.network_address and
295 cur_addr.broadcast_address <= last_addr.broadcast_address):
296 optimized = True
297 elif cur_addr == list(last_addr.supernet().subnets())[1]:
298 ret_array[-1] = last_addr = last_addr.supernet()
299 optimized = True
300 else:
301 last_addr = cur_addr
302 ret_array.append(cur_addr)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000303
Nick Coghlan7319f692012-07-07 21:43:30 +1000304 addresses = ret_array
305 if not optimized:
306 return addresses
Nick Coghlandc9b2552012-05-20 21:01:57 +1000307
308
309def collapse_addresses(addresses):
310 """Collapse a list of IP objects.
311
312 Example:
313 collapse_addresses([IPv4Network('192.0.2.0/25'),
314 IPv4Network('192.0.2.128/25')]) ->
315 [IPv4Network('192.0.2.0/24')]
316
317 Args:
318 addresses: An iterator of IPv4Network or IPv6Network objects.
319
320 Returns:
321 An iterator of the collapsed IPv(4|6)Network objects.
322
323 Raises:
324 TypeError: If passed a list of mixed version objects.
325
326 """
327 i = 0
328 addrs = []
329 ips = []
330 nets = []
331
332 # split IP addresses and networks
333 for ip in addresses:
334 if isinstance(ip, _BaseAddress):
335 if ips and ips[-1]._version != ip._version:
336 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000337 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000338 ips.append(ip)
339 elif ip._prefixlen == ip._max_prefixlen:
340 if ips and ips[-1]._version != ip._version:
341 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000342 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000343 try:
344 ips.append(ip.ip)
345 except AttributeError:
346 ips.append(ip.network_address)
347 else:
348 if nets and nets[-1]._version != ip._version:
349 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000350 ip, nets[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000351 nets.append(ip)
352
353 # sort and dedup
354 ips = sorted(set(ips))
355 nets = sorted(set(nets))
356
357 while i < len(ips):
358 (first, last) = _find_address_range(ips[i:])
359 i = ips.index(last) + 1
360 addrs.extend(summarize_address_range(first, last))
361
362 return iter(_collapse_addresses_recursive(sorted(
363 addrs + nets, key=_BaseNetwork._get_networks_key)))
364
365
366def get_mixed_type_key(obj):
367 """Return a key suitable for sorting between networks and addresses.
368
369 Address and Network objects are not sortable by default; they're
370 fundamentally different so the expression
371
372 IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
373
374 doesn't make any sense. There are some times however, where you may wish
375 to have ipaddress sort these for you anyway. If you need to do this, you
376 can use this function as the key= argument to sorted().
377
378 Args:
379 obj: either a Network or Address object.
380 Returns:
381 appropriate key.
382
383 """
384 if isinstance(obj, _BaseNetwork):
385 return obj._get_networks_key()
386 elif isinstance(obj, _BaseAddress):
387 return obj._get_address_key()
388 return NotImplemented
389
390
Nick Coghlan3008ec02012-07-08 00:45:33 +1000391class _TotalOrderingMixin:
392 # Helper that derives the other comparison operations from
393 # __lt__ and __eq__
Nick Coghlan297b1432012-07-08 17:11:04 +1000394 # We avoid functools.total_ordering because it doesn't handle
395 # NotImplemented correctly yet (http://bugs.python.org/issue10042)
Nick Coghlan3008ec02012-07-08 00:45:33 +1000396 def __eq__(self, other):
397 raise NotImplementedError
398 def __ne__(self, other):
399 equal = self.__eq__(other)
400 if equal is NotImplemented:
401 return NotImplemented
402 return not equal
403 def __lt__(self, other):
404 raise NotImplementedError
405 def __le__(self, other):
406 less = self.__lt__(other)
407 if less is NotImplemented or not less:
408 return self.__eq__(other)
409 return less
410 def __gt__(self, other):
411 less = self.__lt__(other)
412 if less is NotImplemented:
413 return NotImplemented
414 equal = self.__eq__(other)
415 if equal is NotImplemented:
416 return NotImplemented
417 return not (less or equal)
418 def __ge__(self, other):
419 less = self.__lt__(other)
420 if less is NotImplemented:
421 return NotImplemented
422 return not less
423
424class _IPAddressBase(_TotalOrderingMixin):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000425
426 """The mother class."""
427
428 @property
429 def exploded(self):
430 """Return the longhand version of the IP address as a string."""
431 return self._explode_shorthand_ip_string()
432
433 @property
434 def compressed(self):
435 """Return the shorthand version of the IP address as a string."""
436 return str(self)
437
Nick Coghland9722652012-06-17 16:33:00 +1000438 @property
Eric V. Smithebdaaf42014-04-14 12:58:07 -0400439 def reverse_pointer(self):
440 """The name of the reverse DNS pointer for the IP address, e.g.:
441 >>> ipaddress.ip_address("127.0.0.1").reverse_pointer
442 '1.0.0.127.in-addr.arpa'
443 >>> ipaddress.ip_address("2001:db8::1").reverse_pointer
444 '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa'
445
446 """
447 return self._reverse_pointer()
448
449 @property
Nick Coghland9722652012-06-17 16:33:00 +1000450 def version(self):
451 msg = '%200s has no version specified' % (type(self),)
452 raise NotImplementedError(msg)
453
Nick Coghlan297b1432012-07-08 17:11:04 +1000454 def _check_int_address(self, address):
455 if address < 0:
456 msg = "%d (< 0) is not permitted as an IPv%d address"
457 raise AddressValueError(msg % (address, self._version))
458 if address > self._ALL_ONES:
459 msg = "%d (>= 2**%d) is not permitted as an IPv%d address"
460 raise AddressValueError(msg % (address, self._max_prefixlen,
461 self._version))
462
463 def _check_packed_address(self, address, expected_len):
464 address_len = len(address)
465 if address_len != expected_len:
466 msg = "%r (len %d != %d) is not permitted as an IPv%d address"
467 raise AddressValueError(msg % (address, address_len,
468 expected_len, self._version))
469
Nick Coghlan932346f2014-02-08 23:17:36 +1000470 def _ip_int_from_prefix(self, prefixlen):
471 """Turn the prefix length into a bitwise netmask
Nick Coghlandc9b2552012-05-20 21:01:57 +1000472
473 Args:
474 prefixlen: An integer, the prefix length.
475
476 Returns:
477 An integer.
478
479 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000480 return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen)
481
Nick Coghlan932346f2014-02-08 23:17:36 +1000482 def _prefix_from_ip_int(self, ip_int):
483 """Return prefix length from the bitwise netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000484
485 Args:
Nick Coghlan932346f2014-02-08 23:17:36 +1000486 ip_int: An integer, the netmask in axpanded bitwise format
Nick Coghlandc9b2552012-05-20 21:01:57 +1000487
488 Returns:
489 An integer, the prefix length.
490
Nick Coghlan932346f2014-02-08 23:17:36 +1000491 Raises:
492 ValueError: If the input intermingles zeroes & ones
Nick Coghlandc9b2552012-05-20 21:01:57 +1000493 """
Nick Coghlan932346f2014-02-08 23:17:36 +1000494 trailing_zeroes = _count_righthand_zero_bits(ip_int,
495 self._max_prefixlen)
496 prefixlen = self._max_prefixlen - trailing_zeroes
497 leading_ones = ip_int >> trailing_zeroes
498 all_ones = (1 << prefixlen) - 1
499 if leading_ones != all_ones:
500 byteslen = self._max_prefixlen // 8
501 details = ip_int.to_bytes(byteslen, 'big')
502 msg = 'Netmask pattern %r mixes zeroes & ones'
503 raise ValueError(msg % details)
504 return prefixlen
Nick Coghlandc9b2552012-05-20 21:01:57 +1000505
Nick Coghlan932346f2014-02-08 23:17:36 +1000506 def _report_invalid_netmask(self, netmask_str):
507 msg = '%r is not a valid netmask' % netmask_str
508 raise NetmaskValueError(msg) from None
509
510 def _prefix_from_prefix_string(self, prefixlen_str):
511 """Return prefix length from a numeric string
Nick Coghlandc9b2552012-05-20 21:01:57 +1000512
513 Args:
Nick Coghlan932346f2014-02-08 23:17:36 +1000514 prefixlen_str: The string to be converted
Nick Coghlandc9b2552012-05-20 21:01:57 +1000515
516 Returns:
Nick Coghlan932346f2014-02-08 23:17:36 +1000517 An integer, the prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000518
Nick Coghlan932346f2014-02-08 23:17:36 +1000519 Raises:
520 NetmaskValueError: If the input is not a valid netmask
Nick Coghlandc9b2552012-05-20 21:01:57 +1000521 """
Nick Coghlan932346f2014-02-08 23:17:36 +1000522 # int allows a leading +/- as well as surrounding whitespace,
523 # so we ensure that isn't the case
524 if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
525 self._report_invalid_netmask(prefixlen_str)
526 try:
527 prefixlen = int(prefixlen_str)
528 except ValueError:
529 self._report_invalid_netmask(prefixlen_str)
530 if not (0 <= prefixlen <= self._max_prefixlen):
531 self._report_invalid_netmask(prefixlen_str)
532 return prefixlen
533
534 def _prefix_from_ip_string(self, ip_str):
535 """Turn a netmask/hostmask string into a prefix length
536
537 Args:
538 ip_str: The netmask/hostmask to be converted
539
540 Returns:
541 An integer, the prefix length.
542
543 Raises:
544 NetmaskValueError: If the input is not a valid netmask/hostmask
545 """
546 # Parse the netmask/hostmask like an IP address.
547 try:
548 ip_int = self._ip_int_from_string(ip_str)
549 except AddressValueError:
550 self._report_invalid_netmask(ip_str)
551
552 # Try matching a netmask (this would be /1*0*/ as a bitwise regexp).
553 # Note that the two ambiguous cases (all-ones and all-zeroes) are
554 # treated as netmasks.
555 try:
556 return self._prefix_from_ip_int(ip_int)
557 except ValueError:
558 pass
559
560 # Invert the bits, and try matching a /0+1+/ hostmask instead.
561 ip_int ^= self._ALL_ONES
562 try:
563 return self._prefix_from_ip_int(ip_int)
564 except ValueError:
565 self._report_invalid_netmask(ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000566
Nick Coghlan730f67f2012-08-05 22:02:18 +1000567
Nick Coghlandc9b2552012-05-20 21:01:57 +1000568class _BaseAddress(_IPAddressBase):
569
570 """A generic IP object.
571
572 This IP class contains the version independent methods which are
573 used by single IP addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000574 """
575
576 def __init__(self, address):
577 if (not isinstance(address, bytes)
578 and '/' in str(address)):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000579 raise AddressValueError("Unexpected '/' in %r" % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000580
Nick Coghlandc9b2552012-05-20 21:01:57 +1000581 def __int__(self):
582 return self._ip
583
Nick Coghlandc9b2552012-05-20 21:01:57 +1000584 def __eq__(self, other):
585 try:
586 return (self._ip == other._ip
587 and self._version == other._version)
588 except AttributeError:
589 return NotImplemented
590
Nick Coghlandc9b2552012-05-20 21:01:57 +1000591 def __lt__(self, other):
592 if self._version != other._version:
593 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000594 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000595 if not isinstance(other, _BaseAddress):
596 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000597 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000598 if self._ip != other._ip:
599 return self._ip < other._ip
600 return False
601
Nick Coghlandc9b2552012-05-20 21:01:57 +1000602 # Shorthand for Integer addition and subtraction. This is not
603 # meant to ever support addition/subtraction of addresses.
604 def __add__(self, other):
605 if not isinstance(other, int):
606 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000607 return self.__class__(int(self) + other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000608
609 def __sub__(self, other):
610 if not isinstance(other, int):
611 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000612 return self.__class__(int(self) - other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000613
614 def __repr__(self):
615 return '%s(%r)' % (self.__class__.__name__, str(self))
616
617 def __str__(self):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200618 return str(self._string_from_ip_int(self._ip))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000619
620 def __hash__(self):
621 return hash(hex(int(self._ip)))
622
623 def _get_address_key(self):
624 return (self._version, self)
625
Nick Coghlandc9b2552012-05-20 21:01:57 +1000626
627class _BaseNetwork(_IPAddressBase):
628
Nick Coghlan51c30672012-05-27 00:25:58 +1000629 """A generic IP network object.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000630
631 This IP class contains the version independent methods which are
632 used by networks.
633
634 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000635 def __init__(self, address):
636 self._cache = {}
637
Nick Coghlandc9b2552012-05-20 21:01:57 +1000638 def __repr__(self):
639 return '%s(%r)' % (self.__class__.__name__, str(self))
640
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200641 def __str__(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000642 return '%s/%d' % (self.network_address, self.prefixlen)
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200643
Nick Coghlandc9b2552012-05-20 21:01:57 +1000644 def hosts(self):
645 """Generate Iterator over usable hosts in a network.
646
Sandro Tosib95c6342012-05-23 23:17:22 +0200647 This is like __iter__ except it doesn't return the network
648 or broadcast addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000649
650 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000651 network = int(self.network_address)
652 broadcast = int(self.broadcast_address)
653 for x in range(network + 1, broadcast):
654 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000655
656 def __iter__(self):
Nick Coghlan7319f692012-07-07 21:43:30 +1000657 network = int(self.network_address)
658 broadcast = int(self.broadcast_address)
659 for x in range(network, broadcast + 1):
660 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000661
662 def __getitem__(self, n):
663 network = int(self.network_address)
664 broadcast = int(self.broadcast_address)
665 if n >= 0:
666 if network + n > broadcast:
667 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000668 return self._address_class(network + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000669 else:
670 n += 1
671 if broadcast + n < network:
672 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000673 return self._address_class(broadcast + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000674
675 def __lt__(self, other):
676 if self._version != other._version:
677 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000678 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000679 if not isinstance(other, _BaseNetwork):
680 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000681 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000682 if self.network_address != other.network_address:
683 return self.network_address < other.network_address
684 if self.netmask != other.netmask:
685 return self.netmask < other.netmask
686 return False
687
Nick Coghlandc9b2552012-05-20 21:01:57 +1000688 def __eq__(self, other):
Nick Coghlan9a9c28c2012-07-07 23:05:59 +1000689 try:
690 return (self._version == other._version and
691 self.network_address == other.network_address and
692 int(self.netmask) == int(other.netmask))
693 except AttributeError:
694 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000695
Nick Coghlandc9b2552012-05-20 21:01:57 +1000696 def __hash__(self):
697 return hash(int(self.network_address) ^ int(self.netmask))
698
699 def __contains__(self, other):
700 # always false if one is v4 and the other is v6.
701 if self._version != other._version:
702 return False
703 # dealing with another network.
704 if isinstance(other, _BaseNetwork):
705 return False
706 # dealing with another address
707 else:
708 # address
709 return (int(self.network_address) <= int(other._ip) <=
710 int(self.broadcast_address))
711
712 def overlaps(self, other):
713 """Tell if self is partly contained in other."""
714 return self.network_address in other or (
715 self.broadcast_address in other or (
716 other.network_address in self or (
717 other.broadcast_address in self)))
718
719 @property
720 def broadcast_address(self):
721 x = self._cache.get('broadcast_address')
722 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000723 x = self._address_class(int(self.network_address) |
724 int(self.hostmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000725 self._cache['broadcast_address'] = x
726 return x
727
728 @property
729 def hostmask(self):
730 x = self._cache.get('hostmask')
731 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000732 x = self._address_class(int(self.netmask) ^ self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000733 self._cache['hostmask'] = x
734 return x
735
736 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000737 def with_prefixlen(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000738 return '%s/%d' % (self.network_address, self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000739
740 @property
741 def with_netmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000742 return '%s/%s' % (self.network_address, self.netmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000743
744 @property
745 def with_hostmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000746 return '%s/%s' % (self.network_address, self.hostmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000747
748 @property
749 def num_addresses(self):
750 """Number of hosts in the current subnet."""
751 return int(self.broadcast_address) - int(self.network_address) + 1
752
753 @property
Nick Coghlan51c30672012-05-27 00:25:58 +1000754 def _address_class(self):
Nick Coghland9722652012-06-17 16:33:00 +1000755 # Returning bare address objects (rather than interfaces) allows for
756 # more consistent behaviour across the network address, broadcast
757 # address and individual host addresses.
758 msg = '%200s has no associated address class' % (type(self),)
759 raise NotImplementedError(msg)
Nick Coghlan51c30672012-05-27 00:25:58 +1000760
761 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000762 def prefixlen(self):
763 return self._prefixlen
764
765 def address_exclude(self, other):
766 """Remove an address from a larger block.
767
768 For example:
769
770 addr1 = ip_network('192.0.2.0/28')
771 addr2 = ip_network('192.0.2.1/32')
772 addr1.address_exclude(addr2) =
773 [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
774 IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
775
776 or IPv6:
777
778 addr1 = ip_network('2001:db8::1/32')
779 addr2 = ip_network('2001:db8::1/128')
780 addr1.address_exclude(addr2) =
781 [ip_network('2001:db8::1/128'),
782 ip_network('2001:db8::2/127'),
783 ip_network('2001:db8::4/126'),
784 ip_network('2001:db8::8/125'),
785 ...
786 ip_network('2001:db8:8000::/33')]
787
788 Args:
789 other: An IPv4Network or IPv6Network object of the same type.
790
791 Returns:
Ezio Melotti3f5db392013-01-27 06:20:14 +0200792 An iterator of the IPv(4|6)Network objects which is self
Nick Coghlandc9b2552012-05-20 21:01:57 +1000793 minus other.
794
795 Raises:
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300796 TypeError: If self and other are of differing address
Nick Coghlandc9b2552012-05-20 21:01:57 +1000797 versions, or if other is not a network object.
798 ValueError: If other is not completely contained by self.
799
800 """
801 if not self._version == other._version:
802 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000803 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000804
805 if not isinstance(other, _BaseNetwork):
Nick Coghlan912238e2012-07-07 13:34:50 +1000806 raise TypeError("%s is not a network object" % other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000807
808 if not (other.network_address >= self.network_address and
809 other.broadcast_address <= self.broadcast_address):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200810 raise ValueError('%s not contained in %s' % (other, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000811 if other == self:
812 raise StopIteration
813
Nick Coghlandc9b2552012-05-20 21:01:57 +1000814 # Make sure we're comparing the network of other.
Nick Coghlan912238e2012-07-07 13:34:50 +1000815 other = other.__class__('%s/%s' % (other.network_address,
816 other.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000817
818 s1, s2 = self.subnets()
819 while s1 != other and s2 != other:
820 if (other.network_address >= s1.network_address and
821 other.broadcast_address <= s1.broadcast_address):
822 yield s2
823 s1, s2 = s1.subnets()
824 elif (other.network_address >= s2.network_address and
825 other.broadcast_address <= s2.broadcast_address):
826 yield s1
827 s1, s2 = s2.subnets()
828 else:
829 # If we got here, there's a bug somewhere.
830 raise AssertionError('Error performing exclusion: '
831 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000832 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000833 if s1 == other:
834 yield s2
835 elif s2 == other:
836 yield s1
837 else:
838 # If we got here, there's a bug somewhere.
839 raise AssertionError('Error performing exclusion: '
840 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000841 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000842
843 def compare_networks(self, other):
844 """Compare two IP objects.
845
846 This is only concerned about the comparison of the integer
847 representation of the network addresses. This means that the
848 host bits aren't considered at all in this method. If you want
849 to compare host bits, you can easily enough do a
850 'HostA._ip < HostB._ip'
851
852 Args:
853 other: An IP object.
854
855 Returns:
856 If the IP versions of self and other are the same, returns:
857
858 -1 if self < other:
859 eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
860 IPv6Network('2001:db8::1000/124') <
861 IPv6Network('2001:db8::2000/124')
862 0 if self == other
863 eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
864 IPv6Network('2001:db8::1000/124') ==
865 IPv6Network('2001:db8::1000/124')
866 1 if self > other
867 eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
868 IPv6Network('2001:db8::2000/124') >
869 IPv6Network('2001:db8::1000/124')
870
871 Raises:
872 TypeError if the IP versions are different.
873
874 """
875 # does this need to raise a ValueError?
876 if self._version != other._version:
877 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000878 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000879 # self._version == other._version below here:
880 if self.network_address < other.network_address:
881 return -1
882 if self.network_address > other.network_address:
883 return 1
884 # self.network_address == other.network_address below here:
885 if self.netmask < other.netmask:
886 return -1
887 if self.netmask > other.netmask:
888 return 1
889 return 0
890
891 def _get_networks_key(self):
892 """Network-only key function.
893
894 Returns an object that identifies this address' network and
895 netmask. This function is a suitable "key" argument for sorted()
896 and list.sort().
897
898 """
899 return (self._version, self.network_address, self.netmask)
900
901 def subnets(self, prefixlen_diff=1, new_prefix=None):
902 """The subnets which join to make the current subnet.
903
904 In the case that self contains only one IP
905 (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
906 for IPv6), yield an iterator with just ourself.
907
908 Args:
909 prefixlen_diff: An integer, the amount the prefix length
910 should be increased by. This should not be set if
911 new_prefix is also set.
912 new_prefix: The desired new prefix length. This must be a
913 larger number (smaller prefix) than the existing prefix.
914 This should not be set if prefixlen_diff is also set.
915
916 Returns:
917 An iterator of IPv(4|6) objects.
918
919 Raises:
920 ValueError: The prefixlen_diff is too small or too large.
921 OR
922 prefixlen_diff and new_prefix are both set or new_prefix
923 is a smaller number than the current prefix (smaller
924 number means a larger network)
925
926 """
927 if self._prefixlen == self._max_prefixlen:
928 yield self
929 return
930
931 if new_prefix is not None:
932 if new_prefix < self._prefixlen:
933 raise ValueError('new prefix must be longer')
934 if prefixlen_diff != 1:
935 raise ValueError('cannot set prefixlen_diff and new_prefix')
936 prefixlen_diff = new_prefix - self._prefixlen
937
938 if prefixlen_diff < 0:
939 raise ValueError('prefix length diff must be > 0')
940 new_prefixlen = self._prefixlen + prefixlen_diff
941
Nick Coghlan932346f2014-02-08 23:17:36 +1000942 if new_prefixlen > self._max_prefixlen:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000943 raise ValueError(
944 'prefix length diff %d is invalid for netblock %s' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000945 new_prefixlen, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000946
Nick Coghlan51c30672012-05-27 00:25:58 +1000947 first = self.__class__('%s/%s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000948 (self.network_address,
949 self._prefixlen + prefixlen_diff))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000950
951 yield first
952 current = first
953 while True:
954 broadcast = current.broadcast_address
955 if broadcast == self.broadcast_address:
956 return
Nick Coghlan51c30672012-05-27 00:25:58 +1000957 new_addr = self._address_class(int(broadcast) + 1)
Nick Coghlan912238e2012-07-07 13:34:50 +1000958 current = self.__class__('%s/%s' % (new_addr,
959 new_prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000960
961 yield current
962
Nick Coghlandc9b2552012-05-20 21:01:57 +1000963 def supernet(self, prefixlen_diff=1, new_prefix=None):
964 """The supernet containing the current network.
965
966 Args:
967 prefixlen_diff: An integer, the amount the prefix length of
968 the network should be decreased by. For example, given a
969 /24 network and a prefixlen_diff of 3, a supernet with a
970 /21 netmask is returned.
971
972 Returns:
973 An IPv4 network object.
974
975 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200976 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
977 a negative prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000978 OR
979 If prefixlen_diff and new_prefix are both set or new_prefix is a
980 larger number than the current prefix (larger number means a
981 smaller network)
982
983 """
984 if self._prefixlen == 0:
985 return self
986
987 if new_prefix is not None:
988 if new_prefix > self._prefixlen:
989 raise ValueError('new prefix must be shorter')
990 if prefixlen_diff != 1:
991 raise ValueError('cannot set prefixlen_diff and new_prefix')
992 prefixlen_diff = self._prefixlen - new_prefix
993
Nick Coghlandc9b2552012-05-20 21:01:57 +1000994 if self.prefixlen - prefixlen_diff < 0:
995 raise ValueError(
996 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
997 (self.prefixlen, prefixlen_diff))
998 # TODO (pmoody): optimize this.
Nick Coghlan912238e2012-07-07 13:34:50 +1000999 t = self.__class__('%s/%d' % (self.network_address,
Nick Coghlan51c30672012-05-27 00:25:58 +10001000 self.prefixlen - prefixlen_diff),
1001 strict=False)
Nick Coghlan912238e2012-07-07 13:34:50 +10001002 return t.__class__('%s/%d' % (t.network_address, t.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001003
Nick Coghlan730f67f2012-08-05 22:02:18 +10001004 @property
1005 def is_multicast(self):
1006 """Test if the address is reserved for multicast use.
1007
1008 Returns:
1009 A boolean, True if the address is a multicast address.
1010 See RFC 2373 2.7 for details.
1011
1012 """
1013 return (self.network_address.is_multicast and
1014 self.broadcast_address.is_multicast)
1015
1016 @property
1017 def is_reserved(self):
1018 """Test if the address is otherwise IETF reserved.
1019
1020 Returns:
1021 A boolean, True if the address is within one of the
1022 reserved IPv6 Network ranges.
1023
1024 """
1025 return (self.network_address.is_reserved and
1026 self.broadcast_address.is_reserved)
1027
1028 @property
1029 def is_link_local(self):
1030 """Test if the address is reserved for link-local.
1031
1032 Returns:
1033 A boolean, True if the address is reserved per RFC 4291.
1034
1035 """
1036 return (self.network_address.is_link_local and
1037 self.broadcast_address.is_link_local)
1038
1039 @property
1040 def is_private(self):
1041 """Test if this address is allocated for private networks.
1042
1043 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001044 A boolean, True if the address is reserved per
1045 iana-ipv4-special-registry or iana-ipv6-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001046
1047 """
1048 return (self.network_address.is_private and
1049 self.broadcast_address.is_private)
1050
1051 @property
Peter Moody22c31762013-10-21 13:58:06 -07001052 def is_global(self):
Peter Moodybe9c1b12013-10-22 12:36:21 -07001053 """Test if this address is allocated for public networks.
Peter Moody22c31762013-10-21 13:58:06 -07001054
1055 Returns:
1056 A boolean, True if the address is not reserved per
1057 iana-ipv4-special-registry or iana-ipv6-special-registry.
1058
1059 """
1060 return not self.is_private
1061
1062 @property
Nick Coghlan730f67f2012-08-05 22:02:18 +10001063 def is_unspecified(self):
1064 """Test if the address is unspecified.
1065
1066 Returns:
1067 A boolean, True if this is the unspecified address as defined in
1068 RFC 2373 2.5.2.
1069
1070 """
1071 return (self.network_address.is_unspecified and
1072 self.broadcast_address.is_unspecified)
1073
1074 @property
1075 def is_loopback(self):
1076 """Test if the address is a loopback address.
1077
1078 Returns:
1079 A boolean, True if the address is a loopback address as defined in
1080 RFC 2373 2.5.3.
1081
1082 """
1083 return (self.network_address.is_loopback and
1084 self.broadcast_address.is_loopback)
1085
Nick Coghlandc9b2552012-05-20 21:01:57 +10001086
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001087class _BaseV4:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001088
1089 """Base IPv4 object.
1090
1091 The following methods are used by IPv4 objects in both single IP
1092 addresses and networks.
1093
1094 """
1095
1096 # Equivalent to 255.255.255.255 or 32 bits of 1's.
1097 _ALL_ONES = (2**IPV4LENGTH) - 1
1098 _DECIMAL_DIGITS = frozenset('0123456789')
1099
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001100 # the valid octets for host and netmasks. only useful for IPv4.
Nick Coghlan7319f692012-07-07 21:43:30 +10001101 _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0))
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001102
Nick Coghlandc9b2552012-05-20 21:01:57 +10001103 def __init__(self, address):
1104 self._version = 4
1105 self._max_prefixlen = IPV4LENGTH
1106
1107 def _explode_shorthand_ip_string(self):
1108 return str(self)
1109
1110 def _ip_int_from_string(self, ip_str):
1111 """Turn the given IP string into an integer for comparison.
1112
1113 Args:
1114 ip_str: A string, the IP ip_str.
1115
1116 Returns:
1117 The IP ip_str as an integer.
1118
1119 Raises:
1120 AddressValueError: if ip_str isn't a valid IPv4 Address.
1121
1122 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001123 if not ip_str:
1124 raise AddressValueError('Address cannot be empty')
1125
Nick Coghlandc9b2552012-05-20 21:01:57 +10001126 octets = ip_str.split('.')
1127 if len(octets) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001128 raise AddressValueError("Expected 4 octets in %r" % ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001129
Nick Coghlan7319f692012-07-07 21:43:30 +10001130 try:
1131 return int.from_bytes(map(self._parse_octet, octets), 'big')
1132 except ValueError as exc:
1133 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001134
1135 def _parse_octet(self, octet_str):
1136 """Convert a decimal octet into an integer.
1137
1138 Args:
1139 octet_str: A string, the number to parse.
1140
1141 Returns:
1142 The octet as an integer.
1143
1144 Raises:
1145 ValueError: if the octet isn't strictly a decimal from [0..255].
1146
1147 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001148 if not octet_str:
1149 raise ValueError("Empty octet not permitted")
Nick Coghlandc9b2552012-05-20 21:01:57 +10001150 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1151 if not self._DECIMAL_DIGITS.issuperset(octet_str):
Nick Coghlan07c4e332012-07-08 23:06:45 +10001152 msg = "Only decimal digits permitted in %r"
1153 raise ValueError(msg % octet_str)
1154 # We do the length check second, since the invalid character error
1155 # is likely to be more informative for the user
1156 if len(octet_str) > 3:
1157 msg = "At most 3 characters permitted in %r"
1158 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001159 # Convert to integer (we know digits are legal)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001160 octet_int = int(octet_str, 10)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001161 # Any octets that look like they *might* be written in octal,
1162 # and which don't look exactly the same in both octal and
1163 # decimal are rejected as ambiguous
1164 if octet_int > 7 and octet_str[0] == '0':
Nick Coghlan07c4e332012-07-08 23:06:45 +10001165 msg = "Ambiguous (octal/decimal) value in %r not permitted"
1166 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001167 if octet_int > 255:
Nick Coghlanb582ecc2012-07-07 22:15:22 +10001168 raise ValueError("Octet %d (> 255) not permitted" % octet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001169 return octet_int
1170
1171 def _string_from_ip_int(self, ip_int):
1172 """Turns a 32-bit integer into dotted decimal notation.
1173
1174 Args:
1175 ip_int: An integer, the IP address.
1176
1177 Returns:
1178 The IP address as a string in dotted decimal notation.
1179
1180 """
Nick Coghlan7319f692012-07-07 21:43:30 +10001181 return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001182
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001183 def _is_valid_netmask(self, netmask):
1184 """Verify that the netmask is valid.
1185
1186 Args:
1187 netmask: A string, either a prefix or dotted decimal
1188 netmask.
1189
1190 Returns:
1191 A boolean, True if the prefix represents a valid IPv4
1192 netmask.
1193
1194 """
1195 mask = netmask.split('.')
1196 if len(mask) == 4:
Nick Coghlan7319f692012-07-07 21:43:30 +10001197 try:
1198 for x in mask:
1199 if int(x) not in self._valid_mask_octets:
1200 return False
1201 except ValueError:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001202 # Found something that isn't an integer or isn't valid
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001203 return False
Nick Coghlan7319f692012-07-07 21:43:30 +10001204 for idx, y in enumerate(mask):
1205 if idx > 0 and y > mask[idx - 1]:
1206 return False
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001207 return True
1208 try:
1209 netmask = int(netmask)
1210 except ValueError:
1211 return False
1212 return 0 <= netmask <= self._max_prefixlen
1213
1214 def _is_hostmask(self, ip_str):
1215 """Test if the IP string is a hostmask (rather than a netmask).
1216
1217 Args:
1218 ip_str: A string, the potential hostmask.
1219
1220 Returns:
1221 A boolean, True if the IP string is a hostmask.
1222
1223 """
1224 bits = ip_str.split('.')
1225 try:
Nick Coghlan7319f692012-07-07 21:43:30 +10001226 parts = [x for x in map(int, bits) if x in self._valid_mask_octets]
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001227 except ValueError:
1228 return False
1229 if len(parts) != len(bits):
1230 return False
1231 if parts[0] < parts[-1]:
1232 return True
1233 return False
1234
Eric V. Smithebdaaf42014-04-14 12:58:07 -04001235 def _reverse_pointer(self):
1236 """Return the reverse DNS pointer name for the IPv4 address.
1237
1238 This implements the method described in RFC1035 3.5.
1239
1240 """
1241 reverse_octets = str(self).split('.')[::-1]
1242 return '.'.join(reverse_octets) + '.in-addr.arpa'
1243
Nick Coghlandc9b2552012-05-20 21:01:57 +10001244 @property
1245 def max_prefixlen(self):
1246 return self._max_prefixlen
1247
1248 @property
1249 def version(self):
1250 return self._version
1251
Nick Coghlandc9b2552012-05-20 21:01:57 +10001252
1253class IPv4Address(_BaseV4, _BaseAddress):
1254
1255 """Represent and manipulate single IPv4 Addresses."""
1256
1257 def __init__(self, address):
1258
1259 """
1260 Args:
1261 address: A string or integer representing the IP
1262
1263 Additionally, an integer can be passed, so
1264 IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1265 or, more generally
1266 IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1267 IPv4Address('192.0.2.1')
1268
1269 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001270 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001271
1272 """
1273 _BaseAddress.__init__(self, address)
1274 _BaseV4.__init__(self, address)
1275
1276 # Efficient constructor from integer.
1277 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001278 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001279 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001280 return
1281
1282 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001283 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001284 self._check_packed_address(address, 4)
Nick Coghlandb7920b2012-08-20 10:19:12 +10001285 self._ip = int.from_bytes(address, 'big')
Nick Coghlandc9b2552012-05-20 21:01:57 +10001286 return
1287
1288 # Assume input argument to be string or any object representation
1289 # which converts into a formatted IP string.
1290 addr_str = str(address)
1291 self._ip = self._ip_int_from_string(addr_str)
1292
1293 @property
1294 def packed(self):
1295 """The binary representation of this address."""
1296 return v4_int_to_packed(self._ip)
1297
Nick Coghlan730f67f2012-08-05 22:02:18 +10001298 @property
1299 def is_reserved(self):
1300 """Test if the address is otherwise IETF reserved.
1301
1302 Returns:
1303 A boolean, True if the address is within the
1304 reserved IPv4 Network range.
1305
1306 """
1307 reserved_network = IPv4Network('240.0.0.0/4')
1308 return self in reserved_network
1309
1310 @property
Peter Moodybe9c1b12013-10-22 12:36:21 -07001311 @functools.lru_cache()
Nick Coghlan730f67f2012-08-05 22:02:18 +10001312 def is_private(self):
1313 """Test if this address is allocated for private networks.
1314
1315 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001316 A boolean, True if the address is reserved per
1317 iana-ipv4-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001318
1319 """
Peter Moody22c31762013-10-21 13:58:06 -07001320 return (self in IPv4Network('0.0.0.0/8') or
1321 self in IPv4Network('10.0.0.0/8') or
Peter Moody22c31762013-10-21 13:58:06 -07001322 self in IPv4Network('127.0.0.0/8') or
1323 self in IPv4Network('169.254.0.0/16') or
1324 self in IPv4Network('172.16.0.0/12') or
1325 self in IPv4Network('192.0.0.0/29') or
1326 self in IPv4Network('192.0.0.170/31') or
1327 self in IPv4Network('192.0.2.0/24') or
1328 self in IPv4Network('192.168.0.0/16') or
1329 self in IPv4Network('198.18.0.0/15') or
1330 self in IPv4Network('198.51.100.0/24') or
1331 self in IPv4Network('203.0.113.0/24') or
1332 self in IPv4Network('240.0.0.0/4') or
1333 self in IPv4Network('255.255.255.255/32'))
1334
Nick Coghlan730f67f2012-08-05 22:02:18 +10001335
1336 @property
1337 def is_multicast(self):
1338 """Test if the address is reserved for multicast use.
1339
1340 Returns:
1341 A boolean, True if the address is multicast.
1342 See RFC 3171 for details.
1343
1344 """
1345 multicast_network = IPv4Network('224.0.0.0/4')
1346 return self in multicast_network
1347
1348 @property
1349 def is_unspecified(self):
1350 """Test if the address is unspecified.
1351
1352 Returns:
1353 A boolean, True if this is the unspecified address as defined in
1354 RFC 5735 3.
1355
1356 """
1357 unspecified_address = IPv4Address('0.0.0.0')
1358 return self == unspecified_address
1359
1360 @property
1361 def is_loopback(self):
1362 """Test if the address is a loopback address.
1363
1364 Returns:
1365 A boolean, True if the address is a loopback per RFC 3330.
1366
1367 """
1368 loopback_network = IPv4Network('127.0.0.0/8')
1369 return self in loopback_network
1370
1371 @property
1372 def is_link_local(self):
1373 """Test if the address is reserved for link-local.
1374
1375 Returns:
1376 A boolean, True if the address is link-local per RFC 3927.
1377
1378 """
1379 linklocal_network = IPv4Network('169.254.0.0/16')
1380 return self in linklocal_network
1381
Nick Coghlandc9b2552012-05-20 21:01:57 +10001382
1383class IPv4Interface(IPv4Address):
1384
Nick Coghlandc9b2552012-05-20 21:01:57 +10001385 def __init__(self, address):
1386 if isinstance(address, (bytes, int)):
1387 IPv4Address.__init__(self, address)
1388 self.network = IPv4Network(self._ip)
1389 self._prefixlen = self._max_prefixlen
1390 return
1391
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001392 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001393 IPv4Address.__init__(self, addr[0])
1394
1395 self.network = IPv4Network(address, strict=False)
1396 self._prefixlen = self.network._prefixlen
1397
1398 self.netmask = self.network.netmask
1399 self.hostmask = self.network.hostmask
1400
Nick Coghlandc9b2552012-05-20 21:01:57 +10001401 def __str__(self):
1402 return '%s/%d' % (self._string_from_ip_int(self._ip),
1403 self.network.prefixlen)
1404
1405 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001406 address_equal = IPv4Address.__eq__(self, other)
1407 if not address_equal or address_equal is NotImplemented:
1408 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001409 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001410 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001411 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001412 # An interface with an associated network is NOT the
1413 # same as an unassociated address. That's why the hash
1414 # takes the extra info into account.
1415 return False
1416
1417 def __lt__(self, other):
1418 address_less = IPv4Address.__lt__(self, other)
1419 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001420 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001421 try:
1422 return self.network < other.network
1423 except AttributeError:
1424 # We *do* allow addresses and interfaces to be sorted. The
1425 # unassociated address is considered less than all interfaces.
1426 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001427
1428 def __hash__(self):
1429 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1430
Nick Coghlandc9b2552012-05-20 21:01:57 +10001431 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001432 def ip(self):
1433 return IPv4Address(self._ip)
1434
1435 @property
1436 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10001437 return '%s/%s' % (self._string_from_ip_int(self._ip),
1438 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001439
1440 @property
1441 def with_netmask(self):
1442 return '%s/%s' % (self._string_from_ip_int(self._ip),
1443 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001444
Nick Coghlandc9b2552012-05-20 21:01:57 +10001445 @property
1446 def with_hostmask(self):
1447 return '%s/%s' % (self._string_from_ip_int(self._ip),
1448 self.hostmask)
1449
1450
1451class IPv4Network(_BaseV4, _BaseNetwork):
1452
1453 """This class represents and manipulates 32-bit IPv4 network + addresses..
1454
1455 Attributes: [examples for IPv4Network('192.0.2.0/27')]
1456 .network_address: IPv4Address('192.0.2.0')
1457 .hostmask: IPv4Address('0.0.0.31')
1458 .broadcast_address: IPv4Address('192.0.2.32')
1459 .netmask: IPv4Address('255.255.255.224')
1460 .prefixlen: 27
1461
1462 """
Nick Coghlan51c30672012-05-27 00:25:58 +10001463 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001464 _address_class = IPv4Address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001465
Nick Coghlandc9b2552012-05-20 21:01:57 +10001466 def __init__(self, address, strict=True):
1467
1468 """Instantiate a new IPv4 network object.
1469
1470 Args:
1471 address: A string or integer representing the IP [& network].
1472 '192.0.2.0/24'
1473 '192.0.2.0/255.255.255.0'
1474 '192.0.0.2/0.0.0.255'
1475 are all functionally the same in IPv4. Similarly,
1476 '192.0.2.1'
1477 '192.0.2.1/255.255.255.255'
1478 '192.0.2.1/32'
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001479 are also functionally equivalent. That is to say, failing to
Nick Coghlandc9b2552012-05-20 21:01:57 +10001480 provide a subnetmask will create an object with a mask of /32.
1481
1482 If the mask (portion after the / in the argument) is given in
1483 dotted quad form, it is treated as a netmask if it starts with a
1484 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1485 starts with a zero field (e.g. 0.255.255.255 == /8), with the
1486 single exception of an all-zero mask which is treated as a
1487 netmask == /0. If no mask is given, a default of /32 is used.
1488
1489 Additionally, an integer can be passed, so
1490 IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1491 or, more generally
1492 IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1493 IPv4Interface('192.0.2.1')
1494
1495 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001496 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001497 NetmaskValueError: If the netmask isn't valid for
1498 an IPv4 address.
Sandro Tosib4386d32012-06-02 17:14:22 +02001499 ValueError: If strict is True and a network address is not
Nick Coghlandc9b2552012-05-20 21:01:57 +10001500 supplied.
1501
1502 """
1503
1504 _BaseV4.__init__(self, address)
1505 _BaseNetwork.__init__(self, address)
1506
1507 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001508 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001509 self.network_address = IPv4Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001510 self._prefixlen = self._max_prefixlen
1511 self.netmask = IPv4Address(self._ALL_ONES)
1512 #fixme: address/network test here
1513 return
1514
1515 # Efficient constructor from integer.
1516 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001517 self.network_address = IPv4Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001518 self._prefixlen = self._max_prefixlen
1519 self.netmask = IPv4Address(self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001520 #fixme: address/network test here.
1521 return
1522
1523 # Assume input argument to be string or any object representation
1524 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001525 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001526 self.network_address = IPv4Address(self._ip_int_from_string(addr[0]))
1527
Nick Coghlandc9b2552012-05-20 21:01:57 +10001528 if len(addr) == 2:
Nick Coghlan932346f2014-02-08 23:17:36 +10001529 try:
1530 # Check for a netmask in prefix length form
1531 self._prefixlen = self._prefix_from_prefix_string(addr[1])
1532 except NetmaskValueError:
1533 # Check for a netmask or hostmask in dotted-quad form.
1534 # This may raise NetmaskValueError.
1535 self._prefixlen = self._prefix_from_ip_string(addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001536 else:
1537 self._prefixlen = self._max_prefixlen
Nick Coghlan932346f2014-02-08 23:17:36 +10001538 self.netmask = IPv4Address(self._ip_int_from_prefix(self._prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001539
1540 if strict:
1541 if (IPv4Address(int(self.network_address) & int(self.netmask)) !=
1542 self.network_address):
1543 raise ValueError('%s has host bits set' % self)
1544 self.network_address = IPv4Address(int(self.network_address) &
1545 int(self.netmask))
1546
1547 if self._prefixlen == (self._max_prefixlen - 1):
1548 self.hosts = self.__iter__
1549
Peter Moodye5019d52013-10-24 09:47:10 -07001550 @property
1551 @functools.lru_cache()
1552 def is_global(self):
1553 """Test if this address is allocated for public networks.
1554
1555 Returns:
1556 A boolean, True if the address is not reserved per
1557 iana-ipv4-special-registry.
1558
1559 """
1560 return (not (self.network_address in IPv4Network('100.64.0.0/10') and
1561 self.broadcast_address in IPv4Network('100.64.0.0/10')) and
1562 not self.is_private)
1563
1564
Nick Coghlandc9b2552012-05-20 21:01:57 +10001565
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001566class _BaseV6:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001567
1568 """Base IPv6 object.
1569
1570 The following methods are used by IPv6 objects in both single IP
1571 addresses and networks.
1572
1573 """
1574
1575 _ALL_ONES = (2**IPV6LENGTH) - 1
1576 _HEXTET_COUNT = 8
1577 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
1578
1579 def __init__(self, address):
1580 self._version = 6
1581 self._max_prefixlen = IPV6LENGTH
1582
1583 def _ip_int_from_string(self, ip_str):
1584 """Turn an IPv6 ip_str into an integer.
1585
1586 Args:
1587 ip_str: A string, the IPv6 ip_str.
1588
1589 Returns:
1590 An int, the IPv6 address
1591
1592 Raises:
1593 AddressValueError: if ip_str isn't a valid IPv6 Address.
1594
1595 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001596 if not ip_str:
1597 raise AddressValueError('Address cannot be empty')
1598
Nick Coghlandc9b2552012-05-20 21:01:57 +10001599 parts = ip_str.split(':')
1600
1601 # An IPv6 address needs at least 2 colons (3 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001602 _min_parts = 3
1603 if len(parts) < _min_parts:
1604 msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
1605 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001606
1607 # If the address has an IPv4-style suffix, convert it to hexadecimal.
1608 if '.' in parts[-1]:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001609 try:
1610 ipv4_int = IPv4Address(parts.pop())._ip
1611 except AddressValueError as exc:
1612 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001613 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1614 parts.append('%x' % (ipv4_int & 0xFFFF))
1615
1616 # An IPv6 address can't have more than 8 colons (9 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001617 # The extra colon comes from using the "::" notation for a single
1618 # leading or trailing zero part.
1619 _max_parts = self._HEXTET_COUNT + 1
1620 if len(parts) > _max_parts:
1621 msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
1622 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001623
1624 # Disregarding the endpoints, find '::' with nothing in between.
1625 # This indicates that a run of zeroes has been skipped.
Nick Coghlan7319f692012-07-07 21:43:30 +10001626 skip_index = None
1627 for i in range(1, len(parts) - 1):
1628 if not parts[i]:
1629 if skip_index is not None:
1630 # Can't have more than one '::'
1631 msg = "At most one '::' permitted in %r" % ip_str
1632 raise AddressValueError(msg)
1633 skip_index = i
Nick Coghlandc9b2552012-05-20 21:01:57 +10001634
1635 # parts_hi is the number of parts to copy from above/before the '::'
1636 # parts_lo is the number of parts to copy from below/after the '::'
1637 if skip_index is not None:
1638 # If we found a '::', then check if it also covers the endpoints.
1639 parts_hi = skip_index
1640 parts_lo = len(parts) - skip_index - 1
1641 if not parts[0]:
1642 parts_hi -= 1
1643 if parts_hi:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001644 msg = "Leading ':' only permitted as part of '::' in %r"
1645 raise AddressValueError(msg % ip_str) # ^: requires ^::
Nick Coghlandc9b2552012-05-20 21:01:57 +10001646 if not parts[-1]:
1647 parts_lo -= 1
1648 if parts_lo:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001649 msg = "Trailing ':' only permitted as part of '::' in %r"
1650 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001651 parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo)
1652 if parts_skipped < 1:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001653 msg = "Expected at most %d other parts with '::' in %r"
1654 raise AddressValueError(msg % (self._HEXTET_COUNT-1, ip_str))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001655 else:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001656 # Otherwise, allocate the entire address to parts_hi. The
1657 # endpoints could still be empty, but _parse_hextet() will check
1658 # for that.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001659 if len(parts) != self._HEXTET_COUNT:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001660 msg = "Exactly %d parts expected without '::' in %r"
1661 raise AddressValueError(msg % (self._HEXTET_COUNT, ip_str))
1662 if not parts[0]:
1663 msg = "Leading ':' only permitted as part of '::' in %r"
1664 raise AddressValueError(msg % ip_str) # ^: requires ^::
1665 if not parts[-1]:
1666 msg = "Trailing ':' only permitted as part of '::' in %r"
1667 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001668 parts_hi = len(parts)
1669 parts_lo = 0
1670 parts_skipped = 0
1671
1672 try:
1673 # Now, parse the hextets into a 128-bit integer.
1674 ip_int = 0
1675 for i in range(parts_hi):
1676 ip_int <<= 16
1677 ip_int |= self._parse_hextet(parts[i])
1678 ip_int <<= 16 * parts_skipped
1679 for i in range(-parts_lo, 0):
1680 ip_int <<= 16
1681 ip_int |= self._parse_hextet(parts[i])
1682 return ip_int
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001683 except ValueError as exc:
1684 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001685
1686 def _parse_hextet(self, hextet_str):
1687 """Convert an IPv6 hextet string into an integer.
1688
1689 Args:
1690 hextet_str: A string, the number to parse.
1691
1692 Returns:
1693 The hextet as an integer.
1694
1695 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001696 ValueError: if the input isn't strictly a hex number from
1697 [0..FFFF].
Nick Coghlandc9b2552012-05-20 21:01:57 +10001698
1699 """
1700 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1701 if not self._HEX_DIGITS.issuperset(hextet_str):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001702 raise ValueError("Only hex digits permitted in %r" % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001703 # We do the length check second, since the invalid character error
1704 # is likely to be more informative for the user
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001705 if len(hextet_str) > 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001706 msg = "At most 4 characters permitted in %r"
1707 raise ValueError(msg % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001708 # Length check means we can skip checking the integer value
1709 return int(hextet_str, 16)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001710
1711 def _compress_hextets(self, hextets):
1712 """Compresses a list of hextets.
1713
1714 Compresses a list of strings, replacing the longest continuous
1715 sequence of "0" in the list with "" and adding empty strings at
1716 the beginning or at the end of the string such that subsequently
1717 calling ":".join(hextets) will produce the compressed version of
1718 the IPv6 address.
1719
1720 Args:
1721 hextets: A list of strings, the hextets to compress.
1722
1723 Returns:
1724 A list of strings.
1725
1726 """
1727 best_doublecolon_start = -1
1728 best_doublecolon_len = 0
1729 doublecolon_start = -1
1730 doublecolon_len = 0
Nick Coghlandb7920b2012-08-20 10:19:12 +10001731 for index, hextet in enumerate(hextets):
1732 if hextet == '0':
Nick Coghlandc9b2552012-05-20 21:01:57 +10001733 doublecolon_len += 1
1734 if doublecolon_start == -1:
1735 # Start of a sequence of zeros.
1736 doublecolon_start = index
1737 if doublecolon_len > best_doublecolon_len:
1738 # This is the longest sequence of zeros so far.
1739 best_doublecolon_len = doublecolon_len
1740 best_doublecolon_start = doublecolon_start
1741 else:
1742 doublecolon_len = 0
1743 doublecolon_start = -1
1744
1745 if best_doublecolon_len > 1:
1746 best_doublecolon_end = (best_doublecolon_start +
1747 best_doublecolon_len)
1748 # For zeros at the end of the address.
1749 if best_doublecolon_end == len(hextets):
1750 hextets += ['']
1751 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1752 # For zeros at the beginning of the address.
1753 if best_doublecolon_start == 0:
1754 hextets = [''] + hextets
1755
1756 return hextets
1757
1758 def _string_from_ip_int(self, ip_int=None):
1759 """Turns a 128-bit integer into hexadecimal notation.
1760
1761 Args:
1762 ip_int: An integer, the IP address.
1763
1764 Returns:
1765 A string, the hexadecimal representation of the address.
1766
1767 Raises:
1768 ValueError: The address is bigger than 128 bits of all ones.
1769
1770 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001771 if ip_int is None:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001772 ip_int = int(self._ip)
1773
1774 if ip_int > self._ALL_ONES:
1775 raise ValueError('IPv6 address is too large')
1776
1777 hex_str = '%032x' % ip_int
Nick Coghlan7319f692012-07-07 21:43:30 +10001778 hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001779
1780 hextets = self._compress_hextets(hextets)
1781 return ':'.join(hextets)
1782
1783 def _explode_shorthand_ip_string(self):
1784 """Expand a shortened IPv6 address.
1785
1786 Args:
1787 ip_str: A string, the IPv6 address.
1788
1789 Returns:
1790 A string, the expanded IPv6 address.
1791
1792 """
1793 if isinstance(self, IPv6Network):
1794 ip_str = str(self.network_address)
1795 elif isinstance(self, IPv6Interface):
1796 ip_str = str(self.ip)
1797 else:
1798 ip_str = str(self)
1799
1800 ip_int = self._ip_int_from_string(ip_str)
Nick Coghlan7319f692012-07-07 21:43:30 +10001801 hex_str = '%032x' % ip_int
1802 parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001803 if isinstance(self, (_BaseNetwork, IPv6Interface)):
Nick Coghlane3ded952012-08-05 22:45:22 +10001804 return '%s/%d' % (':'.join(parts), self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001805 return ':'.join(parts)
1806
Eric V. Smithebdaaf42014-04-14 12:58:07 -04001807 def _reverse_pointer(self):
1808 """Return the reverse DNS pointer name for the IPv6 address.
1809
1810 This implements the method described in RFC3596 2.5.
1811
1812 """
1813 reverse_chars = self.exploded[::-1].replace(':', '')
1814 return '.'.join(reverse_chars) + '.ip6.arpa'
1815
Nick Coghlandc9b2552012-05-20 21:01:57 +10001816 @property
1817 def max_prefixlen(self):
1818 return self._max_prefixlen
1819
1820 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001821 def version(self):
1822 return self._version
1823
Nick Coghlandc9b2552012-05-20 21:01:57 +10001824
1825class IPv6Address(_BaseV6, _BaseAddress):
1826
Sandro Tosib95c6342012-05-23 23:17:22 +02001827 """Represent and manipulate single IPv6 Addresses."""
Nick Coghlandc9b2552012-05-20 21:01:57 +10001828
1829 def __init__(self, address):
1830 """Instantiate a new IPv6 address object.
1831
1832 Args:
1833 address: A string or integer representing the IP
1834
1835 Additionally, an integer can be passed, so
1836 IPv6Address('2001:db8::') ==
1837 IPv6Address(42540766411282592856903984951653826560)
1838 or, more generally
1839 IPv6Address(int(IPv6Address('2001:db8::'))) ==
1840 IPv6Address('2001:db8::')
1841
1842 Raises:
1843 AddressValueError: If address isn't a valid IPv6 address.
1844
1845 """
1846 _BaseAddress.__init__(self, address)
1847 _BaseV6.__init__(self, address)
1848
1849 # Efficient constructor from integer.
1850 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001851 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001852 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001853 return
1854
1855 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001856 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001857 self._check_packed_address(address, 16)
Nick Coghlandb7920b2012-08-20 10:19:12 +10001858 self._ip = int.from_bytes(address, 'big')
Nick Coghlandc9b2552012-05-20 21:01:57 +10001859 return
1860
1861 # Assume input argument to be string or any object representation
1862 # which converts into a formatted IP string.
1863 addr_str = str(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001864 self._ip = self._ip_int_from_string(addr_str)
1865
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001866 @property
1867 def packed(self):
1868 """The binary representation of this address."""
1869 return v6_int_to_packed(self._ip)
1870
Nick Coghlan730f67f2012-08-05 22:02:18 +10001871 @property
1872 def is_multicast(self):
1873 """Test if the address is reserved for multicast use.
1874
1875 Returns:
1876 A boolean, True if the address is a multicast address.
1877 See RFC 2373 2.7 for details.
1878
1879 """
1880 multicast_network = IPv6Network('ff00::/8')
1881 return self in multicast_network
1882
1883 @property
1884 def is_reserved(self):
1885 """Test if the address is otherwise IETF reserved.
1886
1887 Returns:
1888 A boolean, True if the address is within one of the
1889 reserved IPv6 Network ranges.
1890
1891 """
1892 reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'),
1893 IPv6Network('200::/7'), IPv6Network('400::/6'),
1894 IPv6Network('800::/5'), IPv6Network('1000::/4'),
1895 IPv6Network('4000::/3'), IPv6Network('6000::/3'),
1896 IPv6Network('8000::/3'), IPv6Network('A000::/3'),
1897 IPv6Network('C000::/3'), IPv6Network('E000::/4'),
1898 IPv6Network('F000::/5'), IPv6Network('F800::/6'),
1899 IPv6Network('FE00::/9')]
1900
1901 return any(self in x for x in reserved_networks)
1902
1903 @property
1904 def is_link_local(self):
1905 """Test if the address is reserved for link-local.
1906
1907 Returns:
1908 A boolean, True if the address is reserved per RFC 4291.
1909
1910 """
1911 linklocal_network = IPv6Network('fe80::/10')
1912 return self in linklocal_network
1913
1914 @property
1915 def is_site_local(self):
1916 """Test if the address is reserved for site-local.
1917
1918 Note that the site-local address space has been deprecated by RFC 3879.
1919 Use is_private to test if this address is in the space of unique local
1920 addresses as defined by RFC 4193.
1921
1922 Returns:
1923 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1924
1925 """
1926 sitelocal_network = IPv6Network('fec0::/10')
1927 return self in sitelocal_network
1928
1929 @property
Peter Moodybe9c1b12013-10-22 12:36:21 -07001930 @functools.lru_cache()
Nick Coghlan730f67f2012-08-05 22:02:18 +10001931 def is_private(self):
1932 """Test if this address is allocated for private networks.
1933
1934 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001935 A boolean, True if the address is reserved per
1936 iana-ipv6-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001937
1938 """
Peter Moody22c31762013-10-21 13:58:06 -07001939 return (self in IPv6Network('::1/128') or
1940 self in IPv6Network('::/128') or
1941 self in IPv6Network('::ffff:0:0/96') or
1942 self in IPv6Network('100::/64') or
1943 self in IPv6Network('2001::/23') or
1944 self in IPv6Network('2001:2::/48') or
1945 self in IPv6Network('2001:db8::/32') or
1946 self in IPv6Network('2001:10::/28') or
1947 self in IPv6Network('fc00::/7') or
1948 self in IPv6Network('fe80::/10'))
1949
1950 @property
1951 def is_global(self):
1952 """Test if this address is allocated for public networks.
1953
1954 Returns:
1955 A boolean, true if the address is not reserved per
1956 iana-ipv6-special-registry.
1957
1958 """
1959 return not self.is_private
Nick Coghlan730f67f2012-08-05 22:02:18 +10001960
1961 @property
1962 def is_unspecified(self):
1963 """Test if the address is unspecified.
1964
1965 Returns:
1966 A boolean, True if this is the unspecified address as defined in
1967 RFC 2373 2.5.2.
1968
1969 """
1970 return self._ip == 0
1971
1972 @property
1973 def is_loopback(self):
1974 """Test if the address is a loopback address.
1975
1976 Returns:
1977 A boolean, True if the address is a loopback address as defined in
1978 RFC 2373 2.5.3.
1979
1980 """
1981 return self._ip == 1
1982
1983 @property
1984 def ipv4_mapped(self):
1985 """Return the IPv4 mapped address.
1986
1987 Returns:
1988 If the IPv6 address is a v4 mapped address, return the
1989 IPv4 mapped address. Return None otherwise.
1990
1991 """
1992 if (self._ip >> 32) != 0xFFFF:
1993 return None
1994 return IPv4Address(self._ip & 0xFFFFFFFF)
1995
1996 @property
1997 def teredo(self):
1998 """Tuple of embedded teredo IPs.
1999
2000 Returns:
2001 Tuple of the (server, client) IPs or None if the address
2002 doesn't appear to be a teredo address (doesn't start with
2003 2001::/32)
2004
2005 """
2006 if (self._ip >> 96) != 0x20010000:
2007 return None
2008 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
2009 IPv4Address(~self._ip & 0xFFFFFFFF))
2010
2011 @property
2012 def sixtofour(self):
2013 """Return the IPv4 6to4 embedded address.
2014
2015 Returns:
2016 The IPv4 6to4-embedded address if present or None if the
2017 address doesn't appear to contain a 6to4 embedded address.
2018
2019 """
2020 if (self._ip >> 112) != 0x2002:
2021 return None
2022 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
2023
Nick Coghlandc9b2552012-05-20 21:01:57 +10002024
2025class IPv6Interface(IPv6Address):
2026
2027 def __init__(self, address):
2028 if isinstance(address, (bytes, int)):
2029 IPv6Address.__init__(self, address)
2030 self.network = IPv6Network(self._ip)
2031 self._prefixlen = self._max_prefixlen
2032 return
2033
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002034 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002035 IPv6Address.__init__(self, addr[0])
2036 self.network = IPv6Network(address, strict=False)
2037 self.netmask = self.network.netmask
2038 self._prefixlen = self.network._prefixlen
2039 self.hostmask = self.network.hostmask
2040
Nick Coghlandc9b2552012-05-20 21:01:57 +10002041 def __str__(self):
2042 return '%s/%d' % (self._string_from_ip_int(self._ip),
2043 self.network.prefixlen)
2044
2045 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10002046 address_equal = IPv6Address.__eq__(self, other)
2047 if not address_equal or address_equal is NotImplemented:
2048 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10002049 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10002050 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10002051 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10002052 # An interface with an associated network is NOT the
2053 # same as an unassociated address. That's why the hash
2054 # takes the extra info into account.
2055 return False
2056
2057 def __lt__(self, other):
2058 address_less = IPv6Address.__lt__(self, other)
2059 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10002060 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10002061 try:
2062 return self.network < other.network
2063 except AttributeError:
2064 # We *do* allow addresses and interfaces to be sorted. The
2065 # unassociated address is considered less than all interfaces.
2066 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10002067
2068 def __hash__(self):
2069 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
2070
2071 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10002072 def ip(self):
2073 return IPv6Address(self._ip)
2074
2075 @property
2076 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10002077 return '%s/%s' % (self._string_from_ip_int(self._ip),
2078 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002079
2080 @property
2081 def with_netmask(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10002082 return '%s/%s' % (self._string_from_ip_int(self._ip),
2083 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02002084
Nick Coghlandc9b2552012-05-20 21:01:57 +10002085 @property
2086 def with_hostmask(self):
2087 return '%s/%s' % (self._string_from_ip_int(self._ip),
2088 self.hostmask)
2089
Nick Coghlan730f67f2012-08-05 22:02:18 +10002090 @property
2091 def is_unspecified(self):
2092 return self._ip == 0 and self.network.is_unspecified
2093
2094 @property
2095 def is_loopback(self):
2096 return self._ip == 1 and self.network.is_loopback
2097
Nick Coghlandc9b2552012-05-20 21:01:57 +10002098
2099class IPv6Network(_BaseV6, _BaseNetwork):
2100
2101 """This class represents and manipulates 128-bit IPv6 networks.
2102
2103 Attributes: [examples for IPv6('2001:db8::1000/124')]
2104 .network_address: IPv6Address('2001:db8::1000')
2105 .hostmask: IPv6Address('::f')
2106 .broadcast_address: IPv6Address('2001:db8::100f')
2107 .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
2108 .prefixlen: 124
2109
2110 """
2111
Nick Coghlan51c30672012-05-27 00:25:58 +10002112 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10002113 _address_class = IPv6Address
2114
Nick Coghlandc9b2552012-05-20 21:01:57 +10002115 def __init__(self, address, strict=True):
2116 """Instantiate a new IPv6 Network object.
2117
2118 Args:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02002119 address: A string or integer representing the IPv6 network or the
2120 IP and prefix/netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +10002121 '2001:db8::/128'
2122 '2001:db8:0000:0000:0000:0000:0000:0000/128'
2123 '2001:db8::'
2124 are all functionally the same in IPv6. That is to say,
2125 failing to provide a subnetmask will create an object with
2126 a mask of /128.
2127
2128 Additionally, an integer can be passed, so
2129 IPv6Network('2001:db8::') ==
2130 IPv6Network(42540766411282592856903984951653826560)
2131 or, more generally
2132 IPv6Network(int(IPv6Network('2001:db8::'))) ==
2133 IPv6Network('2001:db8::')
2134
2135 strict: A boolean. If true, ensure that we have been passed
2136 A true network address, eg, 2001:db8::1000/124 and not an
2137 IP address on a network, eg, 2001:db8::1/124.
2138
2139 Raises:
2140 AddressValueError: If address isn't a valid IPv6 address.
2141 NetmaskValueError: If the netmask isn't valid for
2142 an IPv6 address.
2143 ValueError: If strict was True and a network address was not
2144 supplied.
2145
2146 """
2147 _BaseV6.__init__(self, address)
2148 _BaseNetwork.__init__(self, address)
2149
2150 # Efficient constructor from integer.
2151 if isinstance(address, int):
Nick Coghlandc9b2552012-05-20 21:01:57 +10002152 self.network_address = IPv6Address(address)
2153 self._prefixlen = self._max_prefixlen
2154 self.netmask = IPv6Address(self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002155 return
2156
2157 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10002158 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10002159 self.network_address = IPv6Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002160 self._prefixlen = self._max_prefixlen
2161 self.netmask = IPv6Address(self._ALL_ONES)
Hynek Schlawacked36b2e2012-06-08 15:21:21 +02002162 return
Nick Coghlandc9b2552012-05-20 21:01:57 +10002163
2164 # Assume input argument to be string or any object representation
2165 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002166 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002167
2168 self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))
2169
2170 if len(addr) == 2:
Nick Coghlan932346f2014-02-08 23:17:36 +10002171 # This may raise NetmaskValueError
2172 self._prefixlen = self._prefix_from_prefix_string(addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10002173 else:
2174 self._prefixlen = self._max_prefixlen
2175
2176 self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen))
2177 if strict:
2178 if (IPv6Address(int(self.network_address) & int(self.netmask)) !=
2179 self.network_address):
Nick Coghlan912238e2012-07-07 13:34:50 +10002180 raise ValueError('%s has host bits set' % self)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002181 self.network_address = IPv6Address(int(self.network_address) &
2182 int(self.netmask))
2183
2184 if self._prefixlen == (self._max_prefixlen - 1):
2185 self.hosts = self.__iter__
2186
Peter Moody1243c7d2014-03-11 09:55:46 -07002187 def hosts(self):
2188 """Generate Iterator over usable hosts in a network.
2189
2190 This is like __iter__ except it doesn't return the
2191 Subnet-Router anycast address.
2192
2193 """
2194 network = int(self.network_address)
2195 broadcast = int(self.broadcast_address)
2196 for x in range(network + 1, broadcast + 1):
2197 yield self._address_class(x)
2198
Nick Coghlan730f67f2012-08-05 22:02:18 +10002199 @property
2200 def is_site_local(self):
2201 """Test if the address is reserved for site-local.
2202
2203 Note that the site-local address space has been deprecated by RFC 3879.
2204 Use is_private to test if this address is in the space of unique local
2205 addresses as defined by RFC 4193.
2206
2207 Returns:
2208 A boolean, True if the address is reserved per RFC 3513 2.5.6.
2209
2210 """
2211 return (self.network_address.is_site_local and
2212 self.broadcast_address.is_site_local)