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