ยปCore Development>Code coverage>Lib/ipaddress.py

Python code coverage for Lib/ipaddress.py

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