blob: bf2de2d4797501e18523a04b2ac0f1ba8eec598c [file] [log] [blame]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001# Copyright 2007 Google Inc.
2# Licensed to PSF under a Contributor Agreement.
Nick Coghlandc9b2552012-05-20 21:01:57 +10003
4"""A fast, lightweight IPv4/IPv6 manipulation library in Python.
5
6This library is used to create/poke/manipulate IPv4 and IPv6 addresses
7and networks.
8
9"""
10
11__version__ = '1.0'
12
Hynek Schlawack91c5a342012-06-05 11:55:58 +020013
Nick Coghlan3008ec02012-07-08 00:45:33 +100014import functools
Hynek Schlawack91c5a342012-06-05 11:55:58 +020015
Nick Coghlandc9b2552012-05-20 21:01:57 +100016IPV4LENGTH = 32
17IPV6LENGTH = 128
18
Nick Coghlandc9b2552012-05-20 21:01:57 +100019class AddressValueError(ValueError):
20 """A Value Error related to the address."""
21
22
23class NetmaskValueError(ValueError):
24 """A Value Error related to the netmask."""
25
26
Nick Coghlan51c30672012-05-27 00:25:58 +100027def ip_address(address):
Nick Coghlandc9b2552012-05-20 21:01:57 +100028 """Take an IP string/int and return an object of the correct type.
29
30 Args:
31 address: A string or integer, the IP address. Either IPv4 or
32 IPv6 addresses may be supplied; integers less than 2**32 will
33 be considered to be IPv4 by default.
Nick Coghlandc9b2552012-05-20 21:01:57 +100034
35 Returns:
36 An IPv4Address or IPv6Address object.
37
38 Raises:
Sandro Tosi876ecad2012-05-23 22:26:55 +020039 ValueError: if the *address* passed isn't either a v4 or a v6
Nick Coghlan51c30672012-05-27 00:25:58 +100040 address
Nick Coghlandc9b2552012-05-20 21:01:57 +100041
42 """
Nick Coghlandc9b2552012-05-20 21:01:57 +100043 try:
44 return IPv4Address(address)
45 except (AddressValueError, NetmaskValueError):
46 pass
47
48 try:
49 return IPv6Address(address)
50 except (AddressValueError, NetmaskValueError):
51 pass
52
53 raise ValueError('%r does not appear to be an IPv4 or IPv6 address' %
54 address)
55
56
Nick Coghlan51c30672012-05-27 00:25:58 +100057def ip_network(address, strict=True):
Nick Coghlandc9b2552012-05-20 21:01:57 +100058 """Take an IP string/int and return an object of the correct type.
59
60 Args:
61 address: A string or integer, the IP network. Either IPv4 or
62 IPv6 networks may be supplied; integers less than 2**32 will
63 be considered to be IPv4 by default.
Nick Coghlandc9b2552012-05-20 21:01:57 +100064
65 Returns:
66 An IPv4Network or IPv6Network object.
67
68 Raises:
69 ValueError: if the string passed isn't either a v4 or a v6
Nick Coghlan51c30672012-05-27 00:25:58 +100070 address. Or if the network has host bits set.
Nick Coghlandc9b2552012-05-20 21:01:57 +100071
72 """
Nick Coghlandc9b2552012-05-20 21:01:57 +100073 try:
74 return IPv4Network(address, strict)
75 except (AddressValueError, NetmaskValueError):
76 pass
77
78 try:
79 return IPv6Network(address, strict)
80 except (AddressValueError, NetmaskValueError):
81 pass
82
83 raise ValueError('%r does not appear to be an IPv4 or IPv6 network' %
84 address)
85
86
Nick Coghlan51c30672012-05-27 00:25:58 +100087def ip_interface(address):
Nick Coghlandc9b2552012-05-20 21:01:57 +100088 """Take an IP string/int and return an object of the correct type.
89
90 Args:
91 address: A string or integer, the IP address. Either IPv4 or
92 IPv6 addresses may be supplied; integers less than 2**32 will
93 be considered to be IPv4 by default.
Nick Coghlandc9b2552012-05-20 21:01:57 +100094
95 Returns:
Sandro Tosi876ecad2012-05-23 22:26:55 +020096 An IPv4Interface or IPv6Interface object.
Nick Coghlandc9b2552012-05-20 21:01:57 +100097
98 Raises:
99 ValueError: if the string passed isn't either a v4 or a v6
Nick Coghlan51c30672012-05-27 00:25:58 +1000100 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000101
102 Notes:
103 The IPv?Interface classes describe an Address on a particular
104 Network, so they're basically a combination of both the Address
105 and Network classes.
Sandro Tosib95c6342012-05-23 23:17:22 +0200106
Nick Coghlandc9b2552012-05-20 21:01:57 +1000107 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000108 try:
109 return IPv4Interface(address)
110 except (AddressValueError, NetmaskValueError):
111 pass
112
113 try:
114 return IPv6Interface(address)
115 except (AddressValueError, NetmaskValueError):
116 pass
117
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000118 raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' %
Nick Coghlandc9b2552012-05-20 21:01:57 +1000119 address)
120
121
122def v4_int_to_packed(address):
Sandro Tosi876ecad2012-05-23 22:26:55 +0200123 """Represent an address as 4 packed bytes in network (big-endian) order.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000124
125 Args:
126 address: An integer representation of an IPv4 IP address.
127
128 Returns:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200129 The integer address packed as 4 bytes in network (big-endian) order.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000130
131 Raises:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200132 ValueError: If the integer is negative or too large to be an
133 IPv4 IP address.
Sandro Tosib95c6342012-05-23 23:17:22 +0200134
Nick Coghlandc9b2552012-05-20 21:01:57 +1000135 """
Sandro Tosi876ecad2012-05-23 22:26:55 +0200136 try:
Nick Coghlandb7920b2012-08-20 10:19:12 +1000137 return address.to_bytes(4, 'big')
Sandro Tosi876ecad2012-05-23 22:26:55 +0200138 except:
139 raise ValueError("Address negative or too large for IPv4")
Nick Coghlandc9b2552012-05-20 21:01:57 +1000140
141
142def v6_int_to_packed(address):
Sandro Tosi876ecad2012-05-23 22:26:55 +0200143 """Represent an address as 16 packed bytes in network (big-endian) order.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000144
145 Args:
Sandro Tosib4386d32012-06-02 17:14:22 +0200146 address: An integer representation of an IPv6 IP address.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000147
148 Returns:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200149 The integer address packed as 16 bytes in network (big-endian) order.
Sandro Tosib95c6342012-05-23 23:17:22 +0200150
Nick Coghlandc9b2552012-05-20 21:01:57 +1000151 """
Sandro Tosi876ecad2012-05-23 22:26:55 +0200152 try:
Nick Coghlandb7920b2012-08-20 10:19:12 +1000153 return address.to_bytes(16, 'big')
Sandro Tosi876ecad2012-05-23 22:26:55 +0200154 except:
155 raise ValueError("Address negative or too large for IPv6")
Nick Coghlandc9b2552012-05-20 21:01:57 +1000156
157
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000158def _split_optional_netmask(address):
159 """Helper to split the netmask and raise AddressValueError if needed"""
160 addr = str(address).split('/')
161 if len(addr) > 2:
162 raise AddressValueError("Only one '/' permitted in %r" % address)
163 return addr
164
Nick Coghlan297b1432012-07-08 17:11:04 +1000165
Nick Coghlandc9b2552012-05-20 21:01:57 +1000166def _find_address_range(addresses):
Sandro Tosi876ecad2012-05-23 22:26:55 +0200167 """Find a sequence of IPv#Address.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000168
169 Args:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200170 addresses: a list of IPv#Address objects.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000171
172 Returns:
173 A tuple containing the first and last IP addresses in the sequence.
174
175 """
176 first = last = addresses[0]
177 for ip in addresses[1:]:
178 if ip._ip == last._ip + 1:
179 last = ip
180 else:
181 break
182 return (first, last)
183
Sandro Tosib95c6342012-05-23 23:17:22 +0200184
Nick Coghlandc9b2552012-05-20 21:01:57 +1000185def _count_righthand_zero_bits(number, bits):
186 """Count the number of zero bits on the right hand side.
187
188 Args:
189 number: an integer.
190 bits: maximum number of bits to count.
191
192 Returns:
193 The number of zero bits on the right hand side of the number.
194
195 """
196 if number == 0:
197 return bits
Antoine Pitrou824db302014-05-15 20:21:48 +0200198 return min(bits, (~number & (number-1)).bit_length())
Nick Coghlandc9b2552012-05-20 21:01:57 +1000199
200
201def summarize_address_range(first, last):
202 """Summarize a network range given the first and last IP addresses.
203
204 Example:
Eli Bendersky948af232012-10-07 07:23:50 -0700205 >>> list(summarize_address_range(IPv4Address('192.0.2.0'),
206 ... IPv4Address('192.0.2.130')))
207 ... #doctest: +NORMALIZE_WHITESPACE
Nick Coghlandc9b2552012-05-20 21:01:57 +1000208 [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'),
Eli Bendersky948af232012-10-07 07:23:50 -0700209 IPv4Network('192.0.2.130/32')]
Nick Coghlandc9b2552012-05-20 21:01:57 +1000210
211 Args:
212 first: the first IPv4Address or IPv6Address in the range.
213 last: the last IPv4Address or IPv6Address in the range.
214
215 Returns:
216 An iterator of the summarized IPv(4|6) network objects.
217
218 Raise:
219 TypeError:
220 If the first and last objects are not IP addresses.
221 If the first and last objects are not the same version.
222 ValueError:
223 If the last object is not greater than the first.
Nick Coghlan51c30672012-05-27 00:25:58 +1000224 If the version of the first address is not 4 or 6.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000225
226 """
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200227 if (not (isinstance(first, _BaseAddress) and
228 isinstance(last, _BaseAddress))):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000229 raise TypeError('first and last must be IP addresses, not networks')
230 if first.version != last.version:
231 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000232 first, last))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000233 if first > last:
234 raise ValueError('last IP address must be greater than first')
235
Nick Coghlandc9b2552012-05-20 21:01:57 +1000236 if first.version == 4:
237 ip = IPv4Network
238 elif first.version == 6:
239 ip = IPv6Network
240 else:
241 raise ValueError('unknown IP version')
242
243 ip_bits = first._max_prefixlen
244 first_int = first._ip
245 last_int = last._ip
246 while first_int <= last_int:
Nick Coghlan7319f692012-07-07 21:43:30 +1000247 nbits = min(_count_righthand_zero_bits(first_int, ip_bits),
248 (last_int - first_int + 1).bit_length() - 1)
Antoine Pitrou824db302014-05-15 20:21:48 +0200249 net = ip((first_int, ip_bits - nbits))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000250 yield net
Nick Coghlan7319f692012-07-07 21:43:30 +1000251 first_int += 1 << nbits
252 if first_int - 1 == ip._ALL_ONES:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000253 break
Nick Coghlandc9b2552012-05-20 21:01:57 +1000254
Sandro Tosib95c6342012-05-23 23:17:22 +0200255
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200256def _collapse_addresses_internal(addresses):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000257 """Loops through the addresses, collapsing concurrent netblocks.
258
259 Example:
260
261 ip1 = IPv4Network('192.0.2.0/26')
262 ip2 = IPv4Network('192.0.2.64/26')
263 ip3 = IPv4Network('192.0.2.128/26')
264 ip4 = IPv4Network('192.0.2.192/26')
265
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200266 _collapse_addresses_internal([ip1, ip2, ip3, ip4]) ->
Nick Coghlandc9b2552012-05-20 21:01:57 +1000267 [IPv4Network('192.0.2.0/24')]
268
269 This shouldn't be called directly; it is called via
270 collapse_addresses([]).
271
272 Args:
273 addresses: A list of IPv4Network's or IPv6Network's
274
275 Returns:
276 A list of IPv4Network's or IPv6Network's depending on what we were
277 passed.
278
279 """
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200280 # First merge
281 to_merge = list(addresses)
282 subnets = {}
283 while to_merge:
284 net = to_merge.pop()
285 supernet = net.supernet()
286 existing = subnets.get(supernet)
287 if existing is None:
288 subnets[supernet] = net
289 elif existing != net:
290 # Merge consecutive subnets
291 del subnets[supernet]
292 to_merge.append(supernet)
293 # Then iterate over resulting networks, skipping subsumed subnets
294 last = None
295 for net in sorted(subnets.values()):
296 if last is not None:
297 # Since they are sorted, last.network_address <= net.network_address
298 # is a given.
299 if last.broadcast_address >= net.broadcast_address:
300 continue
301 yield net
302 last = net
Nick Coghlandc9b2552012-05-20 21:01:57 +1000303
304
305def collapse_addresses(addresses):
306 """Collapse a list of IP objects.
307
308 Example:
309 collapse_addresses([IPv4Network('192.0.2.0/25'),
310 IPv4Network('192.0.2.128/25')]) ->
311 [IPv4Network('192.0.2.0/24')]
312
313 Args:
314 addresses: An iterator of IPv4Network or IPv6Network objects.
315
316 Returns:
317 An iterator of the collapsed IPv(4|6)Network objects.
318
319 Raises:
320 TypeError: If passed a list of mixed version objects.
321
322 """
323 i = 0
324 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
349 # sort and dedup
350 ips = sorted(set(ips))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000351
352 while i < len(ips):
353 (first, last) = _find_address_range(ips[i:])
354 i = ips.index(last) + 1
355 addrs.extend(summarize_address_range(first, last))
356
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:
Nick Coghlan932346f2014-02-08 23:17:36 +1000482 ip_int: An integer, the netmask in axpanded 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
Nick Coghlan730f67f2012-08-05 22:02:18 +1000566
Nick Coghlandc9b2552012-05-20 21:01:57 +1000567class _BaseAddress(_IPAddressBase):
568
569 """A generic IP object.
570
571 This IP class contains the version independent methods which are
572 used by single IP addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000573 """
574
575 def __init__(self, address):
576 if (not isinstance(address, bytes)
577 and '/' in str(address)):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000578 raise AddressValueError("Unexpected '/' in %r" % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000579
Nick Coghlandc9b2552012-05-20 21:01:57 +1000580 def __int__(self):
581 return self._ip
582
Nick Coghlandc9b2552012-05-20 21:01:57 +1000583 def __eq__(self, other):
584 try:
585 return (self._ip == other._ip
586 and self._version == other._version)
587 except AttributeError:
588 return NotImplemented
589
Nick Coghlandc9b2552012-05-20 21:01:57 +1000590 def __lt__(self, other):
591 if self._version != other._version:
592 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000593 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000594 if not isinstance(other, _BaseAddress):
595 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000596 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000597 if self._ip != other._ip:
598 return self._ip < other._ip
599 return False
600
Nick Coghlandc9b2552012-05-20 21:01:57 +1000601 # Shorthand for Integer addition and subtraction. This is not
602 # meant to ever support addition/subtraction of addresses.
603 def __add__(self, other):
604 if not isinstance(other, int):
605 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000606 return self.__class__(int(self) + other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000607
608 def __sub__(self, other):
609 if not isinstance(other, int):
610 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000611 return self.__class__(int(self) - other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000612
613 def __repr__(self):
614 return '%s(%r)' % (self.__class__.__name__, str(self))
615
616 def __str__(self):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200617 return str(self._string_from_ip_int(self._ip))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000618
619 def __hash__(self):
620 return hash(hex(int(self._ip)))
621
622 def _get_address_key(self):
623 return (self._version, self)
624
Nick Coghlandc9b2552012-05-20 21:01:57 +1000625
626class _BaseNetwork(_IPAddressBase):
627
Nick Coghlan51c30672012-05-27 00:25:58 +1000628 """A generic IP network object.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000629
630 This IP class contains the version independent methods which are
631 used by networks.
632
633 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000634 def __init__(self, address):
635 self._cache = {}
636
Nick Coghlandc9b2552012-05-20 21:01:57 +1000637 def __repr__(self):
638 return '%s(%r)' % (self.__class__.__name__, str(self))
639
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200640 def __str__(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000641 return '%s/%d' % (self.network_address, self.prefixlen)
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200642
Nick Coghlandc9b2552012-05-20 21:01:57 +1000643 def hosts(self):
644 """Generate Iterator over usable hosts in a network.
645
Sandro Tosib95c6342012-05-23 23:17:22 +0200646 This is like __iter__ except it doesn't return the network
647 or broadcast addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000648
649 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000650 network = int(self.network_address)
651 broadcast = int(self.broadcast_address)
652 for x in range(network + 1, broadcast):
653 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000654
655 def __iter__(self):
Nick Coghlan7319f692012-07-07 21:43:30 +1000656 network = int(self.network_address)
657 broadcast = int(self.broadcast_address)
658 for x in range(network, broadcast + 1):
659 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000660
661 def __getitem__(self, n):
662 network = int(self.network_address)
663 broadcast = int(self.broadcast_address)
664 if n >= 0:
665 if network + n > broadcast:
666 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000667 return self._address_class(network + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000668 else:
669 n += 1
670 if broadcast + n < network:
671 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000672 return self._address_class(broadcast + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000673
674 def __lt__(self, other):
675 if self._version != other._version:
676 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000677 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000678 if not isinstance(other, _BaseNetwork):
679 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000680 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000681 if self.network_address != other.network_address:
682 return self.network_address < other.network_address
683 if self.netmask != other.netmask:
684 return self.netmask < other.netmask
685 return False
686
Nick Coghlandc9b2552012-05-20 21:01:57 +1000687 def __eq__(self, other):
Nick Coghlan9a9c28c2012-07-07 23:05:59 +1000688 try:
689 return (self._version == other._version and
690 self.network_address == other.network_address and
691 int(self.netmask) == int(other.netmask))
692 except AttributeError:
693 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000694
Nick Coghlandc9b2552012-05-20 21:01:57 +1000695 def __hash__(self):
696 return hash(int(self.network_address) ^ int(self.netmask))
697
698 def __contains__(self, other):
699 # always false if one is v4 and the other is v6.
700 if self._version != other._version:
701 return False
702 # dealing with another network.
703 if isinstance(other, _BaseNetwork):
704 return False
705 # dealing with another address
706 else:
707 # address
708 return (int(self.network_address) <= int(other._ip) <=
709 int(self.broadcast_address))
710
711 def overlaps(self, other):
712 """Tell if self is partly contained in other."""
713 return self.network_address in other or (
714 self.broadcast_address in other or (
715 other.network_address in self or (
716 other.broadcast_address in self)))
717
718 @property
719 def broadcast_address(self):
720 x = self._cache.get('broadcast_address')
721 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000722 x = self._address_class(int(self.network_address) |
723 int(self.hostmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000724 self._cache['broadcast_address'] = x
725 return x
726
727 @property
728 def hostmask(self):
729 x = self._cache.get('hostmask')
730 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000731 x = self._address_class(int(self.netmask) ^ self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000732 self._cache['hostmask'] = x
733 return x
734
735 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000736 def with_prefixlen(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000737 return '%s/%d' % (self.network_address, self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000738
739 @property
740 def with_netmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000741 return '%s/%s' % (self.network_address, self.netmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000742
743 @property
744 def with_hostmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000745 return '%s/%s' % (self.network_address, self.hostmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000746
747 @property
748 def num_addresses(self):
749 """Number of hosts in the current subnet."""
750 return int(self.broadcast_address) - int(self.network_address) + 1
751
752 @property
Nick Coghlan51c30672012-05-27 00:25:58 +1000753 def _address_class(self):
Nick Coghland9722652012-06-17 16:33:00 +1000754 # Returning bare address objects (rather than interfaces) allows for
755 # more consistent behaviour across the network address, broadcast
756 # address and individual host addresses.
757 msg = '%200s has no associated address class' % (type(self),)
758 raise NotImplementedError(msg)
Nick Coghlan51c30672012-05-27 00:25:58 +1000759
760 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000761 def prefixlen(self):
762 return self._prefixlen
763
764 def address_exclude(self, other):
765 """Remove an address from a larger block.
766
767 For example:
768
769 addr1 = ip_network('192.0.2.0/28')
770 addr2 = ip_network('192.0.2.1/32')
771 addr1.address_exclude(addr2) =
772 [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
773 IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
774
775 or IPv6:
776
777 addr1 = ip_network('2001:db8::1/32')
778 addr2 = ip_network('2001:db8::1/128')
779 addr1.address_exclude(addr2) =
780 [ip_network('2001:db8::1/128'),
781 ip_network('2001:db8::2/127'),
782 ip_network('2001:db8::4/126'),
783 ip_network('2001:db8::8/125'),
784 ...
785 ip_network('2001:db8:8000::/33')]
786
787 Args:
788 other: An IPv4Network or IPv6Network object of the same type.
789
790 Returns:
Ezio Melotti3f5db392013-01-27 06:20:14 +0200791 An iterator of the IPv(4|6)Network objects which is self
Nick Coghlandc9b2552012-05-20 21:01:57 +1000792 minus other.
793
794 Raises:
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300795 TypeError: If self and other are of differing address
Nick Coghlandc9b2552012-05-20 21:01:57 +1000796 versions, or if other is not a network object.
797 ValueError: If other is not completely contained by self.
798
799 """
800 if not self._version == other._version:
801 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000802 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000803
804 if not isinstance(other, _BaseNetwork):
Nick Coghlan912238e2012-07-07 13:34:50 +1000805 raise TypeError("%s is not a network object" % other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000806
807 if not (other.network_address >= self.network_address and
808 other.broadcast_address <= self.broadcast_address):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200809 raise ValueError('%s not contained in %s' % (other, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000810 if other == self:
811 raise StopIteration
812
Nick Coghlandc9b2552012-05-20 21:01:57 +1000813 # Make sure we're comparing the network of other.
Nick Coghlan912238e2012-07-07 13:34:50 +1000814 other = other.__class__('%s/%s' % (other.network_address,
815 other.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000816
817 s1, s2 = self.subnets()
818 while s1 != other and s2 != other:
819 if (other.network_address >= s1.network_address and
820 other.broadcast_address <= s1.broadcast_address):
821 yield s2
822 s1, s2 = s1.subnets()
823 elif (other.network_address >= s2.network_address and
824 other.broadcast_address <= s2.broadcast_address):
825 yield s1
826 s1, s2 = s2.subnets()
827 else:
828 # If we got here, there's a bug somewhere.
829 raise AssertionError('Error performing exclusion: '
830 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000831 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000832 if s1 == other:
833 yield s2
834 elif s2 == other:
835 yield s1
836 else:
837 # If we got here, there's a bug somewhere.
838 raise AssertionError('Error performing exclusion: '
839 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000840 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000841
842 def compare_networks(self, other):
843 """Compare two IP objects.
844
845 This is only concerned about the comparison of the integer
846 representation of the network addresses. This means that the
847 host bits aren't considered at all in this method. If you want
848 to compare host bits, you can easily enough do a
849 'HostA._ip < HostB._ip'
850
851 Args:
852 other: An IP object.
853
854 Returns:
855 If the IP versions of self and other are the same, returns:
856
857 -1 if self < other:
858 eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
859 IPv6Network('2001:db8::1000/124') <
860 IPv6Network('2001:db8::2000/124')
861 0 if self == other
862 eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
863 IPv6Network('2001:db8::1000/124') ==
864 IPv6Network('2001:db8::1000/124')
865 1 if self > other
866 eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
867 IPv6Network('2001:db8::2000/124') >
868 IPv6Network('2001:db8::1000/124')
869
870 Raises:
871 TypeError if the IP versions are different.
872
873 """
874 # does this need to raise a ValueError?
875 if self._version != other._version:
876 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000877 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000878 # self._version == other._version below here:
879 if self.network_address < other.network_address:
880 return -1
881 if self.network_address > other.network_address:
882 return 1
883 # self.network_address == other.network_address below here:
884 if self.netmask < other.netmask:
885 return -1
886 if self.netmask > other.netmask:
887 return 1
888 return 0
889
890 def _get_networks_key(self):
891 """Network-only key function.
892
893 Returns an object that identifies this address' network and
894 netmask. This function is a suitable "key" argument for sorted()
895 and list.sort().
896
897 """
898 return (self._version, self.network_address, self.netmask)
899
900 def subnets(self, prefixlen_diff=1, new_prefix=None):
901 """The subnets which join to make the current subnet.
902
903 In the case that self contains only one IP
904 (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
905 for IPv6), yield an iterator with just ourself.
906
907 Args:
908 prefixlen_diff: An integer, the amount the prefix length
909 should be increased by. This should not be set if
910 new_prefix is also set.
911 new_prefix: The desired new prefix length. This must be a
912 larger number (smaller prefix) than the existing prefix.
913 This should not be set if prefixlen_diff is also set.
914
915 Returns:
916 An iterator of IPv(4|6) objects.
917
918 Raises:
919 ValueError: The prefixlen_diff is too small or too large.
920 OR
921 prefixlen_diff and new_prefix are both set or new_prefix
922 is a smaller number than the current prefix (smaller
923 number means a larger network)
924
925 """
926 if self._prefixlen == self._max_prefixlen:
927 yield self
928 return
929
930 if new_prefix is not None:
931 if new_prefix < self._prefixlen:
932 raise ValueError('new prefix must be longer')
933 if prefixlen_diff != 1:
934 raise ValueError('cannot set prefixlen_diff and new_prefix')
935 prefixlen_diff = new_prefix - self._prefixlen
936
937 if prefixlen_diff < 0:
938 raise ValueError('prefix length diff must be > 0')
939 new_prefixlen = self._prefixlen + prefixlen_diff
940
Nick Coghlan932346f2014-02-08 23:17:36 +1000941 if new_prefixlen > self._max_prefixlen:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000942 raise ValueError(
943 'prefix length diff %d is invalid for netblock %s' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000944 new_prefixlen, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000945
Antoine Pitrou824db302014-05-15 20:21:48 +0200946 start = int(self.network_address)
947 end = int(self.broadcast_address)
948 step = (int(self.hostmask) + 1) >> prefixlen_diff
949 for new_addr in range(start, end, step):
950 current = self.__class__((new_addr, new_prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000951 yield current
952
Nick Coghlandc9b2552012-05-20 21:01:57 +1000953 def supernet(self, prefixlen_diff=1, new_prefix=None):
954 """The supernet containing the current network.
955
956 Args:
957 prefixlen_diff: An integer, the amount the prefix length of
958 the network should be decreased by. For example, given a
959 /24 network and a prefixlen_diff of 3, a supernet with a
960 /21 netmask is returned.
961
962 Returns:
963 An IPv4 network object.
964
965 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200966 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
967 a negative prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000968 OR
969 If prefixlen_diff and new_prefix are both set or new_prefix is a
970 larger number than the current prefix (larger number means a
971 smaller network)
972
973 """
974 if self._prefixlen == 0:
975 return self
976
977 if new_prefix is not None:
978 if new_prefix > self._prefixlen:
979 raise ValueError('new prefix must be shorter')
980 if prefixlen_diff != 1:
981 raise ValueError('cannot set prefixlen_diff and new_prefix')
982 prefixlen_diff = self._prefixlen - new_prefix
983
Antoine Pitrou5fb195f2014-05-12 20:36:46 +0200984 new_prefixlen = self.prefixlen - prefixlen_diff
985 if new_prefixlen < 0:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000986 raise ValueError(
987 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
988 (self.prefixlen, prefixlen_diff))
Antoine Pitrou5fb195f2014-05-12 20:36:46 +0200989 return self.__class__((
990 int(self.network_address) & (int(self.netmask) << prefixlen_diff),
991 new_prefixlen
992 ))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000993
Nick Coghlan730f67f2012-08-05 22:02:18 +1000994 @property
995 def is_multicast(self):
996 """Test if the address is reserved for multicast use.
997
998 Returns:
999 A boolean, True if the address is a multicast address.
1000 See RFC 2373 2.7 for details.
1001
1002 """
1003 return (self.network_address.is_multicast and
1004 self.broadcast_address.is_multicast)
1005
1006 @property
1007 def is_reserved(self):
1008 """Test if the address is otherwise IETF reserved.
1009
1010 Returns:
1011 A boolean, True if the address is within one of the
1012 reserved IPv6 Network ranges.
1013
1014 """
1015 return (self.network_address.is_reserved and
1016 self.broadcast_address.is_reserved)
1017
1018 @property
1019 def is_link_local(self):
1020 """Test if the address is reserved for link-local.
1021
1022 Returns:
1023 A boolean, True if the address is reserved per RFC 4291.
1024
1025 """
1026 return (self.network_address.is_link_local and
1027 self.broadcast_address.is_link_local)
1028
1029 @property
1030 def is_private(self):
1031 """Test if this address is allocated for private networks.
1032
1033 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001034 A boolean, True if the address is reserved per
1035 iana-ipv4-special-registry or iana-ipv6-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001036
1037 """
1038 return (self.network_address.is_private and
1039 self.broadcast_address.is_private)
1040
1041 @property
Peter Moody22c31762013-10-21 13:58:06 -07001042 def is_global(self):
Peter Moodybe9c1b12013-10-22 12:36:21 -07001043 """Test if this address is allocated for public networks.
Peter Moody22c31762013-10-21 13:58:06 -07001044
1045 Returns:
1046 A boolean, True if the address is not reserved per
1047 iana-ipv4-special-registry or iana-ipv6-special-registry.
1048
1049 """
1050 return not self.is_private
1051
1052 @property
Nick Coghlan730f67f2012-08-05 22:02:18 +10001053 def is_unspecified(self):
1054 """Test if the address is unspecified.
1055
1056 Returns:
1057 A boolean, True if this is the unspecified address as defined in
1058 RFC 2373 2.5.2.
1059
1060 """
1061 return (self.network_address.is_unspecified and
1062 self.broadcast_address.is_unspecified)
1063
1064 @property
1065 def is_loopback(self):
1066 """Test if the address is a loopback address.
1067
1068 Returns:
1069 A boolean, True if the address is a loopback address as defined in
1070 RFC 2373 2.5.3.
1071
1072 """
1073 return (self.network_address.is_loopback and
1074 self.broadcast_address.is_loopback)
1075
Nick Coghlandc9b2552012-05-20 21:01:57 +10001076
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001077class _BaseV4:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001078
1079 """Base IPv4 object.
1080
1081 The following methods are used by IPv4 objects in both single IP
1082 addresses and networks.
1083
1084 """
1085
1086 # Equivalent to 255.255.255.255 or 32 bits of 1's.
1087 _ALL_ONES = (2**IPV4LENGTH) - 1
1088 _DECIMAL_DIGITS = frozenset('0123456789')
1089
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001090 # the valid octets for host and netmasks. only useful for IPv4.
Nick Coghlan7319f692012-07-07 21:43:30 +10001091 _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0))
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001092
Antoine Pitrou45aba182014-05-15 20:18:41 +02001093 _max_prefixlen = IPV4LENGTH
1094 # There are only a handful of valid v4 netmasks, so we cache them all
1095 # when constructed (see _make_netmask()).
1096 _netmask_cache = {}
1097
Nick Coghlandc9b2552012-05-20 21:01:57 +10001098 def __init__(self, address):
1099 self._version = 4
Nick Coghlandc9b2552012-05-20 21:01:57 +10001100
1101 def _explode_shorthand_ip_string(self):
1102 return str(self)
1103
Antoine Pitrou45aba182014-05-15 20:18:41 +02001104 @classmethod
1105 def _make_netmask(cls, arg):
1106 """Make a (netmask, prefix_len) tuple from the given argument.
1107
1108 Argument can be:
1109 - an integer (the prefix length)
1110 - a string representing the prefix length (e.g. "24")
1111 - a string representing the prefix netmask (e.g. "255.255.255.0")
1112 """
1113 if arg not in cls._netmask_cache:
1114 if isinstance(arg, int):
1115 prefixlen = arg
1116 else:
1117 try:
1118 # Check for a netmask in prefix length form
1119 prefixlen = cls._prefix_from_prefix_string(arg)
1120 except NetmaskValueError:
1121 # Check for a netmask or hostmask in dotted-quad form.
1122 # This may raise NetmaskValueError.
1123 prefixlen = cls._prefix_from_ip_string(arg)
1124 netmask = IPv4Address(cls._ip_int_from_prefix(prefixlen))
1125 cls._netmask_cache[arg] = netmask, prefixlen
1126 return cls._netmask_cache[arg]
1127
1128 @classmethod
1129 def _ip_int_from_string(cls, ip_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001130 """Turn the given IP string into an integer for comparison.
1131
1132 Args:
1133 ip_str: A string, the IP ip_str.
1134
1135 Returns:
1136 The IP ip_str as an integer.
1137
1138 Raises:
1139 AddressValueError: if ip_str isn't a valid IPv4 Address.
1140
1141 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001142 if not ip_str:
1143 raise AddressValueError('Address cannot be empty')
1144
Nick Coghlandc9b2552012-05-20 21:01:57 +10001145 octets = ip_str.split('.')
1146 if len(octets) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001147 raise AddressValueError("Expected 4 octets in %r" % ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001148
Nick Coghlan7319f692012-07-07 21:43:30 +10001149 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001150 return int.from_bytes(map(cls._parse_octet, octets), 'big')
Nick Coghlan7319f692012-07-07 21:43:30 +10001151 except ValueError as exc:
1152 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001153
Antoine Pitrou45aba182014-05-15 20:18:41 +02001154 @classmethod
1155 def _parse_octet(cls, octet_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001156 """Convert a decimal octet into an integer.
1157
1158 Args:
1159 octet_str: A string, the number to parse.
1160
1161 Returns:
1162 The octet as an integer.
1163
1164 Raises:
1165 ValueError: if the octet isn't strictly a decimal from [0..255].
1166
1167 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001168 if not octet_str:
1169 raise ValueError("Empty octet not permitted")
Nick Coghlandc9b2552012-05-20 21:01:57 +10001170 # Whitelist the characters, since int() allows a lot of bizarre stuff.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001171 if not cls._DECIMAL_DIGITS.issuperset(octet_str):
Nick Coghlan07c4e332012-07-08 23:06:45 +10001172 msg = "Only decimal digits permitted in %r"
1173 raise ValueError(msg % octet_str)
1174 # We do the length check second, since the invalid character error
1175 # is likely to be more informative for the user
1176 if len(octet_str) > 3:
1177 msg = "At most 3 characters permitted in %r"
1178 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001179 # Convert to integer (we know digits are legal)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001180 octet_int = int(octet_str, 10)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001181 # Any octets that look like they *might* be written in octal,
1182 # and which don't look exactly the same in both octal and
1183 # decimal are rejected as ambiguous
1184 if octet_int > 7 and octet_str[0] == '0':
Nick Coghlan07c4e332012-07-08 23:06:45 +10001185 msg = "Ambiguous (octal/decimal) value in %r not permitted"
1186 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001187 if octet_int > 255:
Nick Coghlanb582ecc2012-07-07 22:15:22 +10001188 raise ValueError("Octet %d (> 255) not permitted" % octet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001189 return octet_int
1190
Antoine Pitrou45aba182014-05-15 20:18:41 +02001191 @classmethod
1192 def _string_from_ip_int(cls, ip_int):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001193 """Turns a 32-bit integer into dotted decimal notation.
1194
1195 Args:
1196 ip_int: An integer, the IP address.
1197
1198 Returns:
1199 The IP address as a string in dotted decimal notation.
1200
1201 """
Nick Coghlan7319f692012-07-07 21:43:30 +10001202 return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001203
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001204 def _is_valid_netmask(self, netmask):
1205 """Verify that the netmask is valid.
1206
1207 Args:
1208 netmask: A string, either a prefix or dotted decimal
1209 netmask.
1210
1211 Returns:
1212 A boolean, True if the prefix represents a valid IPv4
1213 netmask.
1214
1215 """
1216 mask = netmask.split('.')
1217 if len(mask) == 4:
Nick Coghlan7319f692012-07-07 21:43:30 +10001218 try:
1219 for x in mask:
1220 if int(x) not in self._valid_mask_octets:
1221 return False
1222 except ValueError:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001223 # Found something that isn't an integer or isn't valid
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001224 return False
Nick Coghlan7319f692012-07-07 21:43:30 +10001225 for idx, y in enumerate(mask):
1226 if idx > 0 and y > mask[idx - 1]:
1227 return False
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001228 return True
1229 try:
1230 netmask = int(netmask)
1231 except ValueError:
1232 return False
1233 return 0 <= netmask <= self._max_prefixlen
1234
1235 def _is_hostmask(self, ip_str):
1236 """Test if the IP string is a hostmask (rather than a netmask).
1237
1238 Args:
1239 ip_str: A string, the potential hostmask.
1240
1241 Returns:
1242 A boolean, True if the IP string is a hostmask.
1243
1244 """
1245 bits = ip_str.split('.')
1246 try:
Nick Coghlan7319f692012-07-07 21:43:30 +10001247 parts = [x for x in map(int, bits) if x in self._valid_mask_octets]
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001248 except ValueError:
1249 return False
1250 if len(parts) != len(bits):
1251 return False
1252 if parts[0] < parts[-1]:
1253 return True
1254 return False
1255
Eric V. Smithebdaaf42014-04-14 12:58:07 -04001256 def _reverse_pointer(self):
1257 """Return the reverse DNS pointer name for the IPv4 address.
1258
1259 This implements the method described in RFC1035 3.5.
1260
1261 """
1262 reverse_octets = str(self).split('.')[::-1]
1263 return '.'.join(reverse_octets) + '.in-addr.arpa'
1264
Nick Coghlandc9b2552012-05-20 21:01:57 +10001265 @property
1266 def max_prefixlen(self):
1267 return self._max_prefixlen
1268
1269 @property
1270 def version(self):
1271 return self._version
1272
Nick Coghlandc9b2552012-05-20 21:01:57 +10001273
1274class IPv4Address(_BaseV4, _BaseAddress):
1275
1276 """Represent and manipulate single IPv4 Addresses."""
1277
1278 def __init__(self, address):
1279
1280 """
1281 Args:
1282 address: A string or integer representing the IP
1283
1284 Additionally, an integer can be passed, so
1285 IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1286 or, more generally
1287 IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1288 IPv4Address('192.0.2.1')
1289
1290 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001291 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001292
1293 """
1294 _BaseAddress.__init__(self, address)
1295 _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)
1312 self._ip = self._ip_int_from_string(addr_str)
1313
1314 @property
1315 def packed(self):
1316 """The binary representation of this address."""
1317 return v4_int_to_packed(self._ip)
1318
Nick Coghlan730f67f2012-08-05 22:02:18 +10001319 @property
1320 def is_reserved(self):
1321 """Test if the address is otherwise IETF reserved.
1322
1323 Returns:
1324 A boolean, True if the address is within the
1325 reserved IPv4 Network range.
1326
1327 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001328 return self in self._constants._reserved_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001329
1330 @property
Peter Moodybe9c1b12013-10-22 12:36:21 -07001331 @functools.lru_cache()
Nick Coghlan730f67f2012-08-05 22:02:18 +10001332 def is_private(self):
1333 """Test if this address is allocated for private networks.
1334
1335 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001336 A boolean, True if the address is reserved per
1337 iana-ipv4-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001338
1339 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001340 return any(self in net for net in self._constants._private_networks)
Nick Coghlan730f67f2012-08-05 22:02:18 +10001341
1342 @property
1343 def is_multicast(self):
1344 """Test if the address is reserved for multicast use.
1345
1346 Returns:
1347 A boolean, True if the address is multicast.
1348 See RFC 3171 for details.
1349
1350 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001351 return self in self._constants._multicast_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001352
1353 @property
1354 def is_unspecified(self):
1355 """Test if the address is unspecified.
1356
1357 Returns:
1358 A boolean, True if this is the unspecified address as defined in
1359 RFC 5735 3.
1360
1361 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001362 return self == self._constants._unspecified_address
Nick Coghlan730f67f2012-08-05 22:02:18 +10001363
1364 @property
1365 def is_loopback(self):
1366 """Test if the address is a loopback address.
1367
1368 Returns:
1369 A boolean, True if the address is a loopback per RFC 3330.
1370
1371 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001372 return self in self._constants._loopback_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001373
1374 @property
1375 def is_link_local(self):
1376 """Test if the address is reserved for link-local.
1377
1378 Returns:
1379 A boolean, True if the address is link-local per RFC 3927.
1380
1381 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001382 return self in self._constants._linklocal_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001383
Nick Coghlandc9b2552012-05-20 21:01:57 +10001384
1385class IPv4Interface(IPv4Address):
1386
Nick Coghlandc9b2552012-05-20 21:01:57 +10001387 def __init__(self, address):
1388 if isinstance(address, (bytes, int)):
1389 IPv4Address.__init__(self, address)
1390 self.network = IPv4Network(self._ip)
1391 self._prefixlen = self._max_prefixlen
1392 return
1393
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001394 if isinstance(address, tuple):
1395 IPv4Address.__init__(self, address[0])
1396 if len(address) > 1:
1397 self._prefixlen = int(address[1])
1398 else:
1399 self._prefixlen = self._max_prefixlen
1400
1401 self.network = IPv4Network(address, strict=False)
1402 self.netmask = self.network.netmask
1403 self.hostmask = self.network.hostmask
1404 return
1405
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001406 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001407 IPv4Address.__init__(self, addr[0])
1408
1409 self.network = IPv4Network(address, strict=False)
1410 self._prefixlen = self.network._prefixlen
1411
1412 self.netmask = self.network.netmask
1413 self.hostmask = self.network.hostmask
1414
Nick Coghlandc9b2552012-05-20 21:01:57 +10001415 def __str__(self):
1416 return '%s/%d' % (self._string_from_ip_int(self._ip),
1417 self.network.prefixlen)
1418
1419 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001420 address_equal = IPv4Address.__eq__(self, other)
1421 if not address_equal or address_equal is NotImplemented:
1422 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001423 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001424 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001425 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001426 # An interface with an associated network is NOT the
1427 # same as an unassociated address. That's why the hash
1428 # takes the extra info into account.
1429 return False
1430
1431 def __lt__(self, other):
1432 address_less = IPv4Address.__lt__(self, other)
1433 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001434 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001435 try:
1436 return self.network < other.network
1437 except AttributeError:
1438 # We *do* allow addresses and interfaces to be sorted. The
1439 # unassociated address is considered less than all interfaces.
1440 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001441
1442 def __hash__(self):
1443 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1444
Nick Coghlandc9b2552012-05-20 21:01:57 +10001445 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001446 def ip(self):
1447 return IPv4Address(self._ip)
1448
1449 @property
1450 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10001451 return '%s/%s' % (self._string_from_ip_int(self._ip),
1452 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001453
1454 @property
1455 def with_netmask(self):
1456 return '%s/%s' % (self._string_from_ip_int(self._ip),
1457 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001458
Nick Coghlandc9b2552012-05-20 21:01:57 +10001459 @property
1460 def with_hostmask(self):
1461 return '%s/%s' % (self._string_from_ip_int(self._ip),
1462 self.hostmask)
1463
1464
1465class IPv4Network(_BaseV4, _BaseNetwork):
1466
1467 """This class represents and manipulates 32-bit IPv4 network + addresses..
1468
1469 Attributes: [examples for IPv4Network('192.0.2.0/27')]
1470 .network_address: IPv4Address('192.0.2.0')
1471 .hostmask: IPv4Address('0.0.0.31')
1472 .broadcast_address: IPv4Address('192.0.2.32')
1473 .netmask: IPv4Address('255.255.255.224')
1474 .prefixlen: 27
1475
1476 """
Nick Coghlan51c30672012-05-27 00:25:58 +10001477 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001478 _address_class = IPv4Address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001479
Nick Coghlandc9b2552012-05-20 21:01:57 +10001480 def __init__(self, address, strict=True):
1481
1482 """Instantiate a new IPv4 network object.
1483
1484 Args:
1485 address: A string or integer representing the IP [& network].
1486 '192.0.2.0/24'
1487 '192.0.2.0/255.255.255.0'
1488 '192.0.0.2/0.0.0.255'
1489 are all functionally the same in IPv4. Similarly,
1490 '192.0.2.1'
1491 '192.0.2.1/255.255.255.255'
1492 '192.0.2.1/32'
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001493 are also functionally equivalent. That is to say, failing to
Nick Coghlandc9b2552012-05-20 21:01:57 +10001494 provide a subnetmask will create an object with a mask of /32.
1495
1496 If the mask (portion after the / in the argument) is given in
1497 dotted quad form, it is treated as a netmask if it starts with a
1498 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1499 starts with a zero field (e.g. 0.255.255.255 == /8), with the
1500 single exception of an all-zero mask which is treated as a
1501 netmask == /0. If no mask is given, a default of /32 is used.
1502
1503 Additionally, an integer can be passed, so
1504 IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1505 or, more generally
1506 IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1507 IPv4Interface('192.0.2.1')
1508
1509 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001510 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001511 NetmaskValueError: If the netmask isn't valid for
1512 an IPv4 address.
Sandro Tosib4386d32012-06-02 17:14:22 +02001513 ValueError: If strict is True and a network address is not
Nick Coghlandc9b2552012-05-20 21:01:57 +10001514 supplied.
1515
1516 """
1517
1518 _BaseV4.__init__(self, address)
1519 _BaseNetwork.__init__(self, address)
1520
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001521 # Constructing from a packed address or integer
1522 if isinstance(address, (int, bytes)):
Nick Coghlan297b1432012-07-08 17:11:04 +10001523 self.network_address = IPv4Address(address)
Antoine Pitrou45aba182014-05-15 20:18:41 +02001524 self.netmask, self._prefixlen = self._make_netmask(self._max_prefixlen)
1525 #fixme: address/network test here.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001526 return
1527
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001528 if isinstance(address, tuple):
1529 if len(address) > 1:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001530 arg = address[1]
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001531 else:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001532 # We weren't given an address[1]
1533 arg = self._max_prefixlen
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001534 self.network_address = IPv4Address(address[0])
Antoine Pitrou45aba182014-05-15 20:18:41 +02001535 self.netmask, self._prefixlen = self._make_netmask(arg)
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001536 packed = int(self.network_address)
1537 if packed & int(self.netmask) != packed:
1538 if strict:
1539 raise ValueError('%s has host bits set' % self)
1540 else:
1541 self.network_address = IPv4Address(packed &
1542 int(self.netmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001543 return
1544
1545 # Assume input argument to be string or any object representation
1546 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001547 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001548 self.network_address = IPv4Address(self._ip_int_from_string(addr[0]))
1549
Nick Coghlandc9b2552012-05-20 21:01:57 +10001550 if len(addr) == 2:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001551 arg = addr[1]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001552 else:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001553 arg = self._max_prefixlen
1554 self.netmask, self._prefixlen = self._make_netmask(arg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001555
1556 if strict:
1557 if (IPv4Address(int(self.network_address) & int(self.netmask)) !=
1558 self.network_address):
1559 raise ValueError('%s has host bits set' % self)
1560 self.network_address = IPv4Address(int(self.network_address) &
1561 int(self.netmask))
1562
1563 if self._prefixlen == (self._max_prefixlen - 1):
1564 self.hosts = self.__iter__
1565
Peter Moodye5019d52013-10-24 09:47:10 -07001566 @property
1567 @functools.lru_cache()
1568 def is_global(self):
1569 """Test if this address is allocated for public networks.
1570
1571 Returns:
1572 A boolean, True if the address is not reserved per
1573 iana-ipv4-special-registry.
1574
1575 """
1576 return (not (self.network_address in IPv4Network('100.64.0.0/10') and
1577 self.broadcast_address in IPv4Network('100.64.0.0/10')) and
1578 not self.is_private)
1579
1580
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001581class _IPv4Constants:
1582 _linklocal_network = IPv4Network('169.254.0.0/16')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001583
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001584 _loopback_network = IPv4Network('127.0.0.0/8')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001585
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001586 _multicast_network = IPv4Network('224.0.0.0/4')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001587
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001588 _private_networks = [
1589 IPv4Network('0.0.0.0/8'),
1590 IPv4Network('10.0.0.0/8'),
1591 IPv4Network('127.0.0.0/8'),
1592 IPv4Network('169.254.0.0/16'),
1593 IPv4Network('172.16.0.0/12'),
1594 IPv4Network('192.0.0.0/29'),
1595 IPv4Network('192.0.0.170/31'),
1596 IPv4Network('192.0.2.0/24'),
1597 IPv4Network('192.168.0.0/16'),
1598 IPv4Network('198.18.0.0/15'),
1599 IPv4Network('198.51.100.0/24'),
1600 IPv4Network('203.0.113.0/24'),
1601 IPv4Network('240.0.0.0/4'),
1602 IPv4Network('255.255.255.255/32'),
1603 ]
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001604
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001605 _reserved_network = IPv4Network('240.0.0.0/4')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001606
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001607 _unspecified_address = IPv4Address('0.0.0.0')
1608
1609
1610IPv4Address._constants = _IPv4Constants
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001611
Nick Coghlandc9b2552012-05-20 21:01:57 +10001612
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001613class _BaseV6:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001614
1615 """Base IPv6 object.
1616
1617 The following methods are used by IPv6 objects in both single IP
1618 addresses and networks.
1619
1620 """
1621
1622 _ALL_ONES = (2**IPV6LENGTH) - 1
1623 _HEXTET_COUNT = 8
1624 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
Antoine Pitrou45aba182014-05-15 20:18:41 +02001625 _max_prefixlen = IPV6LENGTH
1626
1627 # There are only a bunch of valid v6 netmasks, so we cache them all
1628 # when constructed (see _make_netmask()).
1629 _netmask_cache = {}
Nick Coghlandc9b2552012-05-20 21:01:57 +10001630
1631 def __init__(self, address):
1632 self._version = 6
Nick Coghlandc9b2552012-05-20 21:01:57 +10001633
Antoine Pitrou45aba182014-05-15 20:18:41 +02001634 @classmethod
1635 def _make_netmask(cls, arg):
1636 """Make a (netmask, prefix_len) tuple from the given argument.
1637
1638 Argument can be:
1639 - an integer (the prefix length)
1640 - a string representing the prefix length (e.g. "24")
1641 - a string representing the prefix netmask (e.g. "255.255.255.0")
1642 """
1643 if arg not in cls._netmask_cache:
1644 if isinstance(arg, int):
1645 prefixlen = arg
1646 else:
1647 prefixlen = cls._prefix_from_prefix_string(arg)
1648 netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen))
1649 cls._netmask_cache[arg] = netmask, prefixlen
1650 return cls._netmask_cache[arg]
1651
1652 @classmethod
1653 def _ip_int_from_string(cls, ip_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001654 """Turn an IPv6 ip_str into an integer.
1655
1656 Args:
1657 ip_str: A string, the IPv6 ip_str.
1658
1659 Returns:
1660 An int, the IPv6 address
1661
1662 Raises:
1663 AddressValueError: if ip_str isn't a valid IPv6 Address.
1664
1665 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001666 if not ip_str:
1667 raise AddressValueError('Address cannot be empty')
1668
Nick Coghlandc9b2552012-05-20 21:01:57 +10001669 parts = ip_str.split(':')
1670
1671 # An IPv6 address needs at least 2 colons (3 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001672 _min_parts = 3
1673 if len(parts) < _min_parts:
1674 msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
1675 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001676
1677 # If the address has an IPv4-style suffix, convert it to hexadecimal.
1678 if '.' in parts[-1]:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001679 try:
1680 ipv4_int = IPv4Address(parts.pop())._ip
1681 except AddressValueError as exc:
1682 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001683 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1684 parts.append('%x' % (ipv4_int & 0xFFFF))
1685
1686 # An IPv6 address can't have more than 8 colons (9 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001687 # The extra colon comes from using the "::" notation for a single
1688 # leading or trailing zero part.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001689 _max_parts = cls._HEXTET_COUNT + 1
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001690 if len(parts) > _max_parts:
1691 msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
1692 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001693
1694 # Disregarding the endpoints, find '::' with nothing in between.
1695 # This indicates that a run of zeroes has been skipped.
Nick Coghlan7319f692012-07-07 21:43:30 +10001696 skip_index = None
1697 for i in range(1, len(parts) - 1):
1698 if not parts[i]:
1699 if skip_index is not None:
1700 # Can't have more than one '::'
1701 msg = "At most one '::' permitted in %r" % ip_str
1702 raise AddressValueError(msg)
1703 skip_index = i
Nick Coghlandc9b2552012-05-20 21:01:57 +10001704
1705 # parts_hi is the number of parts to copy from above/before the '::'
1706 # parts_lo is the number of parts to copy from below/after the '::'
1707 if skip_index is not None:
1708 # If we found a '::', then check if it also covers the endpoints.
1709 parts_hi = skip_index
1710 parts_lo = len(parts) - skip_index - 1
1711 if not parts[0]:
1712 parts_hi -= 1
1713 if parts_hi:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001714 msg = "Leading ':' only permitted as part of '::' in %r"
1715 raise AddressValueError(msg % ip_str) # ^: requires ^::
Nick Coghlandc9b2552012-05-20 21:01:57 +10001716 if not parts[-1]:
1717 parts_lo -= 1
1718 if parts_lo:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001719 msg = "Trailing ':' only permitted as part of '::' in %r"
1720 raise AddressValueError(msg % ip_str) # :$ requires ::$
Antoine Pitrou45aba182014-05-15 20:18:41 +02001721 parts_skipped = cls._HEXTET_COUNT - (parts_hi + parts_lo)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001722 if parts_skipped < 1:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001723 msg = "Expected at most %d other parts with '::' in %r"
Antoine Pitrou45aba182014-05-15 20:18:41 +02001724 raise AddressValueError(msg % (cls._HEXTET_COUNT-1, ip_str))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001725 else:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001726 # Otherwise, allocate the entire address to parts_hi. The
1727 # endpoints could still be empty, but _parse_hextet() will check
1728 # for that.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001729 if len(parts) != cls._HEXTET_COUNT:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001730 msg = "Exactly %d parts expected without '::' in %r"
Antoine Pitrou45aba182014-05-15 20:18:41 +02001731 raise AddressValueError(msg % (cls._HEXTET_COUNT, ip_str))
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001732 if not parts[0]:
1733 msg = "Leading ':' only permitted as part of '::' in %r"
1734 raise AddressValueError(msg % ip_str) # ^: requires ^::
1735 if not parts[-1]:
1736 msg = "Trailing ':' only permitted as part of '::' in %r"
1737 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001738 parts_hi = len(parts)
1739 parts_lo = 0
1740 parts_skipped = 0
1741
1742 try:
1743 # Now, parse the hextets into a 128-bit integer.
1744 ip_int = 0
1745 for i in range(parts_hi):
1746 ip_int <<= 16
Antoine Pitrou45aba182014-05-15 20:18:41 +02001747 ip_int |= cls._parse_hextet(parts[i])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001748 ip_int <<= 16 * parts_skipped
1749 for i in range(-parts_lo, 0):
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 return ip_int
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001753 except ValueError as exc:
1754 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001755
Antoine Pitrou45aba182014-05-15 20:18:41 +02001756 @classmethod
1757 def _parse_hextet(cls, hextet_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001758 """Convert an IPv6 hextet string into an integer.
1759
1760 Args:
1761 hextet_str: A string, the number to parse.
1762
1763 Returns:
1764 The hextet as an integer.
1765
1766 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001767 ValueError: if the input isn't strictly a hex number from
1768 [0..FFFF].
Nick Coghlandc9b2552012-05-20 21:01:57 +10001769
1770 """
1771 # Whitelist the characters, since int() allows a lot of bizarre stuff.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001772 if not cls._HEX_DIGITS.issuperset(hextet_str):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001773 raise ValueError("Only hex digits permitted in %r" % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001774 # We do the length check second, since the invalid character error
1775 # is likely to be more informative for the user
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001776 if len(hextet_str) > 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001777 msg = "At most 4 characters permitted in %r"
1778 raise ValueError(msg % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001779 # Length check means we can skip checking the integer value
1780 return int(hextet_str, 16)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001781
Antoine Pitrou45aba182014-05-15 20:18:41 +02001782 @classmethod
1783 def _compress_hextets(cls, hextets):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001784 """Compresses a list of hextets.
1785
1786 Compresses a list of strings, replacing the longest continuous
1787 sequence of "0" in the list with "" and adding empty strings at
1788 the beginning or at the end of the string such that subsequently
1789 calling ":".join(hextets) will produce the compressed version of
1790 the IPv6 address.
1791
1792 Args:
1793 hextets: A list of strings, the hextets to compress.
1794
1795 Returns:
1796 A list of strings.
1797
1798 """
1799 best_doublecolon_start = -1
1800 best_doublecolon_len = 0
1801 doublecolon_start = -1
1802 doublecolon_len = 0
Nick Coghlandb7920b2012-08-20 10:19:12 +10001803 for index, hextet in enumerate(hextets):
1804 if hextet == '0':
Nick Coghlandc9b2552012-05-20 21:01:57 +10001805 doublecolon_len += 1
1806 if doublecolon_start == -1:
1807 # Start of a sequence of zeros.
1808 doublecolon_start = index
1809 if doublecolon_len > best_doublecolon_len:
1810 # This is the longest sequence of zeros so far.
1811 best_doublecolon_len = doublecolon_len
1812 best_doublecolon_start = doublecolon_start
1813 else:
1814 doublecolon_len = 0
1815 doublecolon_start = -1
1816
1817 if best_doublecolon_len > 1:
1818 best_doublecolon_end = (best_doublecolon_start +
1819 best_doublecolon_len)
1820 # For zeros at the end of the address.
1821 if best_doublecolon_end == len(hextets):
1822 hextets += ['']
1823 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1824 # For zeros at the beginning of the address.
1825 if best_doublecolon_start == 0:
1826 hextets = [''] + hextets
1827
1828 return hextets
1829
Antoine Pitrou45aba182014-05-15 20:18:41 +02001830 @classmethod
1831 def _string_from_ip_int(cls, ip_int=None):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001832 """Turns a 128-bit integer into hexadecimal notation.
1833
1834 Args:
1835 ip_int: An integer, the IP address.
1836
1837 Returns:
1838 A string, the hexadecimal representation of the address.
1839
1840 Raises:
1841 ValueError: The address is bigger than 128 bits of all ones.
1842
1843 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001844 if ip_int is None:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001845 ip_int = int(cls._ip)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001846
Antoine Pitrou45aba182014-05-15 20:18:41 +02001847 if ip_int > cls._ALL_ONES:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001848 raise ValueError('IPv6 address is too large')
1849
1850 hex_str = '%032x' % ip_int
Nick Coghlan7319f692012-07-07 21:43:30 +10001851 hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001852
Antoine Pitrou45aba182014-05-15 20:18:41 +02001853 hextets = cls._compress_hextets(hextets)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001854 return ':'.join(hextets)
1855
1856 def _explode_shorthand_ip_string(self):
1857 """Expand a shortened IPv6 address.
1858
1859 Args:
1860 ip_str: A string, the IPv6 address.
1861
1862 Returns:
1863 A string, the expanded IPv6 address.
1864
1865 """
1866 if isinstance(self, IPv6Network):
1867 ip_str = str(self.network_address)
1868 elif isinstance(self, IPv6Interface):
1869 ip_str = str(self.ip)
1870 else:
1871 ip_str = str(self)
1872
1873 ip_int = self._ip_int_from_string(ip_str)
Nick Coghlan7319f692012-07-07 21:43:30 +10001874 hex_str = '%032x' % ip_int
1875 parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001876 if isinstance(self, (_BaseNetwork, IPv6Interface)):
Nick Coghlane3ded952012-08-05 22:45:22 +10001877 return '%s/%d' % (':'.join(parts), self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001878 return ':'.join(parts)
1879
Eric V. Smithebdaaf42014-04-14 12:58:07 -04001880 def _reverse_pointer(self):
1881 """Return the reverse DNS pointer name for the IPv6 address.
1882
1883 This implements the method described in RFC3596 2.5.
1884
1885 """
1886 reverse_chars = self.exploded[::-1].replace(':', '')
1887 return '.'.join(reverse_chars) + '.ip6.arpa'
1888
Nick Coghlandc9b2552012-05-20 21:01:57 +10001889 @property
1890 def max_prefixlen(self):
1891 return self._max_prefixlen
1892
1893 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001894 def version(self):
1895 return self._version
1896
Nick Coghlandc9b2552012-05-20 21:01:57 +10001897
1898class IPv6Address(_BaseV6, _BaseAddress):
1899
Sandro Tosib95c6342012-05-23 23:17:22 +02001900 """Represent and manipulate single IPv6 Addresses."""
Nick Coghlandc9b2552012-05-20 21:01:57 +10001901
1902 def __init__(self, address):
1903 """Instantiate a new IPv6 address object.
1904
1905 Args:
1906 address: A string or integer representing the IP
1907
1908 Additionally, an integer can be passed, so
1909 IPv6Address('2001:db8::') ==
1910 IPv6Address(42540766411282592856903984951653826560)
1911 or, more generally
1912 IPv6Address(int(IPv6Address('2001:db8::'))) ==
1913 IPv6Address('2001:db8::')
1914
1915 Raises:
1916 AddressValueError: If address isn't a valid IPv6 address.
1917
1918 """
1919 _BaseAddress.__init__(self, address)
1920 _BaseV6.__init__(self, address)
1921
1922 # Efficient constructor from integer.
1923 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001924 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001925 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001926 return
1927
1928 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001929 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001930 self._check_packed_address(address, 16)
Nick Coghlandb7920b2012-08-20 10:19:12 +10001931 self._ip = int.from_bytes(address, 'big')
Nick Coghlandc9b2552012-05-20 21:01:57 +10001932 return
1933
1934 # Assume input argument to be string or any object representation
1935 # which converts into a formatted IP string.
1936 addr_str = str(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001937 self._ip = self._ip_int_from_string(addr_str)
1938
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001939 @property
1940 def packed(self):
1941 """The binary representation of this address."""
1942 return v6_int_to_packed(self._ip)
1943
Nick Coghlan730f67f2012-08-05 22:02:18 +10001944 @property
1945 def is_multicast(self):
1946 """Test if the address is reserved for multicast use.
1947
1948 Returns:
1949 A boolean, True if the address is a multicast address.
1950 See RFC 2373 2.7 for details.
1951
1952 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001953 return self in self._constants._multicast_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001954
1955 @property
1956 def is_reserved(self):
1957 """Test if the address is otherwise IETF reserved.
1958
1959 Returns:
1960 A boolean, True if the address is within one of the
1961 reserved IPv6 Network ranges.
1962
1963 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001964 return any(self in x for x in self._constants._reserved_networks)
Nick Coghlan730f67f2012-08-05 22:02:18 +10001965
1966 @property
1967 def is_link_local(self):
1968 """Test if the address is reserved for link-local.
1969
1970 Returns:
1971 A boolean, True if the address is reserved per RFC 4291.
1972
1973 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001974 return self in self._constants._linklocal_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001975
1976 @property
1977 def is_site_local(self):
1978 """Test if the address is reserved for site-local.
1979
1980 Note that the site-local address space has been deprecated by RFC 3879.
1981 Use is_private to test if this address is in the space of unique local
1982 addresses as defined by RFC 4193.
1983
1984 Returns:
1985 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1986
1987 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001988 return self in self._constants._sitelocal_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001989
1990 @property
Peter Moodybe9c1b12013-10-22 12:36:21 -07001991 @functools.lru_cache()
Nick Coghlan730f67f2012-08-05 22:02:18 +10001992 def is_private(self):
1993 """Test if this address is allocated for private networks.
1994
1995 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001996 A boolean, True if the address is reserved per
1997 iana-ipv6-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001998
1999 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002000 return any(self in net for net in self._constants._private_networks)
Peter Moody22c31762013-10-21 13:58:06 -07002001
2002 @property
2003 def is_global(self):
2004 """Test if this address is allocated for public networks.
2005
2006 Returns:
2007 A boolean, true if the address is not reserved per
2008 iana-ipv6-special-registry.
2009
2010 """
2011 return not self.is_private
Nick Coghlan730f67f2012-08-05 22:02:18 +10002012
2013 @property
2014 def is_unspecified(self):
2015 """Test if the address is unspecified.
2016
2017 Returns:
2018 A boolean, True if this is the unspecified address as defined in
2019 RFC 2373 2.5.2.
2020
2021 """
2022 return self._ip == 0
2023
2024 @property
2025 def is_loopback(self):
2026 """Test if the address is a loopback address.
2027
2028 Returns:
2029 A boolean, True if the address is a loopback address as defined in
2030 RFC 2373 2.5.3.
2031
2032 """
2033 return self._ip == 1
2034
2035 @property
2036 def ipv4_mapped(self):
2037 """Return the IPv4 mapped address.
2038
2039 Returns:
2040 If the IPv6 address is a v4 mapped address, return the
2041 IPv4 mapped address. Return None otherwise.
2042
2043 """
2044 if (self._ip >> 32) != 0xFFFF:
2045 return None
2046 return IPv4Address(self._ip & 0xFFFFFFFF)
2047
2048 @property
2049 def teredo(self):
2050 """Tuple of embedded teredo IPs.
2051
2052 Returns:
2053 Tuple of the (server, client) IPs or None if the address
2054 doesn't appear to be a teredo address (doesn't start with
2055 2001::/32)
2056
2057 """
2058 if (self._ip >> 96) != 0x20010000:
2059 return None
2060 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
2061 IPv4Address(~self._ip & 0xFFFFFFFF))
2062
2063 @property
2064 def sixtofour(self):
2065 """Return the IPv4 6to4 embedded address.
2066
2067 Returns:
2068 The IPv4 6to4-embedded address if present or None if the
2069 address doesn't appear to contain a 6to4 embedded address.
2070
2071 """
2072 if (self._ip >> 112) != 0x2002:
2073 return None
2074 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
2075
Nick Coghlandc9b2552012-05-20 21:01:57 +10002076
2077class IPv6Interface(IPv6Address):
2078
2079 def __init__(self, address):
2080 if isinstance(address, (bytes, int)):
2081 IPv6Address.__init__(self, address)
2082 self.network = IPv6Network(self._ip)
2083 self._prefixlen = self._max_prefixlen
2084 return
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002085 if isinstance(address, tuple):
2086 IPv6Address.__init__(self, address[0])
2087 if len(address) > 1:
2088 self._prefixlen = int(address[1])
2089 else:
2090 self._prefixlen = self._max_prefixlen
2091 self.network = IPv6Network(address, strict=False)
2092 self.netmask = self.network.netmask
2093 self.hostmask = self.network.hostmask
2094 return
Nick Coghlandc9b2552012-05-20 21:01:57 +10002095
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002096 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002097 IPv6Address.__init__(self, addr[0])
2098 self.network = IPv6Network(address, strict=False)
2099 self.netmask = self.network.netmask
2100 self._prefixlen = self.network._prefixlen
2101 self.hostmask = self.network.hostmask
2102
Nick Coghlandc9b2552012-05-20 21:01:57 +10002103 def __str__(self):
2104 return '%s/%d' % (self._string_from_ip_int(self._ip),
2105 self.network.prefixlen)
2106
2107 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10002108 address_equal = IPv6Address.__eq__(self, other)
2109 if not address_equal or address_equal is NotImplemented:
2110 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10002111 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10002112 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10002113 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10002114 # An interface with an associated network is NOT the
2115 # same as an unassociated address. That's why the hash
2116 # takes the extra info into account.
2117 return False
2118
2119 def __lt__(self, other):
2120 address_less = IPv6Address.__lt__(self, other)
2121 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10002122 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10002123 try:
2124 return self.network < other.network
2125 except AttributeError:
2126 # We *do* allow addresses and interfaces to be sorted. The
2127 # unassociated address is considered less than all interfaces.
2128 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10002129
2130 def __hash__(self):
2131 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
2132
2133 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10002134 def ip(self):
2135 return IPv6Address(self._ip)
2136
2137 @property
2138 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10002139 return '%s/%s' % (self._string_from_ip_int(self._ip),
2140 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002141
2142 @property
2143 def with_netmask(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10002144 return '%s/%s' % (self._string_from_ip_int(self._ip),
2145 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02002146
Nick Coghlandc9b2552012-05-20 21:01:57 +10002147 @property
2148 def with_hostmask(self):
2149 return '%s/%s' % (self._string_from_ip_int(self._ip),
2150 self.hostmask)
2151
Nick Coghlan730f67f2012-08-05 22:02:18 +10002152 @property
2153 def is_unspecified(self):
2154 return self._ip == 0 and self.network.is_unspecified
2155
2156 @property
2157 def is_loopback(self):
2158 return self._ip == 1 and self.network.is_loopback
2159
Nick Coghlandc9b2552012-05-20 21:01:57 +10002160
2161class IPv6Network(_BaseV6, _BaseNetwork):
2162
2163 """This class represents and manipulates 128-bit IPv6 networks.
2164
2165 Attributes: [examples for IPv6('2001:db8::1000/124')]
2166 .network_address: IPv6Address('2001:db8::1000')
2167 .hostmask: IPv6Address('::f')
2168 .broadcast_address: IPv6Address('2001:db8::100f')
2169 .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
2170 .prefixlen: 124
2171
2172 """
2173
Nick Coghlan51c30672012-05-27 00:25:58 +10002174 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10002175 _address_class = IPv6Address
2176
Nick Coghlandc9b2552012-05-20 21:01:57 +10002177 def __init__(self, address, strict=True):
2178 """Instantiate a new IPv6 Network object.
2179
2180 Args:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02002181 address: A string or integer representing the IPv6 network or the
2182 IP and prefix/netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +10002183 '2001:db8::/128'
2184 '2001:db8:0000:0000:0000:0000:0000:0000/128'
2185 '2001:db8::'
2186 are all functionally the same in IPv6. That is to say,
2187 failing to provide a subnetmask will create an object with
2188 a mask of /128.
2189
2190 Additionally, an integer can be passed, so
2191 IPv6Network('2001:db8::') ==
2192 IPv6Network(42540766411282592856903984951653826560)
2193 or, more generally
2194 IPv6Network(int(IPv6Network('2001:db8::'))) ==
2195 IPv6Network('2001:db8::')
2196
2197 strict: A boolean. If true, ensure that we have been passed
2198 A true network address, eg, 2001:db8::1000/124 and not an
2199 IP address on a network, eg, 2001:db8::1/124.
2200
2201 Raises:
2202 AddressValueError: If address isn't a valid IPv6 address.
2203 NetmaskValueError: If the netmask isn't valid for
2204 an IPv6 address.
2205 ValueError: If strict was True and a network address was not
2206 supplied.
2207
2208 """
2209 _BaseV6.__init__(self, address)
2210 _BaseNetwork.__init__(self, address)
2211
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002212 # Efficient constructor from integer or packed address
2213 if isinstance(address, (bytes, int)):
Nick Coghlandc9b2552012-05-20 21:01:57 +10002214 self.network_address = IPv6Address(address)
Antoine Pitrou45aba182014-05-15 20:18:41 +02002215 self.netmask, self._prefixlen = self._make_netmask(self._max_prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002216 return
2217
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002218 if isinstance(address, tuple):
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002219 if len(address) > 1:
Antoine Pitrou45aba182014-05-15 20:18:41 +02002220 arg = address[1]
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002221 else:
Antoine Pitrou45aba182014-05-15 20:18:41 +02002222 arg = self._max_prefixlen
2223 self.netmask, self._prefixlen = self._make_netmask(arg)
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002224 self.network_address = IPv6Address(address[0])
2225 packed = int(self.network_address)
2226 if packed & int(self.netmask) != packed:
2227 if strict:
2228 raise ValueError('%s has host bits set' % self)
2229 else:
2230 self.network_address = IPv6Address(packed &
2231 int(self.netmask))
Hynek Schlawacked36b2e2012-06-08 15:21:21 +02002232 return
Nick Coghlandc9b2552012-05-20 21:01:57 +10002233
2234 # Assume input argument to be string or any object representation
2235 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002236 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002237
2238 self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))
2239
2240 if len(addr) == 2:
Antoine Pitrou45aba182014-05-15 20:18:41 +02002241 arg = addr[1]
Nick Coghlandc9b2552012-05-20 21:01:57 +10002242 else:
Antoine Pitrou45aba182014-05-15 20:18:41 +02002243 arg = self._max_prefixlen
2244 self.netmask, self._prefixlen = self._make_netmask(arg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002245
Nick Coghlandc9b2552012-05-20 21:01:57 +10002246 if strict:
2247 if (IPv6Address(int(self.network_address) & int(self.netmask)) !=
2248 self.network_address):
Nick Coghlan912238e2012-07-07 13:34:50 +10002249 raise ValueError('%s has host bits set' % self)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002250 self.network_address = IPv6Address(int(self.network_address) &
2251 int(self.netmask))
2252
2253 if self._prefixlen == (self._max_prefixlen - 1):
2254 self.hosts = self.__iter__
2255
Peter Moody1243c7d2014-03-11 09:55:46 -07002256 def hosts(self):
2257 """Generate Iterator over usable hosts in a network.
2258
2259 This is like __iter__ except it doesn't return the
2260 Subnet-Router anycast address.
2261
2262 """
2263 network = int(self.network_address)
2264 broadcast = int(self.broadcast_address)
2265 for x in range(network + 1, broadcast + 1):
2266 yield self._address_class(x)
2267
Nick Coghlan730f67f2012-08-05 22:02:18 +10002268 @property
2269 def is_site_local(self):
2270 """Test if the address is reserved for site-local.
2271
2272 Note that the site-local address space has been deprecated by RFC 3879.
2273 Use is_private to test if this address is in the space of unique local
2274 addresses as defined by RFC 4193.
2275
2276 Returns:
2277 A boolean, True if the address is reserved per RFC 3513 2.5.6.
2278
2279 """
2280 return (self.network_address.is_site_local and
2281 self.broadcast_address.is_site_local)
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002282
2283
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002284class _IPv6Constants:
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002285
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002286 _linklocal_network = IPv6Network('fe80::/10')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002287
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002288 _multicast_network = IPv6Network('ff00::/8')
2289
2290 _private_networks = [
2291 IPv6Network('::1/128'),
2292 IPv6Network('::/128'),
2293 IPv6Network('::ffff:0:0/96'),
2294 IPv6Network('100::/64'),
2295 IPv6Network('2001::/23'),
2296 IPv6Network('2001:2::/48'),
2297 IPv6Network('2001:db8::/32'),
2298 IPv6Network('2001:10::/28'),
2299 IPv6Network('fc00::/7'),
2300 IPv6Network('fe80::/10'),
2301 ]
2302
2303 _reserved_networks = [
2304 IPv6Network('::/8'), IPv6Network('100::/8'),
2305 IPv6Network('200::/7'), IPv6Network('400::/6'),
2306 IPv6Network('800::/5'), IPv6Network('1000::/4'),
2307 IPv6Network('4000::/3'), IPv6Network('6000::/3'),
2308 IPv6Network('8000::/3'), IPv6Network('A000::/3'),
2309 IPv6Network('C000::/3'), IPv6Network('E000::/4'),
2310 IPv6Network('F000::/5'), IPv6Network('F800::/6'),
2311 IPv6Network('FE00::/9'),
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002312 ]
2313
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002314 _sitelocal_network = IPv6Network('fec0::/10')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002315
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002316
2317IPv6Address._constants = _IPv6Constants