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