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