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