blob: 2ba98d8926619bbdacf7ae44c9ecb4fe2d495b0e [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):
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200167 """Find a sequence of sorted deduplicated 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
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200172 Yields:
173 A tuple containing the first and last IP addresses in the sequence.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000174
175 """
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200176 it = iter(addresses)
177 first = last = next(it)
178 for ip in it:
179 if ip._ip != last._ip + 1:
180 yield first, last
181 first = ip
182 last = ip
183 yield first, last
Nick Coghlandc9b2552012-05-20 21:01:57 +1000184
Sandro Tosib95c6342012-05-23 23:17:22 +0200185
Nick Coghlandc9b2552012-05-20 21:01:57 +1000186def _count_righthand_zero_bits(number, bits):
187 """Count the number of zero bits on the right hand side.
188
189 Args:
190 number: an integer.
191 bits: maximum number of bits to count.
192
193 Returns:
194 The number of zero bits on the right hand side of the number.
195
196 """
197 if number == 0:
198 return bits
Antoine Pitrou824db302014-05-15 20:21:48 +0200199 return min(bits, (~number & (number-1)).bit_length())
Nick Coghlandc9b2552012-05-20 21:01:57 +1000200
201
202def summarize_address_range(first, last):
203 """Summarize a network range given the first and last IP addresses.
204
205 Example:
Eli Bendersky948af232012-10-07 07:23:50 -0700206 >>> list(summarize_address_range(IPv4Address('192.0.2.0'),
207 ... IPv4Address('192.0.2.130')))
208 ... #doctest: +NORMALIZE_WHITESPACE
Nick Coghlandc9b2552012-05-20 21:01:57 +1000209 [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'),
Eli Bendersky948af232012-10-07 07:23:50 -0700210 IPv4Network('192.0.2.130/32')]
Nick Coghlandc9b2552012-05-20 21:01:57 +1000211
212 Args:
213 first: the first IPv4Address or IPv6Address in the range.
214 last: the last IPv4Address or IPv6Address in the range.
215
216 Returns:
217 An iterator of the summarized IPv(4|6) network objects.
218
219 Raise:
220 TypeError:
221 If the first and last objects are not IP addresses.
222 If the first and last objects are not the same version.
223 ValueError:
224 If the last object is not greater than the first.
Nick Coghlan51c30672012-05-27 00:25:58 +1000225 If the version of the first address is not 4 or 6.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000226
227 """
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200228 if (not (isinstance(first, _BaseAddress) and
229 isinstance(last, _BaseAddress))):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000230 raise TypeError('first and last must be IP addresses, not networks')
231 if first.version != last.version:
232 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000233 first, last))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000234 if first > last:
235 raise ValueError('last IP address must be greater than first')
236
Nick Coghlandc9b2552012-05-20 21:01:57 +1000237 if first.version == 4:
238 ip = IPv4Network
239 elif first.version == 6:
240 ip = IPv6Network
241 else:
242 raise ValueError('unknown IP version')
243
244 ip_bits = first._max_prefixlen
245 first_int = first._ip
246 last_int = last._ip
247 while first_int <= last_int:
Nick Coghlan7319f692012-07-07 21:43:30 +1000248 nbits = min(_count_righthand_zero_bits(first_int, ip_bits),
249 (last_int - first_int + 1).bit_length() - 1)
Antoine Pitrou824db302014-05-15 20:21:48 +0200250 net = ip((first_int, ip_bits - nbits))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000251 yield net
Nick Coghlan7319f692012-07-07 21:43:30 +1000252 first_int += 1 << nbits
253 if first_int - 1 == ip._ALL_ONES:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000254 break
Nick Coghlandc9b2552012-05-20 21:01:57 +1000255
Sandro Tosib95c6342012-05-23 23:17:22 +0200256
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200257def _collapse_addresses_internal(addresses):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000258 """Loops through the addresses, collapsing concurrent netblocks.
259
260 Example:
261
262 ip1 = IPv4Network('192.0.2.0/26')
263 ip2 = IPv4Network('192.0.2.64/26')
264 ip3 = IPv4Network('192.0.2.128/26')
265 ip4 = IPv4Network('192.0.2.192/26')
266
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200267 _collapse_addresses_internal([ip1, ip2, ip3, ip4]) ->
Nick Coghlandc9b2552012-05-20 21:01:57 +1000268 [IPv4Network('192.0.2.0/24')]
269
270 This shouldn't be called directly; it is called via
271 collapse_addresses([]).
272
273 Args:
274 addresses: A list of IPv4Network's or IPv6Network's
275
276 Returns:
277 A list of IPv4Network's or IPv6Network's depending on what we were
278 passed.
279
280 """
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200281 # First merge
282 to_merge = list(addresses)
283 subnets = {}
284 while to_merge:
285 net = to_merge.pop()
286 supernet = net.supernet()
287 existing = subnets.get(supernet)
288 if existing is None:
289 subnets[supernet] = net
290 elif existing != net:
291 # Merge consecutive subnets
292 del subnets[supernet]
293 to_merge.append(supernet)
294 # Then iterate over resulting networks, skipping subsumed subnets
295 last = None
296 for net in sorted(subnets.values()):
297 if last is not None:
298 # Since they are sorted, last.network_address <= net.network_address
299 # is a given.
300 if last.broadcast_address >= net.broadcast_address:
301 continue
302 yield net
303 last = net
Nick Coghlandc9b2552012-05-20 21:01:57 +1000304
305
306def collapse_addresses(addresses):
307 """Collapse a list of IP objects.
308
309 Example:
310 collapse_addresses([IPv4Network('192.0.2.0/25'),
311 IPv4Network('192.0.2.128/25')]) ->
312 [IPv4Network('192.0.2.0/24')]
313
314 Args:
315 addresses: An iterator of IPv4Network or IPv6Network objects.
316
317 Returns:
318 An iterator of the collapsed IPv(4|6)Network objects.
319
320 Raises:
321 TypeError: If passed a list of mixed version objects.
322
323 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000324 addrs = []
325 ips = []
326 nets = []
327
328 # split IP addresses and networks
329 for ip in addresses:
330 if isinstance(ip, _BaseAddress):
331 if ips and ips[-1]._version != ip._version:
332 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000333 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000334 ips.append(ip)
335 elif ip._prefixlen == ip._max_prefixlen:
336 if ips and ips[-1]._version != ip._version:
337 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000338 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000339 try:
340 ips.append(ip.ip)
341 except AttributeError:
342 ips.append(ip.network_address)
343 else:
344 if nets and nets[-1]._version != ip._version:
345 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000346 ip, nets[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000347 nets.append(ip)
348
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200349 # sort and dedup
350 ips = sorted(set(ips))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000351
Antoine Pitroue6f250e2015-01-18 16:22:47 +0100352 # find consecutive address ranges in the sorted sequence and summarize them
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200353 if ips:
354 for first, last in _find_address_range(ips):
355 addrs.extend(summarize_address_range(first, last))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000356
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200357 return _collapse_addresses_internal(addrs + nets)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000358
359
360def get_mixed_type_key(obj):
361 """Return a key suitable for sorting between networks and addresses.
362
363 Address and Network objects are not sortable by default; they're
364 fundamentally different so the expression
365
366 IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
367
368 doesn't make any sense. There are some times however, where you may wish
369 to have ipaddress sort these for you anyway. If you need to do this, you
370 can use this function as the key= argument to sorted().
371
372 Args:
373 obj: either a Network or Address object.
374 Returns:
375 appropriate key.
376
377 """
378 if isinstance(obj, _BaseNetwork):
379 return obj._get_networks_key()
380 elif isinstance(obj, _BaseAddress):
381 return obj._get_address_key()
382 return NotImplemented
383
384
Nick Coghlan3008ec02012-07-08 00:45:33 +1000385class _TotalOrderingMixin:
386 # Helper that derives the other comparison operations from
387 # __lt__ and __eq__
Nick Coghlan297b1432012-07-08 17:11:04 +1000388 # We avoid functools.total_ordering because it doesn't handle
389 # NotImplemented correctly yet (http://bugs.python.org/issue10042)
Nick Coghlan3008ec02012-07-08 00:45:33 +1000390 def __eq__(self, other):
391 raise NotImplementedError
392 def __ne__(self, other):
393 equal = self.__eq__(other)
394 if equal is NotImplemented:
395 return NotImplemented
396 return not equal
397 def __lt__(self, other):
398 raise NotImplementedError
399 def __le__(self, other):
400 less = self.__lt__(other)
401 if less is NotImplemented or not less:
402 return self.__eq__(other)
403 return less
404 def __gt__(self, other):
405 less = self.__lt__(other)
406 if less is NotImplemented:
407 return NotImplemented
408 equal = self.__eq__(other)
409 if equal is NotImplemented:
410 return NotImplemented
411 return not (less or equal)
412 def __ge__(self, other):
413 less = self.__lt__(other)
414 if less is NotImplemented:
415 return NotImplemented
416 return not less
417
418class _IPAddressBase(_TotalOrderingMixin):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000419
420 """The mother class."""
421
422 @property
423 def exploded(self):
424 """Return the longhand version of the IP address as a string."""
425 return self._explode_shorthand_ip_string()
426
427 @property
428 def compressed(self):
429 """Return the shorthand version of the IP address as a string."""
430 return str(self)
431
Nick Coghland9722652012-06-17 16:33:00 +1000432 @property
Eric V. Smithebdaaf42014-04-14 12:58:07 -0400433 def reverse_pointer(self):
434 """The name of the reverse DNS pointer for the IP address, e.g.:
435 >>> ipaddress.ip_address("127.0.0.1").reverse_pointer
436 '1.0.0.127.in-addr.arpa'
437 >>> ipaddress.ip_address("2001:db8::1").reverse_pointer
438 '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'
439
440 """
441 return self._reverse_pointer()
442
443 @property
Nick Coghland9722652012-06-17 16:33:00 +1000444 def version(self):
445 msg = '%200s has no version specified' % (type(self),)
446 raise NotImplementedError(msg)
447
Nick Coghlan297b1432012-07-08 17:11:04 +1000448 def _check_int_address(self, address):
449 if address < 0:
450 msg = "%d (< 0) is not permitted as an IPv%d address"
451 raise AddressValueError(msg % (address, self._version))
452 if address > self._ALL_ONES:
453 msg = "%d (>= 2**%d) is not permitted as an IPv%d address"
454 raise AddressValueError(msg % (address, self._max_prefixlen,
455 self._version))
456
457 def _check_packed_address(self, address, expected_len):
458 address_len = len(address)
459 if address_len != expected_len:
460 msg = "%r (len %d != %d) is not permitted as an IPv%d address"
461 raise AddressValueError(msg % (address, address_len,
462 expected_len, self._version))
463
Antoine Pitrou45aba182014-05-15 20:18:41 +0200464 @classmethod
465 def _ip_int_from_prefix(cls, prefixlen):
Nick Coghlan932346f2014-02-08 23:17:36 +1000466 """Turn the prefix length into a bitwise netmask
Nick Coghlandc9b2552012-05-20 21:01:57 +1000467
468 Args:
469 prefixlen: An integer, the prefix length.
470
471 Returns:
472 An integer.
473
474 """
Antoine Pitrou45aba182014-05-15 20:18:41 +0200475 return cls._ALL_ONES ^ (cls._ALL_ONES >> prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000476
Antoine Pitrou45aba182014-05-15 20:18:41 +0200477 @classmethod
478 def _prefix_from_ip_int(cls, ip_int):
Nick Coghlan932346f2014-02-08 23:17:36 +1000479 """Return prefix length from the bitwise netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000480
481 Args:
Berker Peksagf23530f2014-10-19 18:04:38 +0300482 ip_int: An integer, the netmask in expanded bitwise format
Nick Coghlandc9b2552012-05-20 21:01:57 +1000483
484 Returns:
485 An integer, the prefix length.
486
Nick Coghlan932346f2014-02-08 23:17:36 +1000487 Raises:
488 ValueError: If the input intermingles zeroes & ones
Nick Coghlandc9b2552012-05-20 21:01:57 +1000489 """
Nick Coghlan932346f2014-02-08 23:17:36 +1000490 trailing_zeroes = _count_righthand_zero_bits(ip_int,
Antoine Pitrou45aba182014-05-15 20:18:41 +0200491 cls._max_prefixlen)
492 prefixlen = cls._max_prefixlen - trailing_zeroes
Nick Coghlan932346f2014-02-08 23:17:36 +1000493 leading_ones = ip_int >> trailing_zeroes
494 all_ones = (1 << prefixlen) - 1
495 if leading_ones != all_ones:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200496 byteslen = cls._max_prefixlen // 8
Nick Coghlan932346f2014-02-08 23:17:36 +1000497 details = ip_int.to_bytes(byteslen, 'big')
498 msg = 'Netmask pattern %r mixes zeroes & ones'
499 raise ValueError(msg % details)
500 return prefixlen
Nick Coghlandc9b2552012-05-20 21:01:57 +1000501
Antoine Pitrou45aba182014-05-15 20:18:41 +0200502 @classmethod
503 def _report_invalid_netmask(cls, netmask_str):
Nick Coghlan932346f2014-02-08 23:17:36 +1000504 msg = '%r is not a valid netmask' % netmask_str
505 raise NetmaskValueError(msg) from None
506
Antoine Pitrou45aba182014-05-15 20:18:41 +0200507 @classmethod
508 def _prefix_from_prefix_string(cls, prefixlen_str):
Nick Coghlan932346f2014-02-08 23:17:36 +1000509 """Return prefix length from a numeric string
Nick Coghlandc9b2552012-05-20 21:01:57 +1000510
511 Args:
Nick Coghlan932346f2014-02-08 23:17:36 +1000512 prefixlen_str: The string to be converted
Nick Coghlandc9b2552012-05-20 21:01:57 +1000513
514 Returns:
Nick Coghlan932346f2014-02-08 23:17:36 +1000515 An integer, the prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000516
Nick Coghlan932346f2014-02-08 23:17:36 +1000517 Raises:
518 NetmaskValueError: If the input is not a valid netmask
Nick Coghlandc9b2552012-05-20 21:01:57 +1000519 """
Nick Coghlan932346f2014-02-08 23:17:36 +1000520 # int allows a leading +/- as well as surrounding whitespace,
521 # so we ensure that isn't the case
522 if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
Antoine Pitrou45aba182014-05-15 20:18:41 +0200523 cls._report_invalid_netmask(prefixlen_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000524 try:
525 prefixlen = int(prefixlen_str)
526 except ValueError:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200527 cls._report_invalid_netmask(prefixlen_str)
528 if not (0 <= prefixlen <= cls._max_prefixlen):
529 cls._report_invalid_netmask(prefixlen_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000530 return prefixlen
531
Antoine Pitrou45aba182014-05-15 20:18:41 +0200532 @classmethod
533 def _prefix_from_ip_string(cls, ip_str):
Nick Coghlan932346f2014-02-08 23:17:36 +1000534 """Turn a netmask/hostmask string into a prefix length
535
536 Args:
537 ip_str: The netmask/hostmask to be converted
538
539 Returns:
540 An integer, the prefix length.
541
542 Raises:
543 NetmaskValueError: If the input is not a valid netmask/hostmask
544 """
545 # Parse the netmask/hostmask like an IP address.
546 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200547 ip_int = cls._ip_int_from_string(ip_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000548 except AddressValueError:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200549 cls._report_invalid_netmask(ip_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000550
551 # Try matching a netmask (this would be /1*0*/ as a bitwise regexp).
552 # Note that the two ambiguous cases (all-ones and all-zeroes) are
553 # treated as netmasks.
554 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200555 return cls._prefix_from_ip_int(ip_int)
Nick Coghlan932346f2014-02-08 23:17:36 +1000556 except ValueError:
557 pass
558
559 # Invert the bits, and try matching a /0+1+/ hostmask instead.
Antoine Pitrou45aba182014-05-15 20:18:41 +0200560 ip_int ^= cls._ALL_ONES
Nick Coghlan932346f2014-02-08 23:17:36 +1000561 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200562 return cls._prefix_from_ip_int(ip_int)
Nick Coghlan932346f2014-02-08 23:17:36 +1000563 except ValueError:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200564 cls._report_invalid_netmask(ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000565
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +0200566 def __reduce__(self):
567 return self.__class__, (str(self),)
568
Nick Coghlan730f67f2012-08-05 22:02:18 +1000569
Nick Coghlandc9b2552012-05-20 21:01:57 +1000570class _BaseAddress(_IPAddressBase):
571
572 """A generic IP object.
573
574 This IP class contains the version independent methods which are
575 used by single IP addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000576 """
577
Nick Coghlandc9b2552012-05-20 21:01:57 +1000578 def __int__(self):
579 return self._ip
580
Nick Coghlandc9b2552012-05-20 21:01:57 +1000581 def __eq__(self, other):
582 try:
583 return (self._ip == other._ip
584 and self._version == other._version)
585 except AttributeError:
586 return NotImplemented
587
Nick Coghlandc9b2552012-05-20 21:01:57 +1000588 def __lt__(self, other):
589 if self._version != other._version:
590 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000591 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000592 if not isinstance(other, _BaseAddress):
593 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000594 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000595 if self._ip != other._ip:
596 return self._ip < other._ip
597 return False
598
Nick Coghlandc9b2552012-05-20 21:01:57 +1000599 # Shorthand for Integer addition and subtraction. This is not
600 # meant to ever support addition/subtraction of addresses.
601 def __add__(self, other):
602 if not isinstance(other, int):
603 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000604 return self.__class__(int(self) + other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000605
606 def __sub__(self, other):
607 if not isinstance(other, int):
608 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000609 return self.__class__(int(self) - other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000610
611 def __repr__(self):
612 return '%s(%r)' % (self.__class__.__name__, str(self))
613
614 def __str__(self):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200615 return str(self._string_from_ip_int(self._ip))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000616
617 def __hash__(self):
618 return hash(hex(int(self._ip)))
619
620 def _get_address_key(self):
621 return (self._version, self)
622
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +0200623 def __reduce__(self):
624 return self.__class__, (self._ip,)
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:
Raymond Hettingerbb6c0aa2014-11-22 22:14:41 -0800812 return
Nick Coghlandc9b2552012-05-20 21:01:57 +1000813
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
Antoine Pitrou824db302014-05-15 20:21:48 +0200947 start = int(self.network_address)
948 end = int(self.broadcast_address)
949 step = (int(self.hostmask) + 1) >> prefixlen_diff
950 for new_addr in range(start, end, step):
951 current = self.__class__((new_addr, new_prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000952 yield current
953
Nick Coghlandc9b2552012-05-20 21:01:57 +1000954 def supernet(self, prefixlen_diff=1, new_prefix=None):
955 """The supernet containing the current network.
956
957 Args:
958 prefixlen_diff: An integer, the amount the prefix length of
959 the network should be decreased by. For example, given a
960 /24 network and a prefixlen_diff of 3, a supernet with a
961 /21 netmask is returned.
962
963 Returns:
964 An IPv4 network object.
965
966 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200967 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
968 a negative prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000969 OR
970 If prefixlen_diff and new_prefix are both set or new_prefix is a
971 larger number than the current prefix (larger number means a
972 smaller network)
973
974 """
975 if self._prefixlen == 0:
976 return self
977
978 if new_prefix is not None:
979 if new_prefix > self._prefixlen:
980 raise ValueError('new prefix must be shorter')
981 if prefixlen_diff != 1:
982 raise ValueError('cannot set prefixlen_diff and new_prefix')
983 prefixlen_diff = self._prefixlen - new_prefix
984
Antoine Pitrou5fb195f2014-05-12 20:36:46 +0200985 new_prefixlen = self.prefixlen - prefixlen_diff
986 if new_prefixlen < 0:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000987 raise ValueError(
988 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
989 (self.prefixlen, prefixlen_diff))
Antoine Pitrou5fb195f2014-05-12 20:36:46 +0200990 return self.__class__((
991 int(self.network_address) & (int(self.netmask) << prefixlen_diff),
992 new_prefixlen
993 ))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000994
Nick Coghlan730f67f2012-08-05 22:02:18 +1000995 @property
996 def is_multicast(self):
997 """Test if the address is reserved for multicast use.
998
999 Returns:
1000 A boolean, True if the address is a multicast address.
1001 See RFC 2373 2.7 for details.
1002
1003 """
1004 return (self.network_address.is_multicast and
1005 self.broadcast_address.is_multicast)
1006
1007 @property
1008 def is_reserved(self):
1009 """Test if the address is otherwise IETF reserved.
1010
1011 Returns:
1012 A boolean, True if the address is within one of the
1013 reserved IPv6 Network ranges.
1014
1015 """
1016 return (self.network_address.is_reserved and
1017 self.broadcast_address.is_reserved)
1018
1019 @property
1020 def is_link_local(self):
1021 """Test if the address is reserved for link-local.
1022
1023 Returns:
1024 A boolean, True if the address is reserved per RFC 4291.
1025
1026 """
1027 return (self.network_address.is_link_local and
1028 self.broadcast_address.is_link_local)
1029
1030 @property
1031 def is_private(self):
1032 """Test if this address is allocated for private networks.
1033
1034 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001035 A boolean, True if the address is reserved per
1036 iana-ipv4-special-registry or iana-ipv6-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001037
1038 """
1039 return (self.network_address.is_private and
1040 self.broadcast_address.is_private)
1041
1042 @property
Peter Moody22c31762013-10-21 13:58:06 -07001043 def is_global(self):
Peter Moodybe9c1b12013-10-22 12:36:21 -07001044 """Test if this address is allocated for public networks.
Peter Moody22c31762013-10-21 13:58:06 -07001045
1046 Returns:
1047 A boolean, True if the address is not reserved per
1048 iana-ipv4-special-registry or iana-ipv6-special-registry.
1049
1050 """
1051 return not self.is_private
1052
1053 @property
Nick Coghlan730f67f2012-08-05 22:02:18 +10001054 def is_unspecified(self):
1055 """Test if the address is unspecified.
1056
1057 Returns:
1058 A boolean, True if this is the unspecified address as defined in
1059 RFC 2373 2.5.2.
1060
1061 """
1062 return (self.network_address.is_unspecified and
1063 self.broadcast_address.is_unspecified)
1064
1065 @property
1066 def is_loopback(self):
1067 """Test if the address is a loopback address.
1068
1069 Returns:
1070 A boolean, True if the address is a loopback address as defined in
1071 RFC 2373 2.5.3.
1072
1073 """
1074 return (self.network_address.is_loopback and
1075 self.broadcast_address.is_loopback)
1076
Nick Coghlandc9b2552012-05-20 21:01:57 +10001077
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001078class _BaseV4:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001079
1080 """Base IPv4 object.
1081
1082 The following methods are used by IPv4 objects in both single IP
1083 addresses and networks.
1084
1085 """
1086
1087 # Equivalent to 255.255.255.255 or 32 bits of 1's.
1088 _ALL_ONES = (2**IPV4LENGTH) - 1
1089 _DECIMAL_DIGITS = frozenset('0123456789')
1090
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001091 # the valid octets for host and netmasks. only useful for IPv4.
Raymond Hettingerdf1b6992014-11-09 15:56:33 -08001092 _valid_mask_octets = frozenset({255, 254, 252, 248, 240, 224, 192, 128, 0})
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001093
Antoine Pitrou45aba182014-05-15 20:18:41 +02001094 _max_prefixlen = IPV4LENGTH
1095 # There are only a handful of valid v4 netmasks, so we cache them all
1096 # when constructed (see _make_netmask()).
1097 _netmask_cache = {}
1098
Nick Coghlandc9b2552012-05-20 21:01:57 +10001099 def __init__(self, address):
1100 self._version = 4
Nick Coghlandc9b2552012-05-20 21:01:57 +10001101
1102 def _explode_shorthand_ip_string(self):
1103 return str(self)
1104
Antoine Pitrou45aba182014-05-15 20:18:41 +02001105 @classmethod
1106 def _make_netmask(cls, arg):
1107 """Make a (netmask, prefix_len) tuple from the given argument.
1108
1109 Argument can be:
1110 - an integer (the prefix length)
1111 - a string representing the prefix length (e.g. "24")
1112 - a string representing the prefix netmask (e.g. "255.255.255.0")
1113 """
1114 if arg not in cls._netmask_cache:
1115 if isinstance(arg, int):
1116 prefixlen = arg
1117 else:
1118 try:
1119 # Check for a netmask in prefix length form
1120 prefixlen = cls._prefix_from_prefix_string(arg)
1121 except NetmaskValueError:
1122 # Check for a netmask or hostmask in dotted-quad form.
1123 # This may raise NetmaskValueError.
1124 prefixlen = cls._prefix_from_ip_string(arg)
1125 netmask = IPv4Address(cls._ip_int_from_prefix(prefixlen))
1126 cls._netmask_cache[arg] = netmask, prefixlen
1127 return cls._netmask_cache[arg]
1128
1129 @classmethod
1130 def _ip_int_from_string(cls, ip_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001131 """Turn the given IP string into an integer for comparison.
1132
1133 Args:
1134 ip_str: A string, the IP ip_str.
1135
1136 Returns:
1137 The IP ip_str as an integer.
1138
1139 Raises:
1140 AddressValueError: if ip_str isn't a valid IPv4 Address.
1141
1142 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001143 if not ip_str:
1144 raise AddressValueError('Address cannot be empty')
1145
Nick Coghlandc9b2552012-05-20 21:01:57 +10001146 octets = ip_str.split('.')
1147 if len(octets) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001148 raise AddressValueError("Expected 4 octets in %r" % ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001149
Nick Coghlan7319f692012-07-07 21:43:30 +10001150 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001151 return int.from_bytes(map(cls._parse_octet, octets), 'big')
Nick Coghlan7319f692012-07-07 21:43:30 +10001152 except ValueError as exc:
1153 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001154
Antoine Pitrou45aba182014-05-15 20:18:41 +02001155 @classmethod
1156 def _parse_octet(cls, octet_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001157 """Convert a decimal octet into an integer.
1158
1159 Args:
1160 octet_str: A string, the number to parse.
1161
1162 Returns:
1163 The octet as an integer.
1164
1165 Raises:
1166 ValueError: if the octet isn't strictly a decimal from [0..255].
1167
1168 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001169 if not octet_str:
1170 raise ValueError("Empty octet not permitted")
Nick Coghlandc9b2552012-05-20 21:01:57 +10001171 # Whitelist the characters, since int() allows a lot of bizarre stuff.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001172 if not cls._DECIMAL_DIGITS.issuperset(octet_str):
Nick Coghlan07c4e332012-07-08 23:06:45 +10001173 msg = "Only decimal digits permitted in %r"
1174 raise ValueError(msg % octet_str)
1175 # We do the length check second, since the invalid character error
1176 # is likely to be more informative for the user
1177 if len(octet_str) > 3:
1178 msg = "At most 3 characters permitted in %r"
1179 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001180 # Convert to integer (we know digits are legal)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001181 octet_int = int(octet_str, 10)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001182 # Any octets that look like they *might* be written in octal,
1183 # and which don't look exactly the same in both octal and
1184 # decimal are rejected as ambiguous
1185 if octet_int > 7 and octet_str[0] == '0':
Nick Coghlan07c4e332012-07-08 23:06:45 +10001186 msg = "Ambiguous (octal/decimal) value in %r not permitted"
1187 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001188 if octet_int > 255:
Nick Coghlanb582ecc2012-07-07 22:15:22 +10001189 raise ValueError("Octet %d (> 255) not permitted" % octet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001190 return octet_int
1191
Antoine Pitrou45aba182014-05-15 20:18:41 +02001192 @classmethod
1193 def _string_from_ip_int(cls, ip_int):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001194 """Turns a 32-bit integer into dotted decimal notation.
1195
1196 Args:
1197 ip_int: An integer, the IP address.
1198
1199 Returns:
1200 The IP address as a string in dotted decimal notation.
1201
1202 """
Nick Coghlan7319f692012-07-07 21:43:30 +10001203 return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001204
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001205 def _is_valid_netmask(self, netmask):
1206 """Verify that the netmask is valid.
1207
1208 Args:
1209 netmask: A string, either a prefix or dotted decimal
1210 netmask.
1211
1212 Returns:
1213 A boolean, True if the prefix represents a valid IPv4
1214 netmask.
1215
1216 """
1217 mask = netmask.split('.')
1218 if len(mask) == 4:
Nick Coghlan7319f692012-07-07 21:43:30 +10001219 try:
1220 for x in mask:
1221 if int(x) not in self._valid_mask_octets:
1222 return False
1223 except ValueError:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001224 # Found something that isn't an integer or isn't valid
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001225 return False
Nick Coghlan7319f692012-07-07 21:43:30 +10001226 for idx, y in enumerate(mask):
1227 if idx > 0 and y > mask[idx - 1]:
1228 return False
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001229 return True
1230 try:
1231 netmask = int(netmask)
1232 except ValueError:
1233 return False
1234 return 0 <= netmask <= self._max_prefixlen
1235
1236 def _is_hostmask(self, ip_str):
1237 """Test if the IP string is a hostmask (rather than a netmask).
1238
1239 Args:
1240 ip_str: A string, the potential hostmask.
1241
1242 Returns:
1243 A boolean, True if the IP string is a hostmask.
1244
1245 """
1246 bits = ip_str.split('.')
1247 try:
Nick Coghlan7319f692012-07-07 21:43:30 +10001248 parts = [x for x in map(int, bits) if x in self._valid_mask_octets]
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001249 except ValueError:
1250 return False
1251 if len(parts) != len(bits):
1252 return False
1253 if parts[0] < parts[-1]:
1254 return True
1255 return False
1256
Eric V. Smithebdaaf42014-04-14 12:58:07 -04001257 def _reverse_pointer(self):
1258 """Return the reverse DNS pointer name for the IPv4 address.
1259
1260 This implements the method described in RFC1035 3.5.
1261
1262 """
1263 reverse_octets = str(self).split('.')[::-1]
1264 return '.'.join(reverse_octets) + '.in-addr.arpa'
1265
Nick Coghlandc9b2552012-05-20 21:01:57 +10001266 @property
1267 def max_prefixlen(self):
1268 return self._max_prefixlen
1269
1270 @property
1271 def version(self):
1272 return self._version
1273
Nick Coghlandc9b2552012-05-20 21:01:57 +10001274
1275class IPv4Address(_BaseV4, _BaseAddress):
1276
1277 """Represent and manipulate single IPv4 Addresses."""
1278
1279 def __init__(self, address):
1280
1281 """
1282 Args:
1283 address: A string or integer representing the IP
1284
1285 Additionally, an integer can be passed, so
1286 IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1287 or, more generally
1288 IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1289 IPv4Address('192.0.2.1')
1290
1291 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001292 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001293
1294 """
Nick Coghlandc9b2552012-05-20 21:01:57 +10001295 _BaseV4.__init__(self, address)
1296
1297 # Efficient constructor from integer.
1298 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001299 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001300 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001301 return
1302
1303 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001304 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001305 self._check_packed_address(address, 4)
Nick Coghlandb7920b2012-08-20 10:19:12 +10001306 self._ip = int.from_bytes(address, 'big')
Nick Coghlandc9b2552012-05-20 21:01:57 +10001307 return
1308
1309 # Assume input argument to be string or any object representation
1310 # which converts into a formatted IP string.
1311 addr_str = str(address)
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +02001312 if '/' in addr_str:
1313 raise AddressValueError("Unexpected '/' in %r" % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001314 self._ip = self._ip_int_from_string(addr_str)
1315
1316 @property
1317 def packed(self):
1318 """The binary representation of this address."""
1319 return v4_int_to_packed(self._ip)
1320
Nick Coghlan730f67f2012-08-05 22:02:18 +10001321 @property
1322 def is_reserved(self):
1323 """Test if the address is otherwise IETF reserved.
1324
1325 Returns:
1326 A boolean, True if the address is within the
1327 reserved IPv4 Network range.
1328
1329 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001330 return self in self._constants._reserved_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001331
1332 @property
Peter Moodybe9c1b12013-10-22 12:36:21 -07001333 @functools.lru_cache()
Nick Coghlan730f67f2012-08-05 22:02:18 +10001334 def is_private(self):
1335 """Test if this address is allocated for private networks.
1336
1337 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001338 A boolean, True if the address is reserved per
1339 iana-ipv4-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001340
1341 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001342 return any(self in net for net in self._constants._private_networks)
Nick Coghlan730f67f2012-08-05 22:02:18 +10001343
1344 @property
1345 def is_multicast(self):
1346 """Test if the address is reserved for multicast use.
1347
1348 Returns:
1349 A boolean, True if the address is multicast.
1350 See RFC 3171 for details.
1351
1352 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001353 return self in self._constants._multicast_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001354
1355 @property
1356 def is_unspecified(self):
1357 """Test if the address is unspecified.
1358
1359 Returns:
1360 A boolean, True if this is the unspecified address as defined in
1361 RFC 5735 3.
1362
1363 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001364 return self == self._constants._unspecified_address
Nick Coghlan730f67f2012-08-05 22:02:18 +10001365
1366 @property
1367 def is_loopback(self):
1368 """Test if the address is a loopback address.
1369
1370 Returns:
1371 A boolean, True if the address is a loopback per RFC 3330.
1372
1373 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001374 return self in self._constants._loopback_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001375
1376 @property
1377 def is_link_local(self):
1378 """Test if the address is reserved for link-local.
1379
1380 Returns:
1381 A boolean, True if the address is link-local per RFC 3927.
1382
1383 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001384 return self in self._constants._linklocal_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001385
Nick Coghlandc9b2552012-05-20 21:01:57 +10001386
1387class IPv4Interface(IPv4Address):
1388
Nick Coghlandc9b2552012-05-20 21:01:57 +10001389 def __init__(self, address):
1390 if isinstance(address, (bytes, int)):
1391 IPv4Address.__init__(self, address)
1392 self.network = IPv4Network(self._ip)
1393 self._prefixlen = self._max_prefixlen
1394 return
1395
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001396 if isinstance(address, tuple):
1397 IPv4Address.__init__(self, address[0])
1398 if len(address) > 1:
1399 self._prefixlen = int(address[1])
1400 else:
1401 self._prefixlen = self._max_prefixlen
1402
1403 self.network = IPv4Network(address, strict=False)
1404 self.netmask = self.network.netmask
1405 self.hostmask = self.network.hostmask
1406 return
1407
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001408 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001409 IPv4Address.__init__(self, addr[0])
1410
1411 self.network = IPv4Network(address, strict=False)
1412 self._prefixlen = self.network._prefixlen
1413
1414 self.netmask = self.network.netmask
1415 self.hostmask = self.network.hostmask
1416
Nick Coghlandc9b2552012-05-20 21:01:57 +10001417 def __str__(self):
1418 return '%s/%d' % (self._string_from_ip_int(self._ip),
1419 self.network.prefixlen)
1420
1421 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001422 address_equal = IPv4Address.__eq__(self, other)
1423 if not address_equal or address_equal is NotImplemented:
1424 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001425 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001426 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001427 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001428 # An interface with an associated network is NOT the
1429 # same as an unassociated address. That's why the hash
1430 # takes the extra info into account.
1431 return False
1432
1433 def __lt__(self, other):
1434 address_less = IPv4Address.__lt__(self, other)
1435 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001436 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001437 try:
1438 return self.network < other.network
1439 except AttributeError:
1440 # We *do* allow addresses and interfaces to be sorted. The
1441 # unassociated address is considered less than all interfaces.
1442 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001443
1444 def __hash__(self):
1445 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1446
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +02001447 __reduce__ = _IPAddressBase.__reduce__
1448
Nick Coghlandc9b2552012-05-20 21:01:57 +10001449 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001450 def ip(self):
1451 return IPv4Address(self._ip)
1452
1453 @property
1454 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10001455 return '%s/%s' % (self._string_from_ip_int(self._ip),
1456 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001457
1458 @property
1459 def with_netmask(self):
1460 return '%s/%s' % (self._string_from_ip_int(self._ip),
1461 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001462
Nick Coghlandc9b2552012-05-20 21:01:57 +10001463 @property
1464 def with_hostmask(self):
1465 return '%s/%s' % (self._string_from_ip_int(self._ip),
1466 self.hostmask)
1467
1468
1469class IPv4Network(_BaseV4, _BaseNetwork):
1470
1471 """This class represents and manipulates 32-bit IPv4 network + addresses..
1472
1473 Attributes: [examples for IPv4Network('192.0.2.0/27')]
1474 .network_address: IPv4Address('192.0.2.0')
1475 .hostmask: IPv4Address('0.0.0.31')
1476 .broadcast_address: IPv4Address('192.0.2.32')
1477 .netmask: IPv4Address('255.255.255.224')
1478 .prefixlen: 27
1479
1480 """
Nick Coghlan51c30672012-05-27 00:25:58 +10001481 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001482 _address_class = IPv4Address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001483
Nick Coghlandc9b2552012-05-20 21:01:57 +10001484 def __init__(self, address, strict=True):
1485
1486 """Instantiate a new IPv4 network object.
1487
1488 Args:
1489 address: A string or integer representing the IP [& network].
1490 '192.0.2.0/24'
1491 '192.0.2.0/255.255.255.0'
1492 '192.0.0.2/0.0.0.255'
1493 are all functionally the same in IPv4. Similarly,
1494 '192.0.2.1'
1495 '192.0.2.1/255.255.255.255'
1496 '192.0.2.1/32'
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001497 are also functionally equivalent. That is to say, failing to
Nick Coghlandc9b2552012-05-20 21:01:57 +10001498 provide a subnetmask will create an object with a mask of /32.
1499
1500 If the mask (portion after the / in the argument) is given in
1501 dotted quad form, it is treated as a netmask if it starts with a
1502 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1503 starts with a zero field (e.g. 0.255.255.255 == /8), with the
1504 single exception of an all-zero mask which is treated as a
1505 netmask == /0. If no mask is given, a default of /32 is used.
1506
1507 Additionally, an integer can be passed, so
1508 IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1509 or, more generally
1510 IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1511 IPv4Interface('192.0.2.1')
1512
1513 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001514 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001515 NetmaskValueError: If the netmask isn't valid for
1516 an IPv4 address.
Sandro Tosib4386d32012-06-02 17:14:22 +02001517 ValueError: If strict is True and a network address is not
Nick Coghlandc9b2552012-05-20 21:01:57 +10001518 supplied.
1519
1520 """
1521
1522 _BaseV4.__init__(self, address)
1523 _BaseNetwork.__init__(self, address)
1524
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001525 # Constructing from a packed address or integer
1526 if isinstance(address, (int, bytes)):
Nick Coghlan297b1432012-07-08 17:11:04 +10001527 self.network_address = IPv4Address(address)
Antoine Pitrou45aba182014-05-15 20:18:41 +02001528 self.netmask, self._prefixlen = self._make_netmask(self._max_prefixlen)
1529 #fixme: address/network test here.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001530 return
1531
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001532 if isinstance(address, tuple):
1533 if len(address) > 1:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001534 arg = address[1]
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001535 else:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001536 # We weren't given an address[1]
1537 arg = self._max_prefixlen
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001538 self.network_address = IPv4Address(address[0])
Antoine Pitrou45aba182014-05-15 20:18:41 +02001539 self.netmask, self._prefixlen = self._make_netmask(arg)
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001540 packed = int(self.network_address)
1541 if packed & int(self.netmask) != packed:
1542 if strict:
1543 raise ValueError('%s has host bits set' % self)
1544 else:
1545 self.network_address = IPv4Address(packed &
1546 int(self.netmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001547 return
1548
1549 # Assume input argument to be string or any object representation
1550 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001551 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001552 self.network_address = IPv4Address(self._ip_int_from_string(addr[0]))
1553
Nick Coghlandc9b2552012-05-20 21:01:57 +10001554 if len(addr) == 2:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001555 arg = addr[1]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001556 else:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001557 arg = self._max_prefixlen
1558 self.netmask, self._prefixlen = self._make_netmask(arg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001559
1560 if strict:
1561 if (IPv4Address(int(self.network_address) & int(self.netmask)) !=
1562 self.network_address):
1563 raise ValueError('%s has host bits set' % self)
1564 self.network_address = IPv4Address(int(self.network_address) &
1565 int(self.netmask))
1566
1567 if self._prefixlen == (self._max_prefixlen - 1):
1568 self.hosts = self.__iter__
1569
Peter Moodye5019d52013-10-24 09:47:10 -07001570 @property
1571 @functools.lru_cache()
1572 def is_global(self):
1573 """Test if this address is allocated for public networks.
1574
1575 Returns:
1576 A boolean, True if the address is not reserved per
1577 iana-ipv4-special-registry.
1578
1579 """
1580 return (not (self.network_address in IPv4Network('100.64.0.0/10') and
1581 self.broadcast_address in IPv4Network('100.64.0.0/10')) and
1582 not self.is_private)
1583
1584
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001585class _IPv4Constants:
1586 _linklocal_network = IPv4Network('169.254.0.0/16')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001587
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001588 _loopback_network = IPv4Network('127.0.0.0/8')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001589
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001590 _multicast_network = IPv4Network('224.0.0.0/4')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001591
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001592 _private_networks = [
1593 IPv4Network('0.0.0.0/8'),
1594 IPv4Network('10.0.0.0/8'),
1595 IPv4Network('127.0.0.0/8'),
1596 IPv4Network('169.254.0.0/16'),
1597 IPv4Network('172.16.0.0/12'),
1598 IPv4Network('192.0.0.0/29'),
1599 IPv4Network('192.0.0.170/31'),
1600 IPv4Network('192.0.2.0/24'),
1601 IPv4Network('192.168.0.0/16'),
1602 IPv4Network('198.18.0.0/15'),
1603 IPv4Network('198.51.100.0/24'),
1604 IPv4Network('203.0.113.0/24'),
1605 IPv4Network('240.0.0.0/4'),
1606 IPv4Network('255.255.255.255/32'),
1607 ]
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001608
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001609 _reserved_network = IPv4Network('240.0.0.0/4')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001610
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001611 _unspecified_address = IPv4Address('0.0.0.0')
1612
1613
1614IPv4Address._constants = _IPv4Constants
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001615
Nick Coghlandc9b2552012-05-20 21:01:57 +10001616
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001617class _BaseV6:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001618
1619 """Base IPv6 object.
1620
1621 The following methods are used by IPv6 objects in both single IP
1622 addresses and networks.
1623
1624 """
1625
1626 _ALL_ONES = (2**IPV6LENGTH) - 1
1627 _HEXTET_COUNT = 8
1628 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
Antoine Pitrou45aba182014-05-15 20:18:41 +02001629 _max_prefixlen = IPV6LENGTH
1630
1631 # There are only a bunch of valid v6 netmasks, so we cache them all
1632 # when constructed (see _make_netmask()).
1633 _netmask_cache = {}
Nick Coghlandc9b2552012-05-20 21:01:57 +10001634
1635 def __init__(self, address):
1636 self._version = 6
Nick Coghlandc9b2552012-05-20 21:01:57 +10001637
Antoine Pitrou45aba182014-05-15 20:18:41 +02001638 @classmethod
1639 def _make_netmask(cls, arg):
1640 """Make a (netmask, prefix_len) tuple from the given argument.
1641
1642 Argument can be:
1643 - an integer (the prefix length)
1644 - a string representing the prefix length (e.g. "24")
1645 - a string representing the prefix netmask (e.g. "255.255.255.0")
1646 """
1647 if arg not in cls._netmask_cache:
1648 if isinstance(arg, int):
1649 prefixlen = arg
1650 else:
1651 prefixlen = cls._prefix_from_prefix_string(arg)
1652 netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen))
1653 cls._netmask_cache[arg] = netmask, prefixlen
1654 return cls._netmask_cache[arg]
1655
1656 @classmethod
1657 def _ip_int_from_string(cls, ip_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001658 """Turn an IPv6 ip_str into an integer.
1659
1660 Args:
1661 ip_str: A string, the IPv6 ip_str.
1662
1663 Returns:
1664 An int, the IPv6 address
1665
1666 Raises:
1667 AddressValueError: if ip_str isn't a valid IPv6 Address.
1668
1669 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001670 if not ip_str:
1671 raise AddressValueError('Address cannot be empty')
1672
Nick Coghlandc9b2552012-05-20 21:01:57 +10001673 parts = ip_str.split(':')
1674
1675 # An IPv6 address needs at least 2 colons (3 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001676 _min_parts = 3
1677 if len(parts) < _min_parts:
1678 msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
1679 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001680
1681 # If the address has an IPv4-style suffix, convert it to hexadecimal.
1682 if '.' in parts[-1]:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001683 try:
1684 ipv4_int = IPv4Address(parts.pop())._ip
1685 except AddressValueError as exc:
1686 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001687 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1688 parts.append('%x' % (ipv4_int & 0xFFFF))
1689
1690 # An IPv6 address can't have more than 8 colons (9 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001691 # The extra colon comes from using the "::" notation for a single
1692 # leading or trailing zero part.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001693 _max_parts = cls._HEXTET_COUNT + 1
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001694 if len(parts) > _max_parts:
1695 msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
1696 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001697
1698 # Disregarding the endpoints, find '::' with nothing in between.
1699 # This indicates that a run of zeroes has been skipped.
Nick Coghlan7319f692012-07-07 21:43:30 +10001700 skip_index = None
1701 for i in range(1, len(parts) - 1):
1702 if not parts[i]:
1703 if skip_index is not None:
1704 # Can't have more than one '::'
1705 msg = "At most one '::' permitted in %r" % ip_str
1706 raise AddressValueError(msg)
1707 skip_index = i
Nick Coghlandc9b2552012-05-20 21:01:57 +10001708
1709 # parts_hi is the number of parts to copy from above/before the '::'
1710 # parts_lo is the number of parts to copy from below/after the '::'
1711 if skip_index is not None:
1712 # If we found a '::', then check if it also covers the endpoints.
1713 parts_hi = skip_index
1714 parts_lo = len(parts) - skip_index - 1
1715 if not parts[0]:
1716 parts_hi -= 1
1717 if parts_hi:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001718 msg = "Leading ':' only permitted as part of '::' in %r"
1719 raise AddressValueError(msg % ip_str) # ^: requires ^::
Nick Coghlandc9b2552012-05-20 21:01:57 +10001720 if not parts[-1]:
1721 parts_lo -= 1
1722 if parts_lo:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001723 msg = "Trailing ':' only permitted as part of '::' in %r"
1724 raise AddressValueError(msg % ip_str) # :$ requires ::$
Antoine Pitrou45aba182014-05-15 20:18:41 +02001725 parts_skipped = cls._HEXTET_COUNT - (parts_hi + parts_lo)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001726 if parts_skipped < 1:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001727 msg = "Expected at most %d other parts with '::' in %r"
Antoine Pitrou45aba182014-05-15 20:18:41 +02001728 raise AddressValueError(msg % (cls._HEXTET_COUNT-1, ip_str))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001729 else:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001730 # Otherwise, allocate the entire address to parts_hi. The
1731 # endpoints could still be empty, but _parse_hextet() will check
1732 # for that.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001733 if len(parts) != cls._HEXTET_COUNT:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001734 msg = "Exactly %d parts expected without '::' in %r"
Antoine Pitrou45aba182014-05-15 20:18:41 +02001735 raise AddressValueError(msg % (cls._HEXTET_COUNT, ip_str))
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001736 if not parts[0]:
1737 msg = "Leading ':' only permitted as part of '::' in %r"
1738 raise AddressValueError(msg % ip_str) # ^: requires ^::
1739 if not parts[-1]:
1740 msg = "Trailing ':' only permitted as part of '::' in %r"
1741 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001742 parts_hi = len(parts)
1743 parts_lo = 0
1744 parts_skipped = 0
1745
1746 try:
1747 # Now, parse the hextets into a 128-bit integer.
1748 ip_int = 0
1749 for i in range(parts_hi):
1750 ip_int <<= 16
Antoine Pitrou45aba182014-05-15 20:18:41 +02001751 ip_int |= cls._parse_hextet(parts[i])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001752 ip_int <<= 16 * parts_skipped
1753 for i in range(-parts_lo, 0):
1754 ip_int <<= 16
Antoine Pitrou45aba182014-05-15 20:18:41 +02001755 ip_int |= cls._parse_hextet(parts[i])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001756 return ip_int
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001757 except ValueError as exc:
1758 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001759
Antoine Pitrou45aba182014-05-15 20:18:41 +02001760 @classmethod
1761 def _parse_hextet(cls, hextet_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001762 """Convert an IPv6 hextet string into an integer.
1763
1764 Args:
1765 hextet_str: A string, the number to parse.
1766
1767 Returns:
1768 The hextet as an integer.
1769
1770 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001771 ValueError: if the input isn't strictly a hex number from
1772 [0..FFFF].
Nick Coghlandc9b2552012-05-20 21:01:57 +10001773
1774 """
1775 # Whitelist the characters, since int() allows a lot of bizarre stuff.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001776 if not cls._HEX_DIGITS.issuperset(hextet_str):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001777 raise ValueError("Only hex digits permitted in %r" % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001778 # We do the length check second, since the invalid character error
1779 # is likely to be more informative for the user
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001780 if len(hextet_str) > 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001781 msg = "At most 4 characters permitted in %r"
1782 raise ValueError(msg % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001783 # Length check means we can skip checking the integer value
1784 return int(hextet_str, 16)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001785
Antoine Pitrou45aba182014-05-15 20:18:41 +02001786 @classmethod
1787 def _compress_hextets(cls, hextets):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001788 """Compresses a list of hextets.
1789
1790 Compresses a list of strings, replacing the longest continuous
1791 sequence of "0" in the list with "" and adding empty strings at
1792 the beginning or at the end of the string such that subsequently
1793 calling ":".join(hextets) will produce the compressed version of
1794 the IPv6 address.
1795
1796 Args:
1797 hextets: A list of strings, the hextets to compress.
1798
1799 Returns:
1800 A list of strings.
1801
1802 """
1803 best_doublecolon_start = -1
1804 best_doublecolon_len = 0
1805 doublecolon_start = -1
1806 doublecolon_len = 0
Nick Coghlandb7920b2012-08-20 10:19:12 +10001807 for index, hextet in enumerate(hextets):
1808 if hextet == '0':
Nick Coghlandc9b2552012-05-20 21:01:57 +10001809 doublecolon_len += 1
1810 if doublecolon_start == -1:
1811 # Start of a sequence of zeros.
1812 doublecolon_start = index
1813 if doublecolon_len > best_doublecolon_len:
1814 # This is the longest sequence of zeros so far.
1815 best_doublecolon_len = doublecolon_len
1816 best_doublecolon_start = doublecolon_start
1817 else:
1818 doublecolon_len = 0
1819 doublecolon_start = -1
1820
1821 if best_doublecolon_len > 1:
1822 best_doublecolon_end = (best_doublecolon_start +
1823 best_doublecolon_len)
1824 # For zeros at the end of the address.
1825 if best_doublecolon_end == len(hextets):
1826 hextets += ['']
1827 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1828 # For zeros at the beginning of the address.
1829 if best_doublecolon_start == 0:
1830 hextets = [''] + hextets
1831
1832 return hextets
1833
Antoine Pitrou45aba182014-05-15 20:18:41 +02001834 @classmethod
1835 def _string_from_ip_int(cls, ip_int=None):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001836 """Turns a 128-bit integer into hexadecimal notation.
1837
1838 Args:
1839 ip_int: An integer, the IP address.
1840
1841 Returns:
1842 A string, the hexadecimal representation of the address.
1843
1844 Raises:
1845 ValueError: The address is bigger than 128 bits of all ones.
1846
1847 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001848 if ip_int is None:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001849 ip_int = int(cls._ip)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001850
Antoine Pitrou45aba182014-05-15 20:18:41 +02001851 if ip_int > cls._ALL_ONES:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001852 raise ValueError('IPv6 address is too large')
1853
1854 hex_str = '%032x' % ip_int
Nick Coghlan7319f692012-07-07 21:43:30 +10001855 hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001856
Antoine Pitrou45aba182014-05-15 20:18:41 +02001857 hextets = cls._compress_hextets(hextets)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001858 return ':'.join(hextets)
1859
1860 def _explode_shorthand_ip_string(self):
1861 """Expand a shortened IPv6 address.
1862
1863 Args:
1864 ip_str: A string, the IPv6 address.
1865
1866 Returns:
1867 A string, the expanded IPv6 address.
1868
1869 """
1870 if isinstance(self, IPv6Network):
1871 ip_str = str(self.network_address)
1872 elif isinstance(self, IPv6Interface):
1873 ip_str = str(self.ip)
1874 else:
1875 ip_str = str(self)
1876
1877 ip_int = self._ip_int_from_string(ip_str)
Nick Coghlan7319f692012-07-07 21:43:30 +10001878 hex_str = '%032x' % ip_int
1879 parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001880 if isinstance(self, (_BaseNetwork, IPv6Interface)):
Nick Coghlane3ded952012-08-05 22:45:22 +10001881 return '%s/%d' % (':'.join(parts), self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001882 return ':'.join(parts)
1883
Eric V. Smithebdaaf42014-04-14 12:58:07 -04001884 def _reverse_pointer(self):
1885 """Return the reverse DNS pointer name for the IPv6 address.
1886
1887 This implements the method described in RFC3596 2.5.
1888
1889 """
1890 reverse_chars = self.exploded[::-1].replace(':', '')
1891 return '.'.join(reverse_chars) + '.ip6.arpa'
1892
Nick Coghlandc9b2552012-05-20 21:01:57 +10001893 @property
1894 def max_prefixlen(self):
1895 return self._max_prefixlen
1896
1897 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001898 def version(self):
1899 return self._version
1900
Nick Coghlandc9b2552012-05-20 21:01:57 +10001901
1902class IPv6Address(_BaseV6, _BaseAddress):
1903
Sandro Tosib95c6342012-05-23 23:17:22 +02001904 """Represent and manipulate single IPv6 Addresses."""
Nick Coghlandc9b2552012-05-20 21:01:57 +10001905
1906 def __init__(self, address):
1907 """Instantiate a new IPv6 address object.
1908
1909 Args:
1910 address: A string or integer representing the IP
1911
1912 Additionally, an integer can be passed, so
1913 IPv6Address('2001:db8::') ==
1914 IPv6Address(42540766411282592856903984951653826560)
1915 or, more generally
1916 IPv6Address(int(IPv6Address('2001:db8::'))) ==
1917 IPv6Address('2001:db8::')
1918
1919 Raises:
1920 AddressValueError: If address isn't a valid IPv6 address.
1921
1922 """
Nick Coghlandc9b2552012-05-20 21:01:57 +10001923 _BaseV6.__init__(self, address)
1924
1925 # Efficient constructor from integer.
1926 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001927 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001928 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001929 return
1930
1931 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001932 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001933 self._check_packed_address(address, 16)
Nick Coghlandb7920b2012-08-20 10:19:12 +10001934 self._ip = int.from_bytes(address, 'big')
Nick Coghlandc9b2552012-05-20 21:01:57 +10001935 return
1936
1937 # Assume input argument to be string or any object representation
1938 # which converts into a formatted IP string.
1939 addr_str = str(address)
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +02001940 if '/' in addr_str:
1941 raise AddressValueError("Unexpected '/' in %r" % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001942 self._ip = self._ip_int_from_string(addr_str)
1943
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001944 @property
1945 def packed(self):
1946 """The binary representation of this address."""
1947 return v6_int_to_packed(self._ip)
1948
Nick Coghlan730f67f2012-08-05 22:02:18 +10001949 @property
1950 def is_multicast(self):
1951 """Test if the address is reserved for multicast use.
1952
1953 Returns:
1954 A boolean, True if the address is a multicast address.
1955 See RFC 2373 2.7 for details.
1956
1957 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001958 return self in self._constants._multicast_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001959
1960 @property
1961 def is_reserved(self):
1962 """Test if the address is otherwise IETF reserved.
1963
1964 Returns:
1965 A boolean, True if the address is within one of the
1966 reserved IPv6 Network ranges.
1967
1968 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001969 return any(self in x for x in self._constants._reserved_networks)
Nick Coghlan730f67f2012-08-05 22:02:18 +10001970
1971 @property
1972 def is_link_local(self):
1973 """Test if the address is reserved for link-local.
1974
1975 Returns:
1976 A boolean, True if the address is reserved per RFC 4291.
1977
1978 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001979 return self in self._constants._linklocal_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001980
1981 @property
1982 def is_site_local(self):
1983 """Test if the address is reserved for site-local.
1984
1985 Note that the site-local address space has been deprecated by RFC 3879.
1986 Use is_private to test if this address is in the space of unique local
1987 addresses as defined by RFC 4193.
1988
1989 Returns:
1990 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1991
1992 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001993 return self in self._constants._sitelocal_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001994
1995 @property
Peter Moodybe9c1b12013-10-22 12:36:21 -07001996 @functools.lru_cache()
Nick Coghlan730f67f2012-08-05 22:02:18 +10001997 def is_private(self):
1998 """Test if this address is allocated for private networks.
1999
2000 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07002001 A boolean, True if the address is reserved per
2002 iana-ipv6-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10002003
2004 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002005 return any(self in net for net in self._constants._private_networks)
Peter Moody22c31762013-10-21 13:58:06 -07002006
2007 @property
2008 def is_global(self):
2009 """Test if this address is allocated for public networks.
2010
2011 Returns:
2012 A boolean, true if the address is not reserved per
2013 iana-ipv6-special-registry.
2014
2015 """
2016 return not self.is_private
Nick Coghlan730f67f2012-08-05 22:02:18 +10002017
2018 @property
2019 def is_unspecified(self):
2020 """Test if the address is unspecified.
2021
2022 Returns:
2023 A boolean, True if this is the unspecified address as defined in
2024 RFC 2373 2.5.2.
2025
2026 """
2027 return self._ip == 0
2028
2029 @property
2030 def is_loopback(self):
2031 """Test if the address is a loopback address.
2032
2033 Returns:
2034 A boolean, True if the address is a loopback address as defined in
2035 RFC 2373 2.5.3.
2036
2037 """
2038 return self._ip == 1
2039
2040 @property
2041 def ipv4_mapped(self):
2042 """Return the IPv4 mapped address.
2043
2044 Returns:
2045 If the IPv6 address is a v4 mapped address, return the
2046 IPv4 mapped address. Return None otherwise.
2047
2048 """
2049 if (self._ip >> 32) != 0xFFFF:
2050 return None
2051 return IPv4Address(self._ip & 0xFFFFFFFF)
2052
2053 @property
2054 def teredo(self):
2055 """Tuple of embedded teredo IPs.
2056
2057 Returns:
2058 Tuple of the (server, client) IPs or None if the address
2059 doesn't appear to be a teredo address (doesn't start with
2060 2001::/32)
2061
2062 """
2063 if (self._ip >> 96) != 0x20010000:
2064 return None
2065 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
2066 IPv4Address(~self._ip & 0xFFFFFFFF))
2067
2068 @property
2069 def sixtofour(self):
2070 """Return the IPv4 6to4 embedded address.
2071
2072 Returns:
2073 The IPv4 6to4-embedded address if present or None if the
2074 address doesn't appear to contain a 6to4 embedded address.
2075
2076 """
2077 if (self._ip >> 112) != 0x2002:
2078 return None
2079 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
2080
Nick Coghlandc9b2552012-05-20 21:01:57 +10002081
2082class IPv6Interface(IPv6Address):
2083
2084 def __init__(self, address):
2085 if isinstance(address, (bytes, int)):
2086 IPv6Address.__init__(self, address)
2087 self.network = IPv6Network(self._ip)
2088 self._prefixlen = self._max_prefixlen
2089 return
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002090 if isinstance(address, tuple):
2091 IPv6Address.__init__(self, address[0])
2092 if len(address) > 1:
2093 self._prefixlen = int(address[1])
2094 else:
2095 self._prefixlen = self._max_prefixlen
2096 self.network = IPv6Network(address, strict=False)
2097 self.netmask = self.network.netmask
2098 self.hostmask = self.network.hostmask
2099 return
Nick Coghlandc9b2552012-05-20 21:01:57 +10002100
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002101 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002102 IPv6Address.__init__(self, addr[0])
2103 self.network = IPv6Network(address, strict=False)
2104 self.netmask = self.network.netmask
2105 self._prefixlen = self.network._prefixlen
2106 self.hostmask = self.network.hostmask
2107
Nick Coghlandc9b2552012-05-20 21:01:57 +10002108 def __str__(self):
2109 return '%s/%d' % (self._string_from_ip_int(self._ip),
2110 self.network.prefixlen)
2111
2112 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10002113 address_equal = IPv6Address.__eq__(self, other)
2114 if not address_equal or address_equal is NotImplemented:
2115 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10002116 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10002117 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10002118 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10002119 # An interface with an associated network is NOT the
2120 # same as an unassociated address. That's why the hash
2121 # takes the extra info into account.
2122 return False
2123
2124 def __lt__(self, other):
2125 address_less = IPv6Address.__lt__(self, other)
2126 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10002127 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10002128 try:
2129 return self.network < other.network
2130 except AttributeError:
2131 # We *do* allow addresses and interfaces to be sorted. The
2132 # unassociated address is considered less than all interfaces.
2133 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10002134
2135 def __hash__(self):
2136 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
2137
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +02002138 __reduce__ = _IPAddressBase.__reduce__
2139
Nick Coghlandc9b2552012-05-20 21:01:57 +10002140 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10002141 def ip(self):
2142 return IPv6Address(self._ip)
2143
2144 @property
2145 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10002146 return '%s/%s' % (self._string_from_ip_int(self._ip),
2147 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002148
2149 @property
2150 def with_netmask(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10002151 return '%s/%s' % (self._string_from_ip_int(self._ip),
2152 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02002153
Nick Coghlandc9b2552012-05-20 21:01:57 +10002154 @property
2155 def with_hostmask(self):
2156 return '%s/%s' % (self._string_from_ip_int(self._ip),
2157 self.hostmask)
2158
Nick Coghlan730f67f2012-08-05 22:02:18 +10002159 @property
2160 def is_unspecified(self):
2161 return self._ip == 0 and self.network.is_unspecified
2162
2163 @property
2164 def is_loopback(self):
2165 return self._ip == 1 and self.network.is_loopback
2166
Nick Coghlandc9b2552012-05-20 21:01:57 +10002167
2168class IPv6Network(_BaseV6, _BaseNetwork):
2169
2170 """This class represents and manipulates 128-bit IPv6 networks.
2171
2172 Attributes: [examples for IPv6('2001:db8::1000/124')]
2173 .network_address: IPv6Address('2001:db8::1000')
2174 .hostmask: IPv6Address('::f')
2175 .broadcast_address: IPv6Address('2001:db8::100f')
2176 .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
2177 .prefixlen: 124
2178
2179 """
2180
Nick Coghlan51c30672012-05-27 00:25:58 +10002181 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10002182 _address_class = IPv6Address
2183
Nick Coghlandc9b2552012-05-20 21:01:57 +10002184 def __init__(self, address, strict=True):
2185 """Instantiate a new IPv6 Network object.
2186
2187 Args:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02002188 address: A string or integer representing the IPv6 network or the
2189 IP and prefix/netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +10002190 '2001:db8::/128'
2191 '2001:db8:0000:0000:0000:0000:0000:0000/128'
2192 '2001:db8::'
2193 are all functionally the same in IPv6. That is to say,
2194 failing to provide a subnetmask will create an object with
2195 a mask of /128.
2196
2197 Additionally, an integer can be passed, so
2198 IPv6Network('2001:db8::') ==
2199 IPv6Network(42540766411282592856903984951653826560)
2200 or, more generally
2201 IPv6Network(int(IPv6Network('2001:db8::'))) ==
2202 IPv6Network('2001:db8::')
2203
2204 strict: A boolean. If true, ensure that we have been passed
2205 A true network address, eg, 2001:db8::1000/124 and not an
2206 IP address on a network, eg, 2001:db8::1/124.
2207
2208 Raises:
2209 AddressValueError: If address isn't a valid IPv6 address.
2210 NetmaskValueError: If the netmask isn't valid for
2211 an IPv6 address.
2212 ValueError: If strict was True and a network address was not
2213 supplied.
2214
2215 """
2216 _BaseV6.__init__(self, address)
2217 _BaseNetwork.__init__(self, address)
2218
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002219 # Efficient constructor from integer or packed address
2220 if isinstance(address, (bytes, int)):
Nick Coghlandc9b2552012-05-20 21:01:57 +10002221 self.network_address = IPv6Address(address)
Antoine Pitrou45aba182014-05-15 20:18:41 +02002222 self.netmask, self._prefixlen = self._make_netmask(self._max_prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002223 return
2224
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002225 if isinstance(address, tuple):
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002226 if len(address) > 1:
Antoine Pitrou45aba182014-05-15 20:18:41 +02002227 arg = address[1]
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002228 else:
Antoine Pitrou45aba182014-05-15 20:18:41 +02002229 arg = self._max_prefixlen
2230 self.netmask, self._prefixlen = self._make_netmask(arg)
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002231 self.network_address = IPv6Address(address[0])
2232 packed = int(self.network_address)
2233 if packed & int(self.netmask) != packed:
2234 if strict:
2235 raise ValueError('%s has host bits set' % self)
2236 else:
2237 self.network_address = IPv6Address(packed &
2238 int(self.netmask))
Hynek Schlawacked36b2e2012-06-08 15:21:21 +02002239 return
Nick Coghlandc9b2552012-05-20 21:01:57 +10002240
2241 # Assume input argument to be string or any object representation
2242 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002243 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002244
2245 self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))
2246
2247 if len(addr) == 2:
Antoine Pitrou45aba182014-05-15 20:18:41 +02002248 arg = addr[1]
Nick Coghlandc9b2552012-05-20 21:01:57 +10002249 else:
Antoine Pitrou45aba182014-05-15 20:18:41 +02002250 arg = self._max_prefixlen
2251 self.netmask, self._prefixlen = self._make_netmask(arg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002252
Nick Coghlandc9b2552012-05-20 21:01:57 +10002253 if strict:
2254 if (IPv6Address(int(self.network_address) & int(self.netmask)) !=
2255 self.network_address):
Nick Coghlan912238e2012-07-07 13:34:50 +10002256 raise ValueError('%s has host bits set' % self)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002257 self.network_address = IPv6Address(int(self.network_address) &
2258 int(self.netmask))
2259
2260 if self._prefixlen == (self._max_prefixlen - 1):
2261 self.hosts = self.__iter__
2262
Peter Moody1243c7d2014-03-11 09:55:46 -07002263 def hosts(self):
2264 """Generate Iterator over usable hosts in a network.
2265
2266 This is like __iter__ except it doesn't return the
2267 Subnet-Router anycast address.
2268
2269 """
2270 network = int(self.network_address)
2271 broadcast = int(self.broadcast_address)
2272 for x in range(network + 1, broadcast + 1):
2273 yield self._address_class(x)
2274
Nick Coghlan730f67f2012-08-05 22:02:18 +10002275 @property
2276 def is_site_local(self):
2277 """Test if the address is reserved for site-local.
2278
2279 Note that the site-local address space has been deprecated by RFC 3879.
2280 Use is_private to test if this address is in the space of unique local
2281 addresses as defined by RFC 4193.
2282
2283 Returns:
2284 A boolean, True if the address is reserved per RFC 3513 2.5.6.
2285
2286 """
2287 return (self.network_address.is_site_local and
2288 self.broadcast_address.is_site_local)
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002289
2290
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002291class _IPv6Constants:
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002292
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002293 _linklocal_network = IPv6Network('fe80::/10')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002294
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002295 _multicast_network = IPv6Network('ff00::/8')
2296
2297 _private_networks = [
2298 IPv6Network('::1/128'),
2299 IPv6Network('::/128'),
2300 IPv6Network('::ffff:0:0/96'),
2301 IPv6Network('100::/64'),
2302 IPv6Network('2001::/23'),
2303 IPv6Network('2001:2::/48'),
2304 IPv6Network('2001:db8::/32'),
2305 IPv6Network('2001:10::/28'),
2306 IPv6Network('fc00::/7'),
2307 IPv6Network('fe80::/10'),
2308 ]
2309
2310 _reserved_networks = [
2311 IPv6Network('::/8'), IPv6Network('100::/8'),
2312 IPv6Network('200::/7'), IPv6Network('400::/6'),
2313 IPv6Network('800::/5'), IPv6Network('1000::/4'),
2314 IPv6Network('4000::/3'), IPv6Network('6000::/3'),
2315 IPv6Network('8000::/3'), IPv6Network('A000::/3'),
2316 IPv6Network('C000::/3'), IPv6Network('E000::/4'),
2317 IPv6Network('F000::/5'), IPv6Network('F800::/6'),
2318 IPv6Network('FE00::/9'),
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002319 ]
2320
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002321 _sitelocal_network = IPv6Network('fec0::/10')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002322
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002323
2324IPv6Address._constants = _IPv6Constants