Mercurial > repos > guerler > springsuite
comparison planemo/lib/python3.7/site-packages/pip/_vendor/ipaddress.py @ 1:56ad4e20f292 draft
"planemo upload commit 6eee67778febed82ddd413c3ca40b3183a3898f1"
author | guerler |
---|---|
date | Fri, 31 Jul 2020 00:32:28 -0400 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
0:d30785e31577 | 1:56ad4e20f292 |
---|---|
1 # Copyright 2007 Google Inc. | |
2 # Licensed to PSF under a Contributor Agreement. | |
3 | |
4 """A fast, lightweight IPv4/IPv6 manipulation library in Python. | |
5 | |
6 This library is used to create/poke/manipulate IPv4 and IPv6 addresses | |
7 and networks. | |
8 | |
9 """ | |
10 | |
11 from __future__ import unicode_literals | |
12 | |
13 | |
14 import itertools | |
15 import struct | |
16 | |
17 __version__ = '1.0.22' | |
18 | |
19 # Compatibility functions | |
20 _compat_int_types = (int,) | |
21 try: | |
22 _compat_int_types = (int, long) | |
23 except NameError: | |
24 pass | |
25 try: | |
26 _compat_str = unicode | |
27 except NameError: | |
28 _compat_str = str | |
29 assert bytes != str | |
30 if b'\0'[0] == 0: # Python 3 semantics | |
31 def _compat_bytes_to_byte_vals(byt): | |
32 return byt | |
33 else: | |
34 def _compat_bytes_to_byte_vals(byt): | |
35 return [struct.unpack(b'!B', b)[0] for b in byt] | |
36 try: | |
37 _compat_int_from_byte_vals = int.from_bytes | |
38 except AttributeError: | |
39 def _compat_int_from_byte_vals(bytvals, endianess): | |
40 assert endianess == 'big' | |
41 res = 0 | |
42 for bv in bytvals: | |
43 assert isinstance(bv, _compat_int_types) | |
44 res = (res << 8) + bv | |
45 return res | |
46 | |
47 | |
48 def _compat_to_bytes(intval, length, endianess): | |
49 assert isinstance(intval, _compat_int_types) | |
50 assert endianess == 'big' | |
51 if length == 4: | |
52 if intval < 0 or intval >= 2 ** 32: | |
53 raise struct.error("integer out of range for 'I' format code") | |
54 return struct.pack(b'!I', intval) | |
55 elif length == 16: | |
56 if intval < 0 or intval >= 2 ** 128: | |
57 raise struct.error("integer out of range for 'QQ' format code") | |
58 return struct.pack(b'!QQ', intval >> 64, intval & 0xffffffffffffffff) | |
59 else: | |
60 raise NotImplementedError() | |
61 | |
62 | |
63 if hasattr(int, 'bit_length'): | |
64 # Not int.bit_length , since that won't work in 2.7 where long exists | |
65 def _compat_bit_length(i): | |
66 return i.bit_length() | |
67 else: | |
68 def _compat_bit_length(i): | |
69 for res in itertools.count(): | |
70 if i >> res == 0: | |
71 return res | |
72 | |
73 | |
74 def _compat_range(start, end, step=1): | |
75 assert step > 0 | |
76 i = start | |
77 while i < end: | |
78 yield i | |
79 i += step | |
80 | |
81 | |
82 class _TotalOrderingMixin(object): | |
83 __slots__ = () | |
84 | |
85 # Helper that derives the other comparison operations from | |
86 # __lt__ and __eq__ | |
87 # We avoid functools.total_ordering because it doesn't handle | |
88 # NotImplemented correctly yet (http://bugs.python.org/issue10042) | |
89 def __eq__(self, other): | |
90 raise NotImplementedError | |
91 | |
92 def __ne__(self, other): | |
93 equal = self.__eq__(other) | |
94 if equal is NotImplemented: | |
95 return NotImplemented | |
96 return not equal | |
97 | |
98 def __lt__(self, other): | |
99 raise NotImplementedError | |
100 | |
101 def __le__(self, other): | |
102 less = self.__lt__(other) | |
103 if less is NotImplemented or not less: | |
104 return self.__eq__(other) | |
105 return less | |
106 | |
107 def __gt__(self, other): | |
108 less = self.__lt__(other) | |
109 if less is NotImplemented: | |
110 return NotImplemented | |
111 equal = self.__eq__(other) | |
112 if equal is NotImplemented: | |
113 return NotImplemented | |
114 return not (less or equal) | |
115 | |
116 def __ge__(self, other): | |
117 less = self.__lt__(other) | |
118 if less is NotImplemented: | |
119 return NotImplemented | |
120 return not less | |
121 | |
122 | |
123 IPV4LENGTH = 32 | |
124 IPV6LENGTH = 128 | |
125 | |
126 | |
127 class AddressValueError(ValueError): | |
128 """A Value Error related to the address.""" | |
129 | |
130 | |
131 class NetmaskValueError(ValueError): | |
132 """A Value Error related to the netmask.""" | |
133 | |
134 | |
135 def ip_address(address): | |
136 """Take an IP string/int and return an object of the correct type. | |
137 | |
138 Args: | |
139 address: A string or integer, the IP address. Either IPv4 or | |
140 IPv6 addresses may be supplied; integers less than 2**32 will | |
141 be considered to be IPv4 by default. | |
142 | |
143 Returns: | |
144 An IPv4Address or IPv6Address object. | |
145 | |
146 Raises: | |
147 ValueError: if the *address* passed isn't either a v4 or a v6 | |
148 address | |
149 | |
150 """ | |
151 try: | |
152 return IPv4Address(address) | |
153 except (AddressValueError, NetmaskValueError): | |
154 pass | |
155 | |
156 try: | |
157 return IPv6Address(address) | |
158 except (AddressValueError, NetmaskValueError): | |
159 pass | |
160 | |
161 if isinstance(address, bytes): | |
162 raise AddressValueError( | |
163 '%r does not appear to be an IPv4 or IPv6 address. ' | |
164 'Did you pass in a bytes (str in Python 2) instead of' | |
165 ' a unicode object?' % address) | |
166 | |
167 raise ValueError('%r does not appear to be an IPv4 or IPv6 address' % | |
168 address) | |
169 | |
170 | |
171 def ip_network(address, strict=True): | |
172 """Take an IP string/int and return an object of the correct type. | |
173 | |
174 Args: | |
175 address: A string or integer, the IP network. Either IPv4 or | |
176 IPv6 networks may be supplied; integers less than 2**32 will | |
177 be considered to be IPv4 by default. | |
178 | |
179 Returns: | |
180 An IPv4Network or IPv6Network object. | |
181 | |
182 Raises: | |
183 ValueError: if the string passed isn't either a v4 or a v6 | |
184 address. Or if the network has host bits set. | |
185 | |
186 """ | |
187 try: | |
188 return IPv4Network(address, strict) | |
189 except (AddressValueError, NetmaskValueError): | |
190 pass | |
191 | |
192 try: | |
193 return IPv6Network(address, strict) | |
194 except (AddressValueError, NetmaskValueError): | |
195 pass | |
196 | |
197 if isinstance(address, bytes): | |
198 raise AddressValueError( | |
199 '%r does not appear to be an IPv4 or IPv6 network. ' | |
200 'Did you pass in a bytes (str in Python 2) instead of' | |
201 ' a unicode object?' % address) | |
202 | |
203 raise ValueError('%r does not appear to be an IPv4 or IPv6 network' % | |
204 address) | |
205 | |
206 | |
207 def ip_interface(address): | |
208 """Take an IP string/int and return an object of the correct type. | |
209 | |
210 Args: | |
211 address: A string or integer, the IP address. Either IPv4 or | |
212 IPv6 addresses may be supplied; integers less than 2**32 will | |
213 be considered to be IPv4 by default. | |
214 | |
215 Returns: | |
216 An IPv4Interface or IPv6Interface object. | |
217 | |
218 Raises: | |
219 ValueError: if the string passed isn't either a v4 or a v6 | |
220 address. | |
221 | |
222 Notes: | |
223 The IPv?Interface classes describe an Address on a particular | |
224 Network, so they're basically a combination of both the Address | |
225 and Network classes. | |
226 | |
227 """ | |
228 try: | |
229 return IPv4Interface(address) | |
230 except (AddressValueError, NetmaskValueError): | |
231 pass | |
232 | |
233 try: | |
234 return IPv6Interface(address) | |
235 except (AddressValueError, NetmaskValueError): | |
236 pass | |
237 | |
238 raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' % | |
239 address) | |
240 | |
241 | |
242 def v4_int_to_packed(address): | |
243 """Represent an address as 4 packed bytes in network (big-endian) order. | |
244 | |
245 Args: | |
246 address: An integer representation of an IPv4 IP address. | |
247 | |
248 Returns: | |
249 The integer address packed as 4 bytes in network (big-endian) order. | |
250 | |
251 Raises: | |
252 ValueError: If the integer is negative or too large to be an | |
253 IPv4 IP address. | |
254 | |
255 """ | |
256 try: | |
257 return _compat_to_bytes(address, 4, 'big') | |
258 except (struct.error, OverflowError): | |
259 raise ValueError("Address negative or too large for IPv4") | |
260 | |
261 | |
262 def v6_int_to_packed(address): | |
263 """Represent an address as 16 packed bytes in network (big-endian) order. | |
264 | |
265 Args: | |
266 address: An integer representation of an IPv6 IP address. | |
267 | |
268 Returns: | |
269 The integer address packed as 16 bytes in network (big-endian) order. | |
270 | |
271 """ | |
272 try: | |
273 return _compat_to_bytes(address, 16, 'big') | |
274 except (struct.error, OverflowError): | |
275 raise ValueError("Address negative or too large for IPv6") | |
276 | |
277 | |
278 def _split_optional_netmask(address): | |
279 """Helper to split the netmask and raise AddressValueError if needed""" | |
280 addr = _compat_str(address).split('/') | |
281 if len(addr) > 2: | |
282 raise AddressValueError("Only one '/' permitted in %r" % address) | |
283 return addr | |
284 | |
285 | |
286 def _find_address_range(addresses): | |
287 """Find a sequence of sorted deduplicated IPv#Address. | |
288 | |
289 Args: | |
290 addresses: a list of IPv#Address objects. | |
291 | |
292 Yields: | |
293 A tuple containing the first and last IP addresses in the sequence. | |
294 | |
295 """ | |
296 it = iter(addresses) | |
297 first = last = next(it) | |
298 for ip in it: | |
299 if ip._ip != last._ip + 1: | |
300 yield first, last | |
301 first = ip | |
302 last = ip | |
303 yield first, last | |
304 | |
305 | |
306 def _count_righthand_zero_bits(number, bits): | |
307 """Count the number of zero bits on the right hand side. | |
308 | |
309 Args: | |
310 number: an integer. | |
311 bits: maximum number of bits to count. | |
312 | |
313 Returns: | |
314 The number of zero bits on the right hand side of the number. | |
315 | |
316 """ | |
317 if number == 0: | |
318 return bits | |
319 return min(bits, _compat_bit_length(~number & (number - 1))) | |
320 | |
321 | |
322 def summarize_address_range(first, last): | |
323 """Summarize a network range given the first and last IP addresses. | |
324 | |
325 Example: | |
326 >>> list(summarize_address_range(IPv4Address('192.0.2.0'), | |
327 ... IPv4Address('192.0.2.130'))) | |
328 ... #doctest: +NORMALIZE_WHITESPACE | |
329 [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'), | |
330 IPv4Network('192.0.2.130/32')] | |
331 | |
332 Args: | |
333 first: the first IPv4Address or IPv6Address in the range. | |
334 last: the last IPv4Address or IPv6Address in the range. | |
335 | |
336 Returns: | |
337 An iterator of the summarized IPv(4|6) network objects. | |
338 | |
339 Raise: | |
340 TypeError: | |
341 If the first and last objects are not IP addresses. | |
342 If the first and last objects are not the same version. | |
343 ValueError: | |
344 If the last object is not greater than the first. | |
345 If the version of the first address is not 4 or 6. | |
346 | |
347 """ | |
348 if (not (isinstance(first, _BaseAddress) and | |
349 isinstance(last, _BaseAddress))): | |
350 raise TypeError('first and last must be IP addresses, not networks') | |
351 if first.version != last.version: | |
352 raise TypeError("%s and %s are not of the same version" % ( | |
353 first, last)) | |
354 if first > last: | |
355 raise ValueError('last IP address must be greater than first') | |
356 | |
357 if first.version == 4: | |
358 ip = IPv4Network | |
359 elif first.version == 6: | |
360 ip = IPv6Network | |
361 else: | |
362 raise ValueError('unknown IP version') | |
363 | |
364 ip_bits = first._max_prefixlen | |
365 first_int = first._ip | |
366 last_int = last._ip | |
367 while first_int <= last_int: | |
368 nbits = min(_count_righthand_zero_bits(first_int, ip_bits), | |
369 _compat_bit_length(last_int - first_int + 1) - 1) | |
370 net = ip((first_int, ip_bits - nbits)) | |
371 yield net | |
372 first_int += 1 << nbits | |
373 if first_int - 1 == ip._ALL_ONES: | |
374 break | |
375 | |
376 | |
377 def _collapse_addresses_internal(addresses): | |
378 """Loops through the addresses, collapsing concurrent netblocks. | |
379 | |
380 Example: | |
381 | |
382 ip1 = IPv4Network('192.0.2.0/26') | |
383 ip2 = IPv4Network('192.0.2.64/26') | |
384 ip3 = IPv4Network('192.0.2.128/26') | |
385 ip4 = IPv4Network('192.0.2.192/26') | |
386 | |
387 _collapse_addresses_internal([ip1, ip2, ip3, ip4]) -> | |
388 [IPv4Network('192.0.2.0/24')] | |
389 | |
390 This shouldn't be called directly; it is called via | |
391 collapse_addresses([]). | |
392 | |
393 Args: | |
394 addresses: A list of IPv4Network's or IPv6Network's | |
395 | |
396 Returns: | |
397 A list of IPv4Network's or IPv6Network's depending on what we were | |
398 passed. | |
399 | |
400 """ | |
401 # First merge | |
402 to_merge = list(addresses) | |
403 subnets = {} | |
404 while to_merge: | |
405 net = to_merge.pop() | |
406 supernet = net.supernet() | |
407 existing = subnets.get(supernet) | |
408 if existing is None: | |
409 subnets[supernet] = net | |
410 elif existing != net: | |
411 # Merge consecutive subnets | |
412 del subnets[supernet] | |
413 to_merge.append(supernet) | |
414 # Then iterate over resulting networks, skipping subsumed subnets | |
415 last = None | |
416 for net in sorted(subnets.values()): | |
417 if last is not None: | |
418 # Since they are sorted, | |
419 # last.network_address <= net.network_address is a given. | |
420 if last.broadcast_address >= net.broadcast_address: | |
421 continue | |
422 yield net | |
423 last = net | |
424 | |
425 | |
426 def collapse_addresses(addresses): | |
427 """Collapse a list of IP objects. | |
428 | |
429 Example: | |
430 collapse_addresses([IPv4Network('192.0.2.0/25'), | |
431 IPv4Network('192.0.2.128/25')]) -> | |
432 [IPv4Network('192.0.2.0/24')] | |
433 | |
434 Args: | |
435 addresses: An iterator of IPv4Network or IPv6Network objects. | |
436 | |
437 Returns: | |
438 An iterator of the collapsed IPv(4|6)Network objects. | |
439 | |
440 Raises: | |
441 TypeError: If passed a list of mixed version objects. | |
442 | |
443 """ | |
444 addrs = [] | |
445 ips = [] | |
446 nets = [] | |
447 | |
448 # split IP addresses and networks | |
449 for ip in addresses: | |
450 if isinstance(ip, _BaseAddress): | |
451 if ips and ips[-1]._version != ip._version: | |
452 raise TypeError("%s and %s are not of the same version" % ( | |
453 ip, ips[-1])) | |
454 ips.append(ip) | |
455 elif ip._prefixlen == ip._max_prefixlen: | |
456 if ips and ips[-1]._version != ip._version: | |
457 raise TypeError("%s and %s are not of the same version" % ( | |
458 ip, ips[-1])) | |
459 try: | |
460 ips.append(ip.ip) | |
461 except AttributeError: | |
462 ips.append(ip.network_address) | |
463 else: | |
464 if nets and nets[-1]._version != ip._version: | |
465 raise TypeError("%s and %s are not of the same version" % ( | |
466 ip, nets[-1])) | |
467 nets.append(ip) | |
468 | |
469 # sort and dedup | |
470 ips = sorted(set(ips)) | |
471 | |
472 # find consecutive address ranges in the sorted sequence and summarize them | |
473 if ips: | |
474 for first, last in _find_address_range(ips): | |
475 addrs.extend(summarize_address_range(first, last)) | |
476 | |
477 return _collapse_addresses_internal(addrs + nets) | |
478 | |
479 | |
480 def get_mixed_type_key(obj): | |
481 """Return a key suitable for sorting between networks and addresses. | |
482 | |
483 Address and Network objects are not sortable by default; they're | |
484 fundamentally different so the expression | |
485 | |
486 IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24') | |
487 | |
488 doesn't make any sense. There are some times however, where you may wish | |
489 to have ipaddress sort these for you anyway. If you need to do this, you | |
490 can use this function as the key= argument to sorted(). | |
491 | |
492 Args: | |
493 obj: either a Network or Address object. | |
494 Returns: | |
495 appropriate key. | |
496 | |
497 """ | |
498 if isinstance(obj, _BaseNetwork): | |
499 return obj._get_networks_key() | |
500 elif isinstance(obj, _BaseAddress): | |
501 return obj._get_address_key() | |
502 return NotImplemented | |
503 | |
504 | |
505 class _IPAddressBase(_TotalOrderingMixin): | |
506 | |
507 """The mother class.""" | |
508 | |
509 __slots__ = () | |
510 | |
511 @property | |
512 def exploded(self): | |
513 """Return the longhand version of the IP address as a string.""" | |
514 return self._explode_shorthand_ip_string() | |
515 | |
516 @property | |
517 def compressed(self): | |
518 """Return the shorthand version of the IP address as a string.""" | |
519 return _compat_str(self) | |
520 | |
521 @property | |
522 def reverse_pointer(self): | |
523 """The name of the reverse DNS pointer for the IP address, e.g.: | |
524 >>> ipaddress.ip_address("127.0.0.1").reverse_pointer | |
525 '1.0.0.127.in-addr.arpa' | |
526 >>> ipaddress.ip_address("2001:db8::1").reverse_pointer | |
527 '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' | |
528 | |
529 """ | |
530 return self._reverse_pointer() | |
531 | |
532 @property | |
533 def version(self): | |
534 msg = '%200s has no version specified' % (type(self),) | |
535 raise NotImplementedError(msg) | |
536 | |
537 def _check_int_address(self, address): | |
538 if address < 0: | |
539 msg = "%d (< 0) is not permitted as an IPv%d address" | |
540 raise AddressValueError(msg % (address, self._version)) | |
541 if address > self._ALL_ONES: | |
542 msg = "%d (>= 2**%d) is not permitted as an IPv%d address" | |
543 raise AddressValueError(msg % (address, self._max_prefixlen, | |
544 self._version)) | |
545 | |
546 def _check_packed_address(self, address, expected_len): | |
547 address_len = len(address) | |
548 if address_len != expected_len: | |
549 msg = ( | |
550 '%r (len %d != %d) is not permitted as an IPv%d address. ' | |
551 'Did you pass in a bytes (str in Python 2) instead of' | |
552 ' a unicode object?') | |
553 raise AddressValueError(msg % (address, address_len, | |
554 expected_len, self._version)) | |
555 | |
556 @classmethod | |
557 def _ip_int_from_prefix(cls, prefixlen): | |
558 """Turn the prefix length into a bitwise netmask | |
559 | |
560 Args: | |
561 prefixlen: An integer, the prefix length. | |
562 | |
563 Returns: | |
564 An integer. | |
565 | |
566 """ | |
567 return cls._ALL_ONES ^ (cls._ALL_ONES >> prefixlen) | |
568 | |
569 @classmethod | |
570 def _prefix_from_ip_int(cls, ip_int): | |
571 """Return prefix length from the bitwise netmask. | |
572 | |
573 Args: | |
574 ip_int: An integer, the netmask in expanded bitwise format | |
575 | |
576 Returns: | |
577 An integer, the prefix length. | |
578 | |
579 Raises: | |
580 ValueError: If the input intermingles zeroes & ones | |
581 """ | |
582 trailing_zeroes = _count_righthand_zero_bits(ip_int, | |
583 cls._max_prefixlen) | |
584 prefixlen = cls._max_prefixlen - trailing_zeroes | |
585 leading_ones = ip_int >> trailing_zeroes | |
586 all_ones = (1 << prefixlen) - 1 | |
587 if leading_ones != all_ones: | |
588 byteslen = cls._max_prefixlen // 8 | |
589 details = _compat_to_bytes(ip_int, byteslen, 'big') | |
590 msg = 'Netmask pattern %r mixes zeroes & ones' | |
591 raise ValueError(msg % details) | |
592 return prefixlen | |
593 | |
594 @classmethod | |
595 def _report_invalid_netmask(cls, netmask_str): | |
596 msg = '%r is not a valid netmask' % netmask_str | |
597 raise NetmaskValueError(msg) | |
598 | |
599 @classmethod | |
600 def _prefix_from_prefix_string(cls, prefixlen_str): | |
601 """Return prefix length from a numeric string | |
602 | |
603 Args: | |
604 prefixlen_str: The string to be converted | |
605 | |
606 Returns: | |
607 An integer, the prefix length. | |
608 | |
609 Raises: | |
610 NetmaskValueError: If the input is not a valid netmask | |
611 """ | |
612 # int allows a leading +/- as well as surrounding whitespace, | |
613 # so we ensure that isn't the case | |
614 if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str): | |
615 cls._report_invalid_netmask(prefixlen_str) | |
616 try: | |
617 prefixlen = int(prefixlen_str) | |
618 except ValueError: | |
619 cls._report_invalid_netmask(prefixlen_str) | |
620 if not (0 <= prefixlen <= cls._max_prefixlen): | |
621 cls._report_invalid_netmask(prefixlen_str) | |
622 return prefixlen | |
623 | |
624 @classmethod | |
625 def _prefix_from_ip_string(cls, ip_str): | |
626 """Turn a netmask/hostmask string into a prefix length | |
627 | |
628 Args: | |
629 ip_str: The netmask/hostmask to be converted | |
630 | |
631 Returns: | |
632 An integer, the prefix length. | |
633 | |
634 Raises: | |
635 NetmaskValueError: If the input is not a valid netmask/hostmask | |
636 """ | |
637 # Parse the netmask/hostmask like an IP address. | |
638 try: | |
639 ip_int = cls._ip_int_from_string(ip_str) | |
640 except AddressValueError: | |
641 cls._report_invalid_netmask(ip_str) | |
642 | |
643 # Try matching a netmask (this would be /1*0*/ as a bitwise regexp). | |
644 # Note that the two ambiguous cases (all-ones and all-zeroes) are | |
645 # treated as netmasks. | |
646 try: | |
647 return cls._prefix_from_ip_int(ip_int) | |
648 except ValueError: | |
649 pass | |
650 | |
651 # Invert the bits, and try matching a /0+1+/ hostmask instead. | |
652 ip_int ^= cls._ALL_ONES | |
653 try: | |
654 return cls._prefix_from_ip_int(ip_int) | |
655 except ValueError: | |
656 cls._report_invalid_netmask(ip_str) | |
657 | |
658 def __reduce__(self): | |
659 return self.__class__, (_compat_str(self),) | |
660 | |
661 | |
662 class _BaseAddress(_IPAddressBase): | |
663 | |
664 """A generic IP object. | |
665 | |
666 This IP class contains the version independent methods which are | |
667 used by single IP addresses. | |
668 """ | |
669 | |
670 __slots__ = () | |
671 | |
672 def __int__(self): | |
673 return self._ip | |
674 | |
675 def __eq__(self, other): | |
676 try: | |
677 return (self._ip == other._ip and | |
678 self._version == other._version) | |
679 except AttributeError: | |
680 return NotImplemented | |
681 | |
682 def __lt__(self, other): | |
683 if not isinstance(other, _IPAddressBase): | |
684 return NotImplemented | |
685 if not isinstance(other, _BaseAddress): | |
686 raise TypeError('%s and %s are not of the same type' % ( | |
687 self, other)) | |
688 if self._version != other._version: | |
689 raise TypeError('%s and %s are not of the same version' % ( | |
690 self, other)) | |
691 if self._ip != other._ip: | |
692 return self._ip < other._ip | |
693 return False | |
694 | |
695 # Shorthand for Integer addition and subtraction. This is not | |
696 # meant to ever support addition/subtraction of addresses. | |
697 def __add__(self, other): | |
698 if not isinstance(other, _compat_int_types): | |
699 return NotImplemented | |
700 return self.__class__(int(self) + other) | |
701 | |
702 def __sub__(self, other): | |
703 if not isinstance(other, _compat_int_types): | |
704 return NotImplemented | |
705 return self.__class__(int(self) - other) | |
706 | |
707 def __repr__(self): | |
708 return '%s(%r)' % (self.__class__.__name__, _compat_str(self)) | |
709 | |
710 def __str__(self): | |
711 return _compat_str(self._string_from_ip_int(self._ip)) | |
712 | |
713 def __hash__(self): | |
714 return hash(hex(int(self._ip))) | |
715 | |
716 def _get_address_key(self): | |
717 return (self._version, self) | |
718 | |
719 def __reduce__(self): | |
720 return self.__class__, (self._ip,) | |
721 | |
722 | |
723 class _BaseNetwork(_IPAddressBase): | |
724 | |
725 """A generic IP network object. | |
726 | |
727 This IP class contains the version independent methods which are | |
728 used by networks. | |
729 | |
730 """ | |
731 def __init__(self, address): | |
732 self._cache = {} | |
733 | |
734 def __repr__(self): | |
735 return '%s(%r)' % (self.__class__.__name__, _compat_str(self)) | |
736 | |
737 def __str__(self): | |
738 return '%s/%d' % (self.network_address, self.prefixlen) | |
739 | |
740 def hosts(self): | |
741 """Generate Iterator over usable hosts in a network. | |
742 | |
743 This is like __iter__ except it doesn't return the network | |
744 or broadcast addresses. | |
745 | |
746 """ | |
747 network = int(self.network_address) | |
748 broadcast = int(self.broadcast_address) | |
749 for x in _compat_range(network + 1, broadcast): | |
750 yield self._address_class(x) | |
751 | |
752 def __iter__(self): | |
753 network = int(self.network_address) | |
754 broadcast = int(self.broadcast_address) | |
755 for x in _compat_range(network, broadcast + 1): | |
756 yield self._address_class(x) | |
757 | |
758 def __getitem__(self, n): | |
759 network = int(self.network_address) | |
760 broadcast = int(self.broadcast_address) | |
761 if n >= 0: | |
762 if network + n > broadcast: | |
763 raise IndexError('address out of range') | |
764 return self._address_class(network + n) | |
765 else: | |
766 n += 1 | |
767 if broadcast + n < network: | |
768 raise IndexError('address out of range') | |
769 return self._address_class(broadcast + n) | |
770 | |
771 def __lt__(self, other): | |
772 if not isinstance(other, _IPAddressBase): | |
773 return NotImplemented | |
774 if not isinstance(other, _BaseNetwork): | |
775 raise TypeError('%s and %s are not of the same type' % ( | |
776 self, other)) | |
777 if self._version != other._version: | |
778 raise TypeError('%s and %s are not of the same version' % ( | |
779 self, other)) | |
780 if self.network_address != other.network_address: | |
781 return self.network_address < other.network_address | |
782 if self.netmask != other.netmask: | |
783 return self.netmask < other.netmask | |
784 return False | |
785 | |
786 def __eq__(self, other): | |
787 try: | |
788 return (self._version == other._version and | |
789 self.network_address == other.network_address and | |
790 int(self.netmask) == int(other.netmask)) | |
791 except AttributeError: | |
792 return NotImplemented | |
793 | |
794 def __hash__(self): | |
795 return hash(int(self.network_address) ^ int(self.netmask)) | |
796 | |
797 def __contains__(self, other): | |
798 # always false if one is v4 and the other is v6. | |
799 if self._version != other._version: | |
800 return False | |
801 # dealing with another network. | |
802 if isinstance(other, _BaseNetwork): | |
803 return False | |
804 # dealing with another address | |
805 else: | |
806 # address | |
807 return (int(self.network_address) <= int(other._ip) <= | |
808 int(self.broadcast_address)) | |
809 | |
810 def overlaps(self, other): | |
811 """Tell if self is partly contained in other.""" | |
812 return self.network_address in other or ( | |
813 self.broadcast_address in other or ( | |
814 other.network_address in self or ( | |
815 other.broadcast_address in self))) | |
816 | |
817 @property | |
818 def broadcast_address(self): | |
819 x = self._cache.get('broadcast_address') | |
820 if x is None: | |
821 x = self._address_class(int(self.network_address) | | |
822 int(self.hostmask)) | |
823 self._cache['broadcast_address'] = x | |
824 return x | |
825 | |
826 @property | |
827 def hostmask(self): | |
828 x = self._cache.get('hostmask') | |
829 if x is None: | |
830 x = self._address_class(int(self.netmask) ^ self._ALL_ONES) | |
831 self._cache['hostmask'] = x | |
832 return x | |
833 | |
834 @property | |
835 def with_prefixlen(self): | |
836 return '%s/%d' % (self.network_address, self._prefixlen) | |
837 | |
838 @property | |
839 def with_netmask(self): | |
840 return '%s/%s' % (self.network_address, self.netmask) | |
841 | |
842 @property | |
843 def with_hostmask(self): | |
844 return '%s/%s' % (self.network_address, self.hostmask) | |
845 | |
846 @property | |
847 def num_addresses(self): | |
848 """Number of hosts in the current subnet.""" | |
849 return int(self.broadcast_address) - int(self.network_address) + 1 | |
850 | |
851 @property | |
852 def _address_class(self): | |
853 # Returning bare address objects (rather than interfaces) allows for | |
854 # more consistent behaviour across the network address, broadcast | |
855 # address and individual host addresses. | |
856 msg = '%200s has no associated address class' % (type(self),) | |
857 raise NotImplementedError(msg) | |
858 | |
859 @property | |
860 def prefixlen(self): | |
861 return self._prefixlen | |
862 | |
863 def address_exclude(self, other): | |
864 """Remove an address from a larger block. | |
865 | |
866 For example: | |
867 | |
868 addr1 = ip_network('192.0.2.0/28') | |
869 addr2 = ip_network('192.0.2.1/32') | |
870 list(addr1.address_exclude(addr2)) = | |
871 [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'), | |
872 IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')] | |
873 | |
874 or IPv6: | |
875 | |
876 addr1 = ip_network('2001:db8::1/32') | |
877 addr2 = ip_network('2001:db8::1/128') | |
878 list(addr1.address_exclude(addr2)) = | |
879 [ip_network('2001:db8::1/128'), | |
880 ip_network('2001:db8::2/127'), | |
881 ip_network('2001:db8::4/126'), | |
882 ip_network('2001:db8::8/125'), | |
883 ... | |
884 ip_network('2001:db8:8000::/33')] | |
885 | |
886 Args: | |
887 other: An IPv4Network or IPv6Network object of the same type. | |
888 | |
889 Returns: | |
890 An iterator of the IPv(4|6)Network objects which is self | |
891 minus other. | |
892 | |
893 Raises: | |
894 TypeError: If self and other are of differing address | |
895 versions, or if other is not a network object. | |
896 ValueError: If other is not completely contained by self. | |
897 | |
898 """ | |
899 if not self._version == other._version: | |
900 raise TypeError("%s and %s are not of the same version" % ( | |
901 self, other)) | |
902 | |
903 if not isinstance(other, _BaseNetwork): | |
904 raise TypeError("%s is not a network object" % other) | |
905 | |
906 if not other.subnet_of(self): | |
907 raise ValueError('%s not contained in %s' % (other, self)) | |
908 if other == self: | |
909 return | |
910 | |
911 # Make sure we're comparing the network of other. | |
912 other = other.__class__('%s/%s' % (other.network_address, | |
913 other.prefixlen)) | |
914 | |
915 s1, s2 = self.subnets() | |
916 while s1 != other and s2 != other: | |
917 if other.subnet_of(s1): | |
918 yield s2 | |
919 s1, s2 = s1.subnets() | |
920 elif other.subnet_of(s2): | |
921 yield s1 | |
922 s1, s2 = s2.subnets() | |
923 else: | |
924 # If we got here, there's a bug somewhere. | |
925 raise AssertionError('Error performing exclusion: ' | |
926 's1: %s s2: %s other: %s' % | |
927 (s1, s2, other)) | |
928 if s1 == other: | |
929 yield s2 | |
930 elif s2 == other: | |
931 yield s1 | |
932 else: | |
933 # If we got here, there's a bug somewhere. | |
934 raise AssertionError('Error performing exclusion: ' | |
935 's1: %s s2: %s other: %s' % | |
936 (s1, s2, other)) | |
937 | |
938 def compare_networks(self, other): | |
939 """Compare two IP objects. | |
940 | |
941 This is only concerned about the comparison of the integer | |
942 representation of the network addresses. This means that the | |
943 host bits aren't considered at all in this method. If you want | |
944 to compare host bits, you can easily enough do a | |
945 'HostA._ip < HostB._ip' | |
946 | |
947 Args: | |
948 other: An IP object. | |
949 | |
950 Returns: | |
951 If the IP versions of self and other are the same, returns: | |
952 | |
953 -1 if self < other: | |
954 eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25') | |
955 IPv6Network('2001:db8::1000/124') < | |
956 IPv6Network('2001:db8::2000/124') | |
957 0 if self == other | |
958 eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24') | |
959 IPv6Network('2001:db8::1000/124') == | |
960 IPv6Network('2001:db8::1000/124') | |
961 1 if self > other | |
962 eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25') | |
963 IPv6Network('2001:db8::2000/124') > | |
964 IPv6Network('2001:db8::1000/124') | |
965 | |
966 Raises: | |
967 TypeError if the IP versions are different. | |
968 | |
969 """ | |
970 # does this need to raise a ValueError? | |
971 if self._version != other._version: | |
972 raise TypeError('%s and %s are not of the same type' % ( | |
973 self, other)) | |
974 # self._version == other._version below here: | |
975 if self.network_address < other.network_address: | |
976 return -1 | |
977 if self.network_address > other.network_address: | |
978 return 1 | |
979 # self.network_address == other.network_address below here: | |
980 if self.netmask < other.netmask: | |
981 return -1 | |
982 if self.netmask > other.netmask: | |
983 return 1 | |
984 return 0 | |
985 | |
986 def _get_networks_key(self): | |
987 """Network-only key function. | |
988 | |
989 Returns an object that identifies this address' network and | |
990 netmask. This function is a suitable "key" argument for sorted() | |
991 and list.sort(). | |
992 | |
993 """ | |
994 return (self._version, self.network_address, self.netmask) | |
995 | |
996 def subnets(self, prefixlen_diff=1, new_prefix=None): | |
997 """The subnets which join to make the current subnet. | |
998 | |
999 In the case that self contains only one IP | |
1000 (self._prefixlen == 32 for IPv4 or self._prefixlen == 128 | |
1001 for IPv6), yield an iterator with just ourself. | |
1002 | |
1003 Args: | |
1004 prefixlen_diff: An integer, the amount the prefix length | |
1005 should be increased by. This should not be set if | |
1006 new_prefix is also set. | |
1007 new_prefix: The desired new prefix length. This must be a | |
1008 larger number (smaller prefix) than the existing prefix. | |
1009 This should not be set if prefixlen_diff is also set. | |
1010 | |
1011 Returns: | |
1012 An iterator of IPv(4|6) objects. | |
1013 | |
1014 Raises: | |
1015 ValueError: The prefixlen_diff is too small or too large. | |
1016 OR | |
1017 prefixlen_diff and new_prefix are both set or new_prefix | |
1018 is a smaller number than the current prefix (smaller | |
1019 number means a larger network) | |
1020 | |
1021 """ | |
1022 if self._prefixlen == self._max_prefixlen: | |
1023 yield self | |
1024 return | |
1025 | |
1026 if new_prefix is not None: | |
1027 if new_prefix < self._prefixlen: | |
1028 raise ValueError('new prefix must be longer') | |
1029 if prefixlen_diff != 1: | |
1030 raise ValueError('cannot set prefixlen_diff and new_prefix') | |
1031 prefixlen_diff = new_prefix - self._prefixlen | |
1032 | |
1033 if prefixlen_diff < 0: | |
1034 raise ValueError('prefix length diff must be > 0') | |
1035 new_prefixlen = self._prefixlen + prefixlen_diff | |
1036 | |
1037 if new_prefixlen > self._max_prefixlen: | |
1038 raise ValueError( | |
1039 'prefix length diff %d is invalid for netblock %s' % ( | |
1040 new_prefixlen, self)) | |
1041 | |
1042 start = int(self.network_address) | |
1043 end = int(self.broadcast_address) + 1 | |
1044 step = (int(self.hostmask) + 1) >> prefixlen_diff | |
1045 for new_addr in _compat_range(start, end, step): | |
1046 current = self.__class__((new_addr, new_prefixlen)) | |
1047 yield current | |
1048 | |
1049 def supernet(self, prefixlen_diff=1, new_prefix=None): | |
1050 """The supernet containing the current network. | |
1051 | |
1052 Args: | |
1053 prefixlen_diff: An integer, the amount the prefix length of | |
1054 the network should be decreased by. For example, given a | |
1055 /24 network and a prefixlen_diff of 3, a supernet with a | |
1056 /21 netmask is returned. | |
1057 | |
1058 Returns: | |
1059 An IPv4 network object. | |
1060 | |
1061 Raises: | |
1062 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have | |
1063 a negative prefix length. | |
1064 OR | |
1065 If prefixlen_diff and new_prefix are both set or new_prefix is a | |
1066 larger number than the current prefix (larger number means a | |
1067 smaller network) | |
1068 | |
1069 """ | |
1070 if self._prefixlen == 0: | |
1071 return self | |
1072 | |
1073 if new_prefix is not None: | |
1074 if new_prefix > self._prefixlen: | |
1075 raise ValueError('new prefix must be shorter') | |
1076 if prefixlen_diff != 1: | |
1077 raise ValueError('cannot set prefixlen_diff and new_prefix') | |
1078 prefixlen_diff = self._prefixlen - new_prefix | |
1079 | |
1080 new_prefixlen = self.prefixlen - prefixlen_diff | |
1081 if new_prefixlen < 0: | |
1082 raise ValueError( | |
1083 'current prefixlen is %d, cannot have a prefixlen_diff of %d' % | |
1084 (self.prefixlen, prefixlen_diff)) | |
1085 return self.__class__(( | |
1086 int(self.network_address) & (int(self.netmask) << prefixlen_diff), | |
1087 new_prefixlen)) | |
1088 | |
1089 @property | |
1090 def is_multicast(self): | |
1091 """Test if the address is reserved for multicast use. | |
1092 | |
1093 Returns: | |
1094 A boolean, True if the address is a multicast address. | |
1095 See RFC 2373 2.7 for details. | |
1096 | |
1097 """ | |
1098 return (self.network_address.is_multicast and | |
1099 self.broadcast_address.is_multicast) | |
1100 | |
1101 @staticmethod | |
1102 def _is_subnet_of(a, b): | |
1103 try: | |
1104 # Always false if one is v4 and the other is v6. | |
1105 if a._version != b._version: | |
1106 raise TypeError("%s and %s are not of the same version" (a, b)) | |
1107 return (b.network_address <= a.network_address and | |
1108 b.broadcast_address >= a.broadcast_address) | |
1109 except AttributeError: | |
1110 raise TypeError("Unable to test subnet containment " | |
1111 "between %s and %s" % (a, b)) | |
1112 | |
1113 def subnet_of(self, other): | |
1114 """Return True if this network is a subnet of other.""" | |
1115 return self._is_subnet_of(self, other) | |
1116 | |
1117 def supernet_of(self, other): | |
1118 """Return True if this network is a supernet of other.""" | |
1119 return self._is_subnet_of(other, self) | |
1120 | |
1121 @property | |
1122 def is_reserved(self): | |
1123 """Test if the address is otherwise IETF reserved. | |
1124 | |
1125 Returns: | |
1126 A boolean, True if the address is within one of the | |
1127 reserved IPv6 Network ranges. | |
1128 | |
1129 """ | |
1130 return (self.network_address.is_reserved and | |
1131 self.broadcast_address.is_reserved) | |
1132 | |
1133 @property | |
1134 def is_link_local(self): | |
1135 """Test if the address is reserved for link-local. | |
1136 | |
1137 Returns: | |
1138 A boolean, True if the address is reserved per RFC 4291. | |
1139 | |
1140 """ | |
1141 return (self.network_address.is_link_local and | |
1142 self.broadcast_address.is_link_local) | |
1143 | |
1144 @property | |
1145 def is_private(self): | |
1146 """Test if this address is allocated for private networks. | |
1147 | |
1148 Returns: | |
1149 A boolean, True if the address is reserved per | |
1150 iana-ipv4-special-registry or iana-ipv6-special-registry. | |
1151 | |
1152 """ | |
1153 return (self.network_address.is_private and | |
1154 self.broadcast_address.is_private) | |
1155 | |
1156 @property | |
1157 def is_global(self): | |
1158 """Test if this address is allocated for public networks. | |
1159 | |
1160 Returns: | |
1161 A boolean, True if the address is not reserved per | |
1162 iana-ipv4-special-registry or iana-ipv6-special-registry. | |
1163 | |
1164 """ | |
1165 return not self.is_private | |
1166 | |
1167 @property | |
1168 def is_unspecified(self): | |
1169 """Test if the address is unspecified. | |
1170 | |
1171 Returns: | |
1172 A boolean, True if this is the unspecified address as defined in | |
1173 RFC 2373 2.5.2. | |
1174 | |
1175 """ | |
1176 return (self.network_address.is_unspecified and | |
1177 self.broadcast_address.is_unspecified) | |
1178 | |
1179 @property | |
1180 def is_loopback(self): | |
1181 """Test if the address is a loopback address. | |
1182 | |
1183 Returns: | |
1184 A boolean, True if the address is a loopback address as defined in | |
1185 RFC 2373 2.5.3. | |
1186 | |
1187 """ | |
1188 return (self.network_address.is_loopback and | |
1189 self.broadcast_address.is_loopback) | |
1190 | |
1191 | |
1192 class _BaseV4(object): | |
1193 | |
1194 """Base IPv4 object. | |
1195 | |
1196 The following methods are used by IPv4 objects in both single IP | |
1197 addresses and networks. | |
1198 | |
1199 """ | |
1200 | |
1201 __slots__ = () | |
1202 _version = 4 | |
1203 # Equivalent to 255.255.255.255 or 32 bits of 1's. | |
1204 _ALL_ONES = (2 ** IPV4LENGTH) - 1 | |
1205 _DECIMAL_DIGITS = frozenset('0123456789') | |
1206 | |
1207 # the valid octets for host and netmasks. only useful for IPv4. | |
1208 _valid_mask_octets = frozenset([255, 254, 252, 248, 240, 224, 192, 128, 0]) | |
1209 | |
1210 _max_prefixlen = IPV4LENGTH | |
1211 # There are only a handful of valid v4 netmasks, so we cache them all | |
1212 # when constructed (see _make_netmask()). | |
1213 _netmask_cache = {} | |
1214 | |
1215 def _explode_shorthand_ip_string(self): | |
1216 return _compat_str(self) | |
1217 | |
1218 @classmethod | |
1219 def _make_netmask(cls, arg): | |
1220 """Make a (netmask, prefix_len) tuple from the given argument. | |
1221 | |
1222 Argument can be: | |
1223 - an integer (the prefix length) | |
1224 - a string representing the prefix length (e.g. "24") | |
1225 - a string representing the prefix netmask (e.g. "255.255.255.0") | |
1226 """ | |
1227 if arg not in cls._netmask_cache: | |
1228 if isinstance(arg, _compat_int_types): | |
1229 prefixlen = arg | |
1230 else: | |
1231 try: | |
1232 # Check for a netmask in prefix length form | |
1233 prefixlen = cls._prefix_from_prefix_string(arg) | |
1234 except NetmaskValueError: | |
1235 # Check for a netmask or hostmask in dotted-quad form. | |
1236 # This may raise NetmaskValueError. | |
1237 prefixlen = cls._prefix_from_ip_string(arg) | |
1238 netmask = IPv4Address(cls._ip_int_from_prefix(prefixlen)) | |
1239 cls._netmask_cache[arg] = netmask, prefixlen | |
1240 return cls._netmask_cache[arg] | |
1241 | |
1242 @classmethod | |
1243 def _ip_int_from_string(cls, ip_str): | |
1244 """Turn the given IP string into an integer for comparison. | |
1245 | |
1246 Args: | |
1247 ip_str: A string, the IP ip_str. | |
1248 | |
1249 Returns: | |
1250 The IP ip_str as an integer. | |
1251 | |
1252 Raises: | |
1253 AddressValueError: if ip_str isn't a valid IPv4 Address. | |
1254 | |
1255 """ | |
1256 if not ip_str: | |
1257 raise AddressValueError('Address cannot be empty') | |
1258 | |
1259 octets = ip_str.split('.') | |
1260 if len(octets) != 4: | |
1261 raise AddressValueError("Expected 4 octets in %r" % ip_str) | |
1262 | |
1263 try: | |
1264 return _compat_int_from_byte_vals( | |
1265 map(cls._parse_octet, octets), 'big') | |
1266 except ValueError as exc: | |
1267 raise AddressValueError("%s in %r" % (exc, ip_str)) | |
1268 | |
1269 @classmethod | |
1270 def _parse_octet(cls, octet_str): | |
1271 """Convert a decimal octet into an integer. | |
1272 | |
1273 Args: | |
1274 octet_str: A string, the number to parse. | |
1275 | |
1276 Returns: | |
1277 The octet as an integer. | |
1278 | |
1279 Raises: | |
1280 ValueError: if the octet isn't strictly a decimal from [0..255]. | |
1281 | |
1282 """ | |
1283 if not octet_str: | |
1284 raise ValueError("Empty octet not permitted") | |
1285 # Whitelist the characters, since int() allows a lot of bizarre stuff. | |
1286 if not cls._DECIMAL_DIGITS.issuperset(octet_str): | |
1287 msg = "Only decimal digits permitted in %r" | |
1288 raise ValueError(msg % octet_str) | |
1289 # We do the length check second, since the invalid character error | |
1290 # is likely to be more informative for the user | |
1291 if len(octet_str) > 3: | |
1292 msg = "At most 3 characters permitted in %r" | |
1293 raise ValueError(msg % octet_str) | |
1294 # Convert to integer (we know digits are legal) | |
1295 octet_int = int(octet_str, 10) | |
1296 # Any octets that look like they *might* be written in octal, | |
1297 # and which don't look exactly the same in both octal and | |
1298 # decimal are rejected as ambiguous | |
1299 if octet_int > 7 and octet_str[0] == '0': | |
1300 msg = "Ambiguous (octal/decimal) value in %r not permitted" | |
1301 raise ValueError(msg % octet_str) | |
1302 if octet_int > 255: | |
1303 raise ValueError("Octet %d (> 255) not permitted" % octet_int) | |
1304 return octet_int | |
1305 | |
1306 @classmethod | |
1307 def _string_from_ip_int(cls, ip_int): | |
1308 """Turns a 32-bit integer into dotted decimal notation. | |
1309 | |
1310 Args: | |
1311 ip_int: An integer, the IP address. | |
1312 | |
1313 Returns: | |
1314 The IP address as a string in dotted decimal notation. | |
1315 | |
1316 """ | |
1317 return '.'.join(_compat_str(struct.unpack(b'!B', b)[0] | |
1318 if isinstance(b, bytes) | |
1319 else b) | |
1320 for b in _compat_to_bytes(ip_int, 4, 'big')) | |
1321 | |
1322 def _is_hostmask(self, ip_str): | |
1323 """Test if the IP string is a hostmask (rather than a netmask). | |
1324 | |
1325 Args: | |
1326 ip_str: A string, the potential hostmask. | |
1327 | |
1328 Returns: | |
1329 A boolean, True if the IP string is a hostmask. | |
1330 | |
1331 """ | |
1332 bits = ip_str.split('.') | |
1333 try: | |
1334 parts = [x for x in map(int, bits) if x in self._valid_mask_octets] | |
1335 except ValueError: | |
1336 return False | |
1337 if len(parts) != len(bits): | |
1338 return False | |
1339 if parts[0] < parts[-1]: | |
1340 return True | |
1341 return False | |
1342 | |
1343 def _reverse_pointer(self): | |
1344 """Return the reverse DNS pointer name for the IPv4 address. | |
1345 | |
1346 This implements the method described in RFC1035 3.5. | |
1347 | |
1348 """ | |
1349 reverse_octets = _compat_str(self).split('.')[::-1] | |
1350 return '.'.join(reverse_octets) + '.in-addr.arpa' | |
1351 | |
1352 @property | |
1353 def max_prefixlen(self): | |
1354 return self._max_prefixlen | |
1355 | |
1356 @property | |
1357 def version(self): | |
1358 return self._version | |
1359 | |
1360 | |
1361 class IPv4Address(_BaseV4, _BaseAddress): | |
1362 | |
1363 """Represent and manipulate single IPv4 Addresses.""" | |
1364 | |
1365 __slots__ = ('_ip', '__weakref__') | |
1366 | |
1367 def __init__(self, address): | |
1368 | |
1369 """ | |
1370 Args: | |
1371 address: A string or integer representing the IP | |
1372 | |
1373 Additionally, an integer can be passed, so | |
1374 IPv4Address('192.0.2.1') == IPv4Address(3221225985). | |
1375 or, more generally | |
1376 IPv4Address(int(IPv4Address('192.0.2.1'))) == | |
1377 IPv4Address('192.0.2.1') | |
1378 | |
1379 Raises: | |
1380 AddressValueError: If ipaddress isn't a valid IPv4 address. | |
1381 | |
1382 """ | |
1383 # Efficient constructor from integer. | |
1384 if isinstance(address, _compat_int_types): | |
1385 self._check_int_address(address) | |
1386 self._ip = address | |
1387 return | |
1388 | |
1389 # Constructing from a packed address | |
1390 if isinstance(address, bytes): | |
1391 self._check_packed_address(address, 4) | |
1392 bvs = _compat_bytes_to_byte_vals(address) | |
1393 self._ip = _compat_int_from_byte_vals(bvs, 'big') | |
1394 return | |
1395 | |
1396 # Assume input argument to be string or any object representation | |
1397 # which converts into a formatted IP string. | |
1398 addr_str = _compat_str(address) | |
1399 if '/' in addr_str: | |
1400 raise AddressValueError("Unexpected '/' in %r" % address) | |
1401 self._ip = self._ip_int_from_string(addr_str) | |
1402 | |
1403 @property | |
1404 def packed(self): | |
1405 """The binary representation of this address.""" | |
1406 return v4_int_to_packed(self._ip) | |
1407 | |
1408 @property | |
1409 def is_reserved(self): | |
1410 """Test if the address is otherwise IETF reserved. | |
1411 | |
1412 Returns: | |
1413 A boolean, True if the address is within the | |
1414 reserved IPv4 Network range. | |
1415 | |
1416 """ | |
1417 return self in self._constants._reserved_network | |
1418 | |
1419 @property | |
1420 def is_private(self): | |
1421 """Test if this address is allocated for private networks. | |
1422 | |
1423 Returns: | |
1424 A boolean, True if the address is reserved per | |
1425 iana-ipv4-special-registry. | |
1426 | |
1427 """ | |
1428 return any(self in net for net in self._constants._private_networks) | |
1429 | |
1430 @property | |
1431 def is_global(self): | |
1432 return ( | |
1433 self not in self._constants._public_network and | |
1434 not self.is_private) | |
1435 | |
1436 @property | |
1437 def is_multicast(self): | |
1438 """Test if the address is reserved for multicast use. | |
1439 | |
1440 Returns: | |
1441 A boolean, True if the address is multicast. | |
1442 See RFC 3171 for details. | |
1443 | |
1444 """ | |
1445 return self in self._constants._multicast_network | |
1446 | |
1447 @property | |
1448 def is_unspecified(self): | |
1449 """Test if the address is unspecified. | |
1450 | |
1451 Returns: | |
1452 A boolean, True if this is the unspecified address as defined in | |
1453 RFC 5735 3. | |
1454 | |
1455 """ | |
1456 return self == self._constants._unspecified_address | |
1457 | |
1458 @property | |
1459 def is_loopback(self): | |
1460 """Test if the address is a loopback address. | |
1461 | |
1462 Returns: | |
1463 A boolean, True if the address is a loopback per RFC 3330. | |
1464 | |
1465 """ | |
1466 return self in self._constants._loopback_network | |
1467 | |
1468 @property | |
1469 def is_link_local(self): | |
1470 """Test if the address is reserved for link-local. | |
1471 | |
1472 Returns: | |
1473 A boolean, True if the address is link-local per RFC 3927. | |
1474 | |
1475 """ | |
1476 return self in self._constants._linklocal_network | |
1477 | |
1478 | |
1479 class IPv4Interface(IPv4Address): | |
1480 | |
1481 def __init__(self, address): | |
1482 if isinstance(address, (bytes, _compat_int_types)): | |
1483 IPv4Address.__init__(self, address) | |
1484 self.network = IPv4Network(self._ip) | |
1485 self._prefixlen = self._max_prefixlen | |
1486 return | |
1487 | |
1488 if isinstance(address, tuple): | |
1489 IPv4Address.__init__(self, address[0]) | |
1490 if len(address) > 1: | |
1491 self._prefixlen = int(address[1]) | |
1492 else: | |
1493 self._prefixlen = self._max_prefixlen | |
1494 | |
1495 self.network = IPv4Network(address, strict=False) | |
1496 self.netmask = self.network.netmask | |
1497 self.hostmask = self.network.hostmask | |
1498 return | |
1499 | |
1500 addr = _split_optional_netmask(address) | |
1501 IPv4Address.__init__(self, addr[0]) | |
1502 | |
1503 self.network = IPv4Network(address, strict=False) | |
1504 self._prefixlen = self.network._prefixlen | |
1505 | |
1506 self.netmask = self.network.netmask | |
1507 self.hostmask = self.network.hostmask | |
1508 | |
1509 def __str__(self): | |
1510 return '%s/%d' % (self._string_from_ip_int(self._ip), | |
1511 self.network.prefixlen) | |
1512 | |
1513 def __eq__(self, other): | |
1514 address_equal = IPv4Address.__eq__(self, other) | |
1515 if not address_equal or address_equal is NotImplemented: | |
1516 return address_equal | |
1517 try: | |
1518 return self.network == other.network | |
1519 except AttributeError: | |
1520 # An interface with an associated network is NOT the | |
1521 # same as an unassociated address. That's why the hash | |
1522 # takes the extra info into account. | |
1523 return False | |
1524 | |
1525 def __lt__(self, other): | |
1526 address_less = IPv4Address.__lt__(self, other) | |
1527 if address_less is NotImplemented: | |
1528 return NotImplemented | |
1529 try: | |
1530 return (self.network < other.network or | |
1531 self.network == other.network and address_less) | |
1532 except AttributeError: | |
1533 # We *do* allow addresses and interfaces to be sorted. The | |
1534 # unassociated address is considered less than all interfaces. | |
1535 return False | |
1536 | |
1537 def __hash__(self): | |
1538 return self._ip ^ self._prefixlen ^ int(self.network.network_address) | |
1539 | |
1540 __reduce__ = _IPAddressBase.__reduce__ | |
1541 | |
1542 @property | |
1543 def ip(self): | |
1544 return IPv4Address(self._ip) | |
1545 | |
1546 @property | |
1547 def with_prefixlen(self): | |
1548 return '%s/%s' % (self._string_from_ip_int(self._ip), | |
1549 self._prefixlen) | |
1550 | |
1551 @property | |
1552 def with_netmask(self): | |
1553 return '%s/%s' % (self._string_from_ip_int(self._ip), | |
1554 self.netmask) | |
1555 | |
1556 @property | |
1557 def with_hostmask(self): | |
1558 return '%s/%s' % (self._string_from_ip_int(self._ip), | |
1559 self.hostmask) | |
1560 | |
1561 | |
1562 class IPv4Network(_BaseV4, _BaseNetwork): | |
1563 | |
1564 """This class represents and manipulates 32-bit IPv4 network + addresses.. | |
1565 | |
1566 Attributes: [examples for IPv4Network('192.0.2.0/27')] | |
1567 .network_address: IPv4Address('192.0.2.0') | |
1568 .hostmask: IPv4Address('0.0.0.31') | |
1569 .broadcast_address: IPv4Address('192.0.2.32') | |
1570 .netmask: IPv4Address('255.255.255.224') | |
1571 .prefixlen: 27 | |
1572 | |
1573 """ | |
1574 # Class to use when creating address objects | |
1575 _address_class = IPv4Address | |
1576 | |
1577 def __init__(self, address, strict=True): | |
1578 | |
1579 """Instantiate a new IPv4 network object. | |
1580 | |
1581 Args: | |
1582 address: A string or integer representing the IP [& network]. | |
1583 '192.0.2.0/24' | |
1584 '192.0.2.0/255.255.255.0' | |
1585 '192.0.0.2/0.0.0.255' | |
1586 are all functionally the same in IPv4. Similarly, | |
1587 '192.0.2.1' | |
1588 '192.0.2.1/255.255.255.255' | |
1589 '192.0.2.1/32' | |
1590 are also functionally equivalent. That is to say, failing to | |
1591 provide a subnetmask will create an object with a mask of /32. | |
1592 | |
1593 If the mask (portion after the / in the argument) is given in | |
1594 dotted quad form, it is treated as a netmask if it starts with a | |
1595 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it | |
1596 starts with a zero field (e.g. 0.255.255.255 == /8), with the | |
1597 single exception of an all-zero mask which is treated as a | |
1598 netmask == /0. If no mask is given, a default of /32 is used. | |
1599 | |
1600 Additionally, an integer can be passed, so | |
1601 IPv4Network('192.0.2.1') == IPv4Network(3221225985) | |
1602 or, more generally | |
1603 IPv4Interface(int(IPv4Interface('192.0.2.1'))) == | |
1604 IPv4Interface('192.0.2.1') | |
1605 | |
1606 Raises: | |
1607 AddressValueError: If ipaddress isn't a valid IPv4 address. | |
1608 NetmaskValueError: If the netmask isn't valid for | |
1609 an IPv4 address. | |
1610 ValueError: If strict is True and a network address is not | |
1611 supplied. | |
1612 | |
1613 """ | |
1614 _BaseNetwork.__init__(self, address) | |
1615 | |
1616 # Constructing from a packed address or integer | |
1617 if isinstance(address, (_compat_int_types, bytes)): | |
1618 self.network_address = IPv4Address(address) | |
1619 self.netmask, self._prefixlen = self._make_netmask( | |
1620 self._max_prefixlen) | |
1621 # fixme: address/network test here. | |
1622 return | |
1623 | |
1624 if isinstance(address, tuple): | |
1625 if len(address) > 1: | |
1626 arg = address[1] | |
1627 else: | |
1628 # We weren't given an address[1] | |
1629 arg = self._max_prefixlen | |
1630 self.network_address = IPv4Address(address[0]) | |
1631 self.netmask, self._prefixlen = self._make_netmask(arg) | |
1632 packed = int(self.network_address) | |
1633 if packed & int(self.netmask) != packed: | |
1634 if strict: | |
1635 raise ValueError('%s has host bits set' % self) | |
1636 else: | |
1637 self.network_address = IPv4Address(packed & | |
1638 int(self.netmask)) | |
1639 return | |
1640 | |
1641 # Assume input argument to be string or any object representation | |
1642 # which converts into a formatted IP prefix string. | |
1643 addr = _split_optional_netmask(address) | |
1644 self.network_address = IPv4Address(self._ip_int_from_string(addr[0])) | |
1645 | |
1646 if len(addr) == 2: | |
1647 arg = addr[1] | |
1648 else: | |
1649 arg = self._max_prefixlen | |
1650 self.netmask, self._prefixlen = self._make_netmask(arg) | |
1651 | |
1652 if strict: | |
1653 if (IPv4Address(int(self.network_address) & int(self.netmask)) != | |
1654 self.network_address): | |
1655 raise ValueError('%s has host bits set' % self) | |
1656 self.network_address = IPv4Address(int(self.network_address) & | |
1657 int(self.netmask)) | |
1658 | |
1659 if self._prefixlen == (self._max_prefixlen - 1): | |
1660 self.hosts = self.__iter__ | |
1661 | |
1662 @property | |
1663 def is_global(self): | |
1664 """Test if this address is allocated for public networks. | |
1665 | |
1666 Returns: | |
1667 A boolean, True if the address is not reserved per | |
1668 iana-ipv4-special-registry. | |
1669 | |
1670 """ | |
1671 return (not (self.network_address in IPv4Network('100.64.0.0/10') and | |
1672 self.broadcast_address in IPv4Network('100.64.0.0/10')) and | |
1673 not self.is_private) | |
1674 | |
1675 | |
1676 class _IPv4Constants(object): | |
1677 | |
1678 _linklocal_network = IPv4Network('169.254.0.0/16') | |
1679 | |
1680 _loopback_network = IPv4Network('127.0.0.0/8') | |
1681 | |
1682 _multicast_network = IPv4Network('224.0.0.0/4') | |
1683 | |
1684 _public_network = IPv4Network('100.64.0.0/10') | |
1685 | |
1686 _private_networks = [ | |
1687 IPv4Network('0.0.0.0/8'), | |
1688 IPv4Network('10.0.0.0/8'), | |
1689 IPv4Network('127.0.0.0/8'), | |
1690 IPv4Network('169.254.0.0/16'), | |
1691 IPv4Network('172.16.0.0/12'), | |
1692 IPv4Network('192.0.0.0/29'), | |
1693 IPv4Network('192.0.0.170/31'), | |
1694 IPv4Network('192.0.2.0/24'), | |
1695 IPv4Network('192.168.0.0/16'), | |
1696 IPv4Network('198.18.0.0/15'), | |
1697 IPv4Network('198.51.100.0/24'), | |
1698 IPv4Network('203.0.113.0/24'), | |
1699 IPv4Network('240.0.0.0/4'), | |
1700 IPv4Network('255.255.255.255/32'), | |
1701 ] | |
1702 | |
1703 _reserved_network = IPv4Network('240.0.0.0/4') | |
1704 | |
1705 _unspecified_address = IPv4Address('0.0.0.0') | |
1706 | |
1707 | |
1708 IPv4Address._constants = _IPv4Constants | |
1709 | |
1710 | |
1711 class _BaseV6(object): | |
1712 | |
1713 """Base IPv6 object. | |
1714 | |
1715 The following methods are used by IPv6 objects in both single IP | |
1716 addresses and networks. | |
1717 | |
1718 """ | |
1719 | |
1720 __slots__ = () | |
1721 _version = 6 | |
1722 _ALL_ONES = (2 ** IPV6LENGTH) - 1 | |
1723 _HEXTET_COUNT = 8 | |
1724 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef') | |
1725 _max_prefixlen = IPV6LENGTH | |
1726 | |
1727 # There are only a bunch of valid v6 netmasks, so we cache them all | |
1728 # when constructed (see _make_netmask()). | |
1729 _netmask_cache = {} | |
1730 | |
1731 @classmethod | |
1732 def _make_netmask(cls, arg): | |
1733 """Make a (netmask, prefix_len) tuple from the given argument. | |
1734 | |
1735 Argument can be: | |
1736 - an integer (the prefix length) | |
1737 - a string representing the prefix length (e.g. "24") | |
1738 - a string representing the prefix netmask (e.g. "255.255.255.0") | |
1739 """ | |
1740 if arg not in cls._netmask_cache: | |
1741 if isinstance(arg, _compat_int_types): | |
1742 prefixlen = arg | |
1743 else: | |
1744 prefixlen = cls._prefix_from_prefix_string(arg) | |
1745 netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen)) | |
1746 cls._netmask_cache[arg] = netmask, prefixlen | |
1747 return cls._netmask_cache[arg] | |
1748 | |
1749 @classmethod | |
1750 def _ip_int_from_string(cls, ip_str): | |
1751 """Turn an IPv6 ip_str into an integer. | |
1752 | |
1753 Args: | |
1754 ip_str: A string, the IPv6 ip_str. | |
1755 | |
1756 Returns: | |
1757 An int, the IPv6 address | |
1758 | |
1759 Raises: | |
1760 AddressValueError: if ip_str isn't a valid IPv6 Address. | |
1761 | |
1762 """ | |
1763 if not ip_str: | |
1764 raise AddressValueError('Address cannot be empty') | |
1765 | |
1766 parts = ip_str.split(':') | |
1767 | |
1768 # An IPv6 address needs at least 2 colons (3 parts). | |
1769 _min_parts = 3 | |
1770 if len(parts) < _min_parts: | |
1771 msg = "At least %d parts expected in %r" % (_min_parts, ip_str) | |
1772 raise AddressValueError(msg) | |
1773 | |
1774 # If the address has an IPv4-style suffix, convert it to hexadecimal. | |
1775 if '.' in parts[-1]: | |
1776 try: | |
1777 ipv4_int = IPv4Address(parts.pop())._ip | |
1778 except AddressValueError as exc: | |
1779 raise AddressValueError("%s in %r" % (exc, ip_str)) | |
1780 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF)) | |
1781 parts.append('%x' % (ipv4_int & 0xFFFF)) | |
1782 | |
1783 # An IPv6 address can't have more than 8 colons (9 parts). | |
1784 # The extra colon comes from using the "::" notation for a single | |
1785 # leading or trailing zero part. | |
1786 _max_parts = cls._HEXTET_COUNT + 1 | |
1787 if len(parts) > _max_parts: | |
1788 msg = "At most %d colons permitted in %r" % ( | |
1789 _max_parts - 1, ip_str) | |
1790 raise AddressValueError(msg) | |
1791 | |
1792 # Disregarding the endpoints, find '::' with nothing in between. | |
1793 # This indicates that a run of zeroes has been skipped. | |
1794 skip_index = None | |
1795 for i in _compat_range(1, len(parts) - 1): | |
1796 if not parts[i]: | |
1797 if skip_index is not None: | |
1798 # Can't have more than one '::' | |
1799 msg = "At most one '::' permitted in %r" % ip_str | |
1800 raise AddressValueError(msg) | |
1801 skip_index = i | |
1802 | |
1803 # parts_hi is the number of parts to copy from above/before the '::' | |
1804 # parts_lo is the number of parts to copy from below/after the '::' | |
1805 if skip_index is not None: | |
1806 # If we found a '::', then check if it also covers the endpoints. | |
1807 parts_hi = skip_index | |
1808 parts_lo = len(parts) - skip_index - 1 | |
1809 if not parts[0]: | |
1810 parts_hi -= 1 | |
1811 if parts_hi: | |
1812 msg = "Leading ':' only permitted as part of '::' in %r" | |
1813 raise AddressValueError(msg % ip_str) # ^: requires ^:: | |
1814 if not parts[-1]: | |
1815 parts_lo -= 1 | |
1816 if parts_lo: | |
1817 msg = "Trailing ':' only permitted as part of '::' in %r" | |
1818 raise AddressValueError(msg % ip_str) # :$ requires ::$ | |
1819 parts_skipped = cls._HEXTET_COUNT - (parts_hi + parts_lo) | |
1820 if parts_skipped < 1: | |
1821 msg = "Expected at most %d other parts with '::' in %r" | |
1822 raise AddressValueError(msg % (cls._HEXTET_COUNT - 1, ip_str)) | |
1823 else: | |
1824 # Otherwise, allocate the entire address to parts_hi. The | |
1825 # endpoints could still be empty, but _parse_hextet() will check | |
1826 # for that. | |
1827 if len(parts) != cls._HEXTET_COUNT: | |
1828 msg = "Exactly %d parts expected without '::' in %r" | |
1829 raise AddressValueError(msg % (cls._HEXTET_COUNT, ip_str)) | |
1830 if not parts[0]: | |
1831 msg = "Leading ':' only permitted as part of '::' in %r" | |
1832 raise AddressValueError(msg % ip_str) # ^: requires ^:: | |
1833 if not parts[-1]: | |
1834 msg = "Trailing ':' only permitted as part of '::' in %r" | |
1835 raise AddressValueError(msg % ip_str) # :$ requires ::$ | |
1836 parts_hi = len(parts) | |
1837 parts_lo = 0 | |
1838 parts_skipped = 0 | |
1839 | |
1840 try: | |
1841 # Now, parse the hextets into a 128-bit integer. | |
1842 ip_int = 0 | |
1843 for i in range(parts_hi): | |
1844 ip_int <<= 16 | |
1845 ip_int |= cls._parse_hextet(parts[i]) | |
1846 ip_int <<= 16 * parts_skipped | |
1847 for i in range(-parts_lo, 0): | |
1848 ip_int <<= 16 | |
1849 ip_int |= cls._parse_hextet(parts[i]) | |
1850 return ip_int | |
1851 except ValueError as exc: | |
1852 raise AddressValueError("%s in %r" % (exc, ip_str)) | |
1853 | |
1854 @classmethod | |
1855 def _parse_hextet(cls, hextet_str): | |
1856 """Convert an IPv6 hextet string into an integer. | |
1857 | |
1858 Args: | |
1859 hextet_str: A string, the number to parse. | |
1860 | |
1861 Returns: | |
1862 The hextet as an integer. | |
1863 | |
1864 Raises: | |
1865 ValueError: if the input isn't strictly a hex number from | |
1866 [0..FFFF]. | |
1867 | |
1868 """ | |
1869 # Whitelist the characters, since int() allows a lot of bizarre stuff. | |
1870 if not cls._HEX_DIGITS.issuperset(hextet_str): | |
1871 raise ValueError("Only hex digits permitted in %r" % hextet_str) | |
1872 # We do the length check second, since the invalid character error | |
1873 # is likely to be more informative for the user | |
1874 if len(hextet_str) > 4: | |
1875 msg = "At most 4 characters permitted in %r" | |
1876 raise ValueError(msg % hextet_str) | |
1877 # Length check means we can skip checking the integer value | |
1878 return int(hextet_str, 16) | |
1879 | |
1880 @classmethod | |
1881 def _compress_hextets(cls, hextets): | |
1882 """Compresses a list of hextets. | |
1883 | |
1884 Compresses a list of strings, replacing the longest continuous | |
1885 sequence of "0" in the list with "" and adding empty strings at | |
1886 the beginning or at the end of the string such that subsequently | |
1887 calling ":".join(hextets) will produce the compressed version of | |
1888 the IPv6 address. | |
1889 | |
1890 Args: | |
1891 hextets: A list of strings, the hextets to compress. | |
1892 | |
1893 Returns: | |
1894 A list of strings. | |
1895 | |
1896 """ | |
1897 best_doublecolon_start = -1 | |
1898 best_doublecolon_len = 0 | |
1899 doublecolon_start = -1 | |
1900 doublecolon_len = 0 | |
1901 for index, hextet in enumerate(hextets): | |
1902 if hextet == '0': | |
1903 doublecolon_len += 1 | |
1904 if doublecolon_start == -1: | |
1905 # Start of a sequence of zeros. | |
1906 doublecolon_start = index | |
1907 if doublecolon_len > best_doublecolon_len: | |
1908 # This is the longest sequence of zeros so far. | |
1909 best_doublecolon_len = doublecolon_len | |
1910 best_doublecolon_start = doublecolon_start | |
1911 else: | |
1912 doublecolon_len = 0 | |
1913 doublecolon_start = -1 | |
1914 | |
1915 if best_doublecolon_len > 1: | |
1916 best_doublecolon_end = (best_doublecolon_start + | |
1917 best_doublecolon_len) | |
1918 # For zeros at the end of the address. | |
1919 if best_doublecolon_end == len(hextets): | |
1920 hextets += [''] | |
1921 hextets[best_doublecolon_start:best_doublecolon_end] = [''] | |
1922 # For zeros at the beginning of the address. | |
1923 if best_doublecolon_start == 0: | |
1924 hextets = [''] + hextets | |
1925 | |
1926 return hextets | |
1927 | |
1928 @classmethod | |
1929 def _string_from_ip_int(cls, ip_int=None): | |
1930 """Turns a 128-bit integer into hexadecimal notation. | |
1931 | |
1932 Args: | |
1933 ip_int: An integer, the IP address. | |
1934 | |
1935 Returns: | |
1936 A string, the hexadecimal representation of the address. | |
1937 | |
1938 Raises: | |
1939 ValueError: The address is bigger than 128 bits of all ones. | |
1940 | |
1941 """ | |
1942 if ip_int is None: | |
1943 ip_int = int(cls._ip) | |
1944 | |
1945 if ip_int > cls._ALL_ONES: | |
1946 raise ValueError('IPv6 address is too large') | |
1947 | |
1948 hex_str = '%032x' % ip_int | |
1949 hextets = ['%x' % int(hex_str[x:x + 4], 16) for x in range(0, 32, 4)] | |
1950 | |
1951 hextets = cls._compress_hextets(hextets) | |
1952 return ':'.join(hextets) | |
1953 | |
1954 def _explode_shorthand_ip_string(self): | |
1955 """Expand a shortened IPv6 address. | |
1956 | |
1957 Args: | |
1958 ip_str: A string, the IPv6 address. | |
1959 | |
1960 Returns: | |
1961 A string, the expanded IPv6 address. | |
1962 | |
1963 """ | |
1964 if isinstance(self, IPv6Network): | |
1965 ip_str = _compat_str(self.network_address) | |
1966 elif isinstance(self, IPv6Interface): | |
1967 ip_str = _compat_str(self.ip) | |
1968 else: | |
1969 ip_str = _compat_str(self) | |
1970 | |
1971 ip_int = self._ip_int_from_string(ip_str) | |
1972 hex_str = '%032x' % ip_int | |
1973 parts = [hex_str[x:x + 4] for x in range(0, 32, 4)] | |
1974 if isinstance(self, (_BaseNetwork, IPv6Interface)): | |
1975 return '%s/%d' % (':'.join(parts), self._prefixlen) | |
1976 return ':'.join(parts) | |
1977 | |
1978 def _reverse_pointer(self): | |
1979 """Return the reverse DNS pointer name for the IPv6 address. | |
1980 | |
1981 This implements the method described in RFC3596 2.5. | |
1982 | |
1983 """ | |
1984 reverse_chars = self.exploded[::-1].replace(':', '') | |
1985 return '.'.join(reverse_chars) + '.ip6.arpa' | |
1986 | |
1987 @property | |
1988 def max_prefixlen(self): | |
1989 return self._max_prefixlen | |
1990 | |
1991 @property | |
1992 def version(self): | |
1993 return self._version | |
1994 | |
1995 | |
1996 class IPv6Address(_BaseV6, _BaseAddress): | |
1997 | |
1998 """Represent and manipulate single IPv6 Addresses.""" | |
1999 | |
2000 __slots__ = ('_ip', '__weakref__') | |
2001 | |
2002 def __init__(self, address): | |
2003 """Instantiate a new IPv6 address object. | |
2004 | |
2005 Args: | |
2006 address: A string or integer representing the IP | |
2007 | |
2008 Additionally, an integer can be passed, so | |
2009 IPv6Address('2001:db8::') == | |
2010 IPv6Address(42540766411282592856903984951653826560) | |
2011 or, more generally | |
2012 IPv6Address(int(IPv6Address('2001:db8::'))) == | |
2013 IPv6Address('2001:db8::') | |
2014 | |
2015 Raises: | |
2016 AddressValueError: If address isn't a valid IPv6 address. | |
2017 | |
2018 """ | |
2019 # Efficient constructor from integer. | |
2020 if isinstance(address, _compat_int_types): | |
2021 self._check_int_address(address) | |
2022 self._ip = address | |
2023 return | |
2024 | |
2025 # Constructing from a packed address | |
2026 if isinstance(address, bytes): | |
2027 self._check_packed_address(address, 16) | |
2028 bvs = _compat_bytes_to_byte_vals(address) | |
2029 self._ip = _compat_int_from_byte_vals(bvs, 'big') | |
2030 return | |
2031 | |
2032 # Assume input argument to be string or any object representation | |
2033 # which converts into a formatted IP string. | |
2034 addr_str = _compat_str(address) | |
2035 if '/' in addr_str: | |
2036 raise AddressValueError("Unexpected '/' in %r" % address) | |
2037 self._ip = self._ip_int_from_string(addr_str) | |
2038 | |
2039 @property | |
2040 def packed(self): | |
2041 """The binary representation of this address.""" | |
2042 return v6_int_to_packed(self._ip) | |
2043 | |
2044 @property | |
2045 def is_multicast(self): | |
2046 """Test if the address is reserved for multicast use. | |
2047 | |
2048 Returns: | |
2049 A boolean, True if the address is a multicast address. | |
2050 See RFC 2373 2.7 for details. | |
2051 | |
2052 """ | |
2053 return self in self._constants._multicast_network | |
2054 | |
2055 @property | |
2056 def is_reserved(self): | |
2057 """Test if the address is otherwise IETF reserved. | |
2058 | |
2059 Returns: | |
2060 A boolean, True if the address is within one of the | |
2061 reserved IPv6 Network ranges. | |
2062 | |
2063 """ | |
2064 return any(self in x for x in self._constants._reserved_networks) | |
2065 | |
2066 @property | |
2067 def is_link_local(self): | |
2068 """Test if the address is reserved for link-local. | |
2069 | |
2070 Returns: | |
2071 A boolean, True if the address is reserved per RFC 4291. | |
2072 | |
2073 """ | |
2074 return self in self._constants._linklocal_network | |
2075 | |
2076 @property | |
2077 def is_site_local(self): | |
2078 """Test if the address is reserved for site-local. | |
2079 | |
2080 Note that the site-local address space has been deprecated by RFC 3879. | |
2081 Use is_private to test if this address is in the space of unique local | |
2082 addresses as defined by RFC 4193. | |
2083 | |
2084 Returns: | |
2085 A boolean, True if the address is reserved per RFC 3513 2.5.6. | |
2086 | |
2087 """ | |
2088 return self in self._constants._sitelocal_network | |
2089 | |
2090 @property | |
2091 def is_private(self): | |
2092 """Test if this address is allocated for private networks. | |
2093 | |
2094 Returns: | |
2095 A boolean, True if the address is reserved per | |
2096 iana-ipv6-special-registry. | |
2097 | |
2098 """ | |
2099 return any(self in net for net in self._constants._private_networks) | |
2100 | |
2101 @property | |
2102 def is_global(self): | |
2103 """Test if this address is allocated for public networks. | |
2104 | |
2105 Returns: | |
2106 A boolean, true if the address is not reserved per | |
2107 iana-ipv6-special-registry. | |
2108 | |
2109 """ | |
2110 return not self.is_private | |
2111 | |
2112 @property | |
2113 def is_unspecified(self): | |
2114 """Test if the address is unspecified. | |
2115 | |
2116 Returns: | |
2117 A boolean, True if this is the unspecified address as defined in | |
2118 RFC 2373 2.5.2. | |
2119 | |
2120 """ | |
2121 return self._ip == 0 | |
2122 | |
2123 @property | |
2124 def is_loopback(self): | |
2125 """Test if the address is a loopback address. | |
2126 | |
2127 Returns: | |
2128 A boolean, True if the address is a loopback address as defined in | |
2129 RFC 2373 2.5.3. | |
2130 | |
2131 """ | |
2132 return self._ip == 1 | |
2133 | |
2134 @property | |
2135 def ipv4_mapped(self): | |
2136 """Return the IPv4 mapped address. | |
2137 | |
2138 Returns: | |
2139 If the IPv6 address is a v4 mapped address, return the | |
2140 IPv4 mapped address. Return None otherwise. | |
2141 | |
2142 """ | |
2143 if (self._ip >> 32) != 0xFFFF: | |
2144 return None | |
2145 return IPv4Address(self._ip & 0xFFFFFFFF) | |
2146 | |
2147 @property | |
2148 def teredo(self): | |
2149 """Tuple of embedded teredo IPs. | |
2150 | |
2151 Returns: | |
2152 Tuple of the (server, client) IPs or None if the address | |
2153 doesn't appear to be a teredo address (doesn't start with | |
2154 2001::/32) | |
2155 | |
2156 """ | |
2157 if (self._ip >> 96) != 0x20010000: | |
2158 return None | |
2159 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF), | |
2160 IPv4Address(~self._ip & 0xFFFFFFFF)) | |
2161 | |
2162 @property | |
2163 def sixtofour(self): | |
2164 """Return the IPv4 6to4 embedded address. | |
2165 | |
2166 Returns: | |
2167 The IPv4 6to4-embedded address if present or None if the | |
2168 address doesn't appear to contain a 6to4 embedded address. | |
2169 | |
2170 """ | |
2171 if (self._ip >> 112) != 0x2002: | |
2172 return None | |
2173 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF) | |
2174 | |
2175 | |
2176 class IPv6Interface(IPv6Address): | |
2177 | |
2178 def __init__(self, address): | |
2179 if isinstance(address, (bytes, _compat_int_types)): | |
2180 IPv6Address.__init__(self, address) | |
2181 self.network = IPv6Network(self._ip) | |
2182 self._prefixlen = self._max_prefixlen | |
2183 return | |
2184 if isinstance(address, tuple): | |
2185 IPv6Address.__init__(self, address[0]) | |
2186 if len(address) > 1: | |
2187 self._prefixlen = int(address[1]) | |
2188 else: | |
2189 self._prefixlen = self._max_prefixlen | |
2190 self.network = IPv6Network(address, strict=False) | |
2191 self.netmask = self.network.netmask | |
2192 self.hostmask = self.network.hostmask | |
2193 return | |
2194 | |
2195 addr = _split_optional_netmask(address) | |
2196 IPv6Address.__init__(self, addr[0]) | |
2197 self.network = IPv6Network(address, strict=False) | |
2198 self.netmask = self.network.netmask | |
2199 self._prefixlen = self.network._prefixlen | |
2200 self.hostmask = self.network.hostmask | |
2201 | |
2202 def __str__(self): | |
2203 return '%s/%d' % (self._string_from_ip_int(self._ip), | |
2204 self.network.prefixlen) | |
2205 | |
2206 def __eq__(self, other): | |
2207 address_equal = IPv6Address.__eq__(self, other) | |
2208 if not address_equal or address_equal is NotImplemented: | |
2209 return address_equal | |
2210 try: | |
2211 return self.network == other.network | |
2212 except AttributeError: | |
2213 # An interface with an associated network is NOT the | |
2214 # same as an unassociated address. That's why the hash | |
2215 # takes the extra info into account. | |
2216 return False | |
2217 | |
2218 def __lt__(self, other): | |
2219 address_less = IPv6Address.__lt__(self, other) | |
2220 if address_less is NotImplemented: | |
2221 return NotImplemented | |
2222 try: | |
2223 return (self.network < other.network or | |
2224 self.network == other.network and address_less) | |
2225 except AttributeError: | |
2226 # We *do* allow addresses and interfaces to be sorted. The | |
2227 # unassociated address is considered less than all interfaces. | |
2228 return False | |
2229 | |
2230 def __hash__(self): | |
2231 return self._ip ^ self._prefixlen ^ int(self.network.network_address) | |
2232 | |
2233 __reduce__ = _IPAddressBase.__reduce__ | |
2234 | |
2235 @property | |
2236 def ip(self): | |
2237 return IPv6Address(self._ip) | |
2238 | |
2239 @property | |
2240 def with_prefixlen(self): | |
2241 return '%s/%s' % (self._string_from_ip_int(self._ip), | |
2242 self._prefixlen) | |
2243 | |
2244 @property | |
2245 def with_netmask(self): | |
2246 return '%s/%s' % (self._string_from_ip_int(self._ip), | |
2247 self.netmask) | |
2248 | |
2249 @property | |
2250 def with_hostmask(self): | |
2251 return '%s/%s' % (self._string_from_ip_int(self._ip), | |
2252 self.hostmask) | |
2253 | |
2254 @property | |
2255 def is_unspecified(self): | |
2256 return self._ip == 0 and self.network.is_unspecified | |
2257 | |
2258 @property | |
2259 def is_loopback(self): | |
2260 return self._ip == 1 and self.network.is_loopback | |
2261 | |
2262 | |
2263 class IPv6Network(_BaseV6, _BaseNetwork): | |
2264 | |
2265 """This class represents and manipulates 128-bit IPv6 networks. | |
2266 | |
2267 Attributes: [examples for IPv6('2001:db8::1000/124')] | |
2268 .network_address: IPv6Address('2001:db8::1000') | |
2269 .hostmask: IPv6Address('::f') | |
2270 .broadcast_address: IPv6Address('2001:db8::100f') | |
2271 .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0') | |
2272 .prefixlen: 124 | |
2273 | |
2274 """ | |
2275 | |
2276 # Class to use when creating address objects | |
2277 _address_class = IPv6Address | |
2278 | |
2279 def __init__(self, address, strict=True): | |
2280 """Instantiate a new IPv6 Network object. | |
2281 | |
2282 Args: | |
2283 address: A string or integer representing the IPv6 network or the | |
2284 IP and prefix/netmask. | |
2285 '2001:db8::/128' | |
2286 '2001:db8:0000:0000:0000:0000:0000:0000/128' | |
2287 '2001:db8::' | |
2288 are all functionally the same in IPv6. That is to say, | |
2289 failing to provide a subnetmask will create an object with | |
2290 a mask of /128. | |
2291 | |
2292 Additionally, an integer can be passed, so | |
2293 IPv6Network('2001:db8::') == | |
2294 IPv6Network(42540766411282592856903984951653826560) | |
2295 or, more generally | |
2296 IPv6Network(int(IPv6Network('2001:db8::'))) == | |
2297 IPv6Network('2001:db8::') | |
2298 | |
2299 strict: A boolean. If true, ensure that we have been passed | |
2300 A true network address, eg, 2001:db8::1000/124 and not an | |
2301 IP address on a network, eg, 2001:db8::1/124. | |
2302 | |
2303 Raises: | |
2304 AddressValueError: If address isn't a valid IPv6 address. | |
2305 NetmaskValueError: If the netmask isn't valid for | |
2306 an IPv6 address. | |
2307 ValueError: If strict was True and a network address was not | |
2308 supplied. | |
2309 | |
2310 """ | |
2311 _BaseNetwork.__init__(self, address) | |
2312 | |
2313 # Efficient constructor from integer or packed address | |
2314 if isinstance(address, (bytes, _compat_int_types)): | |
2315 self.network_address = IPv6Address(address) | |
2316 self.netmask, self._prefixlen = self._make_netmask( | |
2317 self._max_prefixlen) | |
2318 return | |
2319 | |
2320 if isinstance(address, tuple): | |
2321 if len(address) > 1: | |
2322 arg = address[1] | |
2323 else: | |
2324 arg = self._max_prefixlen | |
2325 self.netmask, self._prefixlen = self._make_netmask(arg) | |
2326 self.network_address = IPv6Address(address[0]) | |
2327 packed = int(self.network_address) | |
2328 if packed & int(self.netmask) != packed: | |
2329 if strict: | |
2330 raise ValueError('%s has host bits set' % self) | |
2331 else: | |
2332 self.network_address = IPv6Address(packed & | |
2333 int(self.netmask)) | |
2334 return | |
2335 | |
2336 # Assume input argument to be string or any object representation | |
2337 # which converts into a formatted IP prefix string. | |
2338 addr = _split_optional_netmask(address) | |
2339 | |
2340 self.network_address = IPv6Address(self._ip_int_from_string(addr[0])) | |
2341 | |
2342 if len(addr) == 2: | |
2343 arg = addr[1] | |
2344 else: | |
2345 arg = self._max_prefixlen | |
2346 self.netmask, self._prefixlen = self._make_netmask(arg) | |
2347 | |
2348 if strict: | |
2349 if (IPv6Address(int(self.network_address) & int(self.netmask)) != | |
2350 self.network_address): | |
2351 raise ValueError('%s has host bits set' % self) | |
2352 self.network_address = IPv6Address(int(self.network_address) & | |
2353 int(self.netmask)) | |
2354 | |
2355 if self._prefixlen == (self._max_prefixlen - 1): | |
2356 self.hosts = self.__iter__ | |
2357 | |
2358 def hosts(self): | |
2359 """Generate Iterator over usable hosts in a network. | |
2360 | |
2361 This is like __iter__ except it doesn't return the | |
2362 Subnet-Router anycast address. | |
2363 | |
2364 """ | |
2365 network = int(self.network_address) | |
2366 broadcast = int(self.broadcast_address) | |
2367 for x in _compat_range(network + 1, broadcast + 1): | |
2368 yield self._address_class(x) | |
2369 | |
2370 @property | |
2371 def is_site_local(self): | |
2372 """Test if the address is reserved for site-local. | |
2373 | |
2374 Note that the site-local address space has been deprecated by RFC 3879. | |
2375 Use is_private to test if this address is in the space of unique local | |
2376 addresses as defined by RFC 4193. | |
2377 | |
2378 Returns: | |
2379 A boolean, True if the address is reserved per RFC 3513 2.5.6. | |
2380 | |
2381 """ | |
2382 return (self.network_address.is_site_local and | |
2383 self.broadcast_address.is_site_local) | |
2384 | |
2385 | |
2386 class _IPv6Constants(object): | |
2387 | |
2388 _linklocal_network = IPv6Network('fe80::/10') | |
2389 | |
2390 _multicast_network = IPv6Network('ff00::/8') | |
2391 | |
2392 _private_networks = [ | |
2393 IPv6Network('::1/128'), | |
2394 IPv6Network('::/128'), | |
2395 IPv6Network('::ffff:0:0/96'), | |
2396 IPv6Network('100::/64'), | |
2397 IPv6Network('2001::/23'), | |
2398 IPv6Network('2001:2::/48'), | |
2399 IPv6Network('2001:db8::/32'), | |
2400 IPv6Network('2001:10::/28'), | |
2401 IPv6Network('fc00::/7'), | |
2402 IPv6Network('fe80::/10'), | |
2403 ] | |
2404 | |
2405 _reserved_networks = [ | |
2406 IPv6Network('::/8'), IPv6Network('100::/8'), | |
2407 IPv6Network('200::/7'), IPv6Network('400::/6'), | |
2408 IPv6Network('800::/5'), IPv6Network('1000::/4'), | |
2409 IPv6Network('4000::/3'), IPv6Network('6000::/3'), | |
2410 IPv6Network('8000::/3'), IPv6Network('A000::/3'), | |
2411 IPv6Network('C000::/3'), IPv6Network('E000::/4'), | |
2412 IPv6Network('F000::/5'), IPv6Network('F800::/6'), | |
2413 IPv6Network('FE00::/9'), | |
2414 ] | |
2415 | |
2416 _sitelocal_network = IPv6Network('fec0::/10') | |
2417 | |
2418 | |
2419 IPv6Address._constants = _IPv6Constants |