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