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