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