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