blob: c389f0528823e8bd2a75daa09dfe382f5c92eb0c [file] [log] [blame]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001# Copyright 2007 Google Inc.
2# Licensed to PSF under a Contributor Agreement.
Nick Coghlandc9b2552012-05-20 21:01:57 +10003
4"""A fast, lightweight IPv4/IPv6 manipulation library in Python.
5
6This library is used to create/poke/manipulate IPv4 and IPv6 addresses
7and networks.
8
9"""
10
11__version__ = '1.0'
12
Hynek Schlawack91c5a342012-06-05 11:55:58 +020013
Nick Coghlan3008ec02012-07-08 00:45:33 +100014import functools
Hynek Schlawack91c5a342012-06-05 11:55:58 +020015
Nick Coghlandc9b2552012-05-20 21:01:57 +100016IPV4LENGTH = 32
17IPV6LENGTH = 128
18
Nick Coghlandc9b2552012-05-20 21:01:57 +100019class AddressValueError(ValueError):
20 """A Value Error related to the address."""
21
22
23class NetmaskValueError(ValueError):
24 """A Value Error related to the netmask."""
25
26
Nick Coghlan51c30672012-05-27 00:25:58 +100027def ip_address(address):
Nick Coghlandc9b2552012-05-20 21:01:57 +100028 """Take an IP string/int and return an object of the correct type.
29
30 Args:
31 address: A string or integer, the IP address. Either IPv4 or
32 IPv6 addresses may be supplied; integers less than 2**32 will
33 be considered to be IPv4 by default.
Nick Coghlandc9b2552012-05-20 21:01:57 +100034
35 Returns:
36 An IPv4Address or IPv6Address object.
37
38 Raises:
Sandro Tosi876ecad2012-05-23 22:26:55 +020039 ValueError: if the *address* passed isn't either a v4 or a v6
Nick Coghlan51c30672012-05-27 00:25:58 +100040 address
Nick Coghlandc9b2552012-05-20 21:01:57 +100041
42 """
Nick Coghlandc9b2552012-05-20 21:01:57 +100043 try:
44 return IPv4Address(address)
45 except (AddressValueError, NetmaskValueError):
46 pass
47
48 try:
49 return IPv6Address(address)
50 except (AddressValueError, NetmaskValueError):
51 pass
52
53 raise ValueError('%r does not appear to be an IPv4 or IPv6 address' %
54 address)
55
56
Nick Coghlan51c30672012-05-27 00:25:58 +100057def ip_network(address, strict=True):
Nick Coghlandc9b2552012-05-20 21:01:57 +100058 """Take an IP string/int and return an object of the correct type.
59
60 Args:
61 address: A string or integer, the IP network. Either IPv4 or
62 IPv6 networks may be supplied; integers less than 2**32 will
63 be considered to be IPv4 by default.
Nick Coghlandc9b2552012-05-20 21:01:57 +100064
65 Returns:
66 An IPv4Network or IPv6Network object.
67
68 Raises:
69 ValueError: if the string passed isn't either a v4 or a v6
Nick Coghlan51c30672012-05-27 00:25:58 +100070 address. Or if the network has host bits set.
Nick Coghlandc9b2552012-05-20 21:01:57 +100071
72 """
Nick Coghlandc9b2552012-05-20 21:01:57 +100073 try:
74 return IPv4Network(address, strict)
75 except (AddressValueError, NetmaskValueError):
76 pass
77
78 try:
79 return IPv6Network(address, strict)
80 except (AddressValueError, NetmaskValueError):
81 pass
82
83 raise ValueError('%r does not appear to be an IPv4 or IPv6 network' %
84 address)
85
86
Nick Coghlan51c30672012-05-27 00:25:58 +100087def ip_interface(address):
Nick Coghlandc9b2552012-05-20 21:01:57 +100088 """Take an IP string/int and return an object of the correct type.
89
90 Args:
91 address: A string or integer, the IP address. Either IPv4 or
92 IPv6 addresses may be supplied; integers less than 2**32 will
93 be considered to be IPv4 by default.
Nick Coghlandc9b2552012-05-20 21:01:57 +100094
95 Returns:
Sandro Tosi876ecad2012-05-23 22:26:55 +020096 An IPv4Interface or IPv6Interface object.
Nick Coghlandc9b2552012-05-20 21:01:57 +100097
98 Raises:
99 ValueError: if the string passed isn't either a v4 or a v6
Nick Coghlan51c30672012-05-27 00:25:58 +1000100 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000101
102 Notes:
103 The IPv?Interface classes describe an Address on a particular
104 Network, so they're basically a combination of both the Address
105 and Network classes.
Sandro Tosib95c6342012-05-23 23:17:22 +0200106
Nick Coghlandc9b2552012-05-20 21:01:57 +1000107 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000108 try:
109 return IPv4Interface(address)
110 except (AddressValueError, NetmaskValueError):
111 pass
112
113 try:
114 return IPv6Interface(address)
115 except (AddressValueError, NetmaskValueError):
116 pass
117
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000118 raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' %
Nick Coghlandc9b2552012-05-20 21:01:57 +1000119 address)
120
121
122def v4_int_to_packed(address):
Sandro Tosi876ecad2012-05-23 22:26:55 +0200123 """Represent an address as 4 packed bytes in network (big-endian) order.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000124
125 Args:
126 address: An integer representation of an IPv4 IP address.
127
128 Returns:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200129 The integer address packed as 4 bytes in network (big-endian) order.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000130
131 Raises:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200132 ValueError: If the integer is negative or too large to be an
133 IPv4 IP address.
Sandro Tosib95c6342012-05-23 23:17:22 +0200134
Nick Coghlandc9b2552012-05-20 21:01:57 +1000135 """
Sandro Tosi876ecad2012-05-23 22:26:55 +0200136 try:
Nick Coghlandb7920b2012-08-20 10:19:12 +1000137 return address.to_bytes(4, 'big')
Serhiy Storchakaba9ac5b2015-05-20 10:33:40 +0300138 except OverflowError:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200139 raise ValueError("Address negative or too large for IPv4")
Nick Coghlandc9b2552012-05-20 21:01:57 +1000140
141
142def v6_int_to_packed(address):
Sandro Tosi876ecad2012-05-23 22:26:55 +0200143 """Represent an address as 16 packed bytes in network (big-endian) order.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000144
145 Args:
Sandro Tosib4386d32012-06-02 17:14:22 +0200146 address: An integer representation of an IPv6 IP address.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000147
148 Returns:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200149 The integer address packed as 16 bytes in network (big-endian) order.
Sandro Tosib95c6342012-05-23 23:17:22 +0200150
Nick Coghlandc9b2552012-05-20 21:01:57 +1000151 """
Sandro Tosi876ecad2012-05-23 22:26:55 +0200152 try:
Nick Coghlandb7920b2012-08-20 10:19:12 +1000153 return address.to_bytes(16, 'big')
Serhiy Storchakaba9ac5b2015-05-20 10:33:40 +0300154 except OverflowError:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200155 raise ValueError("Address negative or too large for IPv6")
Nick Coghlandc9b2552012-05-20 21:01:57 +1000156
157
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000158def _split_optional_netmask(address):
159 """Helper to split the netmask and raise AddressValueError if needed"""
160 addr = str(address).split('/')
161 if len(addr) > 2:
162 raise AddressValueError("Only one '/' permitted in %r" % address)
163 return addr
164
Nick Coghlan297b1432012-07-08 17:11:04 +1000165
Nick Coghlandc9b2552012-05-20 21:01:57 +1000166def _find_address_range(addresses):
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200167 """Find a sequence of sorted deduplicated IPv#Address.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000168
169 Args:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200170 addresses: a list of IPv#Address objects.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000171
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200172 Yields:
173 A tuple containing the first and last IP addresses in the sequence.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000174
175 """
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200176 it = iter(addresses)
177 first = last = next(it)
178 for ip in it:
179 if ip._ip != last._ip + 1:
180 yield first, last
181 first = ip
182 last = ip
183 yield first, last
Nick Coghlandc9b2552012-05-20 21:01:57 +1000184
Sandro Tosib95c6342012-05-23 23:17:22 +0200185
Nick Coghlandc9b2552012-05-20 21:01:57 +1000186def _count_righthand_zero_bits(number, bits):
187 """Count the number of zero bits on the right hand side.
188
189 Args:
190 number: an integer.
191 bits: maximum number of bits to count.
192
193 Returns:
194 The number of zero bits on the right hand side of the number.
195
196 """
197 if number == 0:
198 return bits
Antoine Pitrou824db302014-05-15 20:21:48 +0200199 return min(bits, (~number & (number-1)).bit_length())
Nick Coghlandc9b2552012-05-20 21:01:57 +1000200
201
202def summarize_address_range(first, last):
203 """Summarize a network range given the first and last IP addresses.
204
205 Example:
Eli Bendersky948af232012-10-07 07:23:50 -0700206 >>> list(summarize_address_range(IPv4Address('192.0.2.0'),
207 ... IPv4Address('192.0.2.130')))
208 ... #doctest: +NORMALIZE_WHITESPACE
Nick Coghlandc9b2552012-05-20 21:01:57 +1000209 [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'),
Eli Bendersky948af232012-10-07 07:23:50 -0700210 IPv4Network('192.0.2.130/32')]
Nick Coghlandc9b2552012-05-20 21:01:57 +1000211
212 Args:
213 first: the first IPv4Address or IPv6Address in the range.
214 last: the last IPv4Address or IPv6Address in the range.
215
216 Returns:
217 An iterator of the summarized IPv(4|6) network objects.
218
219 Raise:
220 TypeError:
221 If the first and last objects are not IP addresses.
222 If the first and last objects are not the same version.
223 ValueError:
224 If the last object is not greater than the first.
Nick Coghlan51c30672012-05-27 00:25:58 +1000225 If the version of the first address is not 4 or 6.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000226
227 """
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200228 if (not (isinstance(first, _BaseAddress) and
229 isinstance(last, _BaseAddress))):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000230 raise TypeError('first and last must be IP addresses, not networks')
231 if first.version != last.version:
232 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000233 first, last))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000234 if first > last:
235 raise ValueError('last IP address must be greater than first')
236
Nick Coghlandc9b2552012-05-20 21:01:57 +1000237 if first.version == 4:
238 ip = IPv4Network
239 elif first.version == 6:
240 ip = IPv6Network
241 else:
242 raise ValueError('unknown IP version')
243
244 ip_bits = first._max_prefixlen
245 first_int = first._ip
246 last_int = last._ip
247 while first_int <= last_int:
Nick Coghlan7319f692012-07-07 21:43:30 +1000248 nbits = min(_count_righthand_zero_bits(first_int, ip_bits),
249 (last_int - first_int + 1).bit_length() - 1)
Antoine Pitrou824db302014-05-15 20:21:48 +0200250 net = ip((first_int, ip_bits - nbits))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000251 yield net
Nick Coghlan7319f692012-07-07 21:43:30 +1000252 first_int += 1 << nbits
253 if first_int - 1 == ip._ALL_ONES:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000254 break
Nick Coghlandc9b2552012-05-20 21:01:57 +1000255
Sandro Tosib95c6342012-05-23 23:17:22 +0200256
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200257def _collapse_addresses_internal(addresses):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000258 """Loops through the addresses, collapsing concurrent netblocks.
259
260 Example:
261
262 ip1 = IPv4Network('192.0.2.0/26')
263 ip2 = IPv4Network('192.0.2.64/26')
264 ip3 = IPv4Network('192.0.2.128/26')
265 ip4 = IPv4Network('192.0.2.192/26')
266
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200267 _collapse_addresses_internal([ip1, ip2, ip3, ip4]) ->
Nick Coghlandc9b2552012-05-20 21:01:57 +1000268 [IPv4Network('192.0.2.0/24')]
269
270 This shouldn't be called directly; it is called via
271 collapse_addresses([]).
272
273 Args:
274 addresses: A list of IPv4Network's or IPv6Network's
275
276 Returns:
277 A list of IPv4Network's or IPv6Network's depending on what we were
278 passed.
279
280 """
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200281 # First merge
282 to_merge = list(addresses)
283 subnets = {}
284 while to_merge:
285 net = to_merge.pop()
286 supernet = net.supernet()
287 existing = subnets.get(supernet)
288 if existing is None:
289 subnets[supernet] = net
290 elif existing != net:
291 # Merge consecutive subnets
292 del subnets[supernet]
293 to_merge.append(supernet)
294 # Then iterate over resulting networks, skipping subsumed subnets
295 last = None
296 for net in sorted(subnets.values()):
297 if last is not None:
298 # Since they are sorted, last.network_address <= net.network_address
299 # is a given.
300 if last.broadcast_address >= net.broadcast_address:
301 continue
302 yield net
303 last = net
Nick Coghlandc9b2552012-05-20 21:01:57 +1000304
305
306def collapse_addresses(addresses):
307 """Collapse a list of IP objects.
308
309 Example:
310 collapse_addresses([IPv4Network('192.0.2.0/25'),
311 IPv4Network('192.0.2.128/25')]) ->
312 [IPv4Network('192.0.2.0/24')]
313
314 Args:
315 addresses: An iterator of IPv4Network or IPv6Network objects.
316
317 Returns:
318 An iterator of the collapsed IPv(4|6)Network objects.
319
320 Raises:
321 TypeError: If passed a list of mixed version objects.
322
323 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000324 addrs = []
325 ips = []
326 nets = []
327
328 # split IP addresses and networks
329 for ip in addresses:
330 if isinstance(ip, _BaseAddress):
331 if ips and ips[-1]._version != ip._version:
332 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000333 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000334 ips.append(ip)
335 elif ip._prefixlen == ip._max_prefixlen:
336 if ips and ips[-1]._version != ip._version:
337 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000338 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000339 try:
340 ips.append(ip.ip)
341 except AttributeError:
342 ips.append(ip.network_address)
343 else:
344 if nets and nets[-1]._version != ip._version:
345 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000346 ip, nets[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000347 nets.append(ip)
348
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200349 # sort and dedup
350 ips = sorted(set(ips))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000351
Antoine Pitroue6f250e2015-01-18 16:22:47 +0100352 # find consecutive address ranges in the sorted sequence and summarize them
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200353 if ips:
354 for first, last in _find_address_range(ips):
355 addrs.extend(summarize_address_range(first, last))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000356
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200357 return _collapse_addresses_internal(addrs + nets)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000358
359
360def get_mixed_type_key(obj):
361 """Return a key suitable for sorting between networks and addresses.
362
363 Address and Network objects are not sortable by default; they're
364 fundamentally different so the expression
365
366 IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
367
368 doesn't make any sense. There are some times however, where you may wish
369 to have ipaddress sort these for you anyway. If you need to do this, you
370 can use this function as the key= argument to sorted().
371
372 Args:
373 obj: either a Network or Address object.
374 Returns:
375 appropriate key.
376
377 """
378 if isinstance(obj, _BaseNetwork):
379 return obj._get_networks_key()
380 elif isinstance(obj, _BaseAddress):
381 return obj._get_address_key()
382 return NotImplemented
383
384
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200385class _IPAddressBase:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000386
387 """The mother class."""
388
Serhiy Storchaka88f64f32015-03-07 20:08:34 +0200389 __slots__ = ()
390
Nick Coghlandc9b2552012-05-20 21:01:57 +1000391 @property
392 def exploded(self):
393 """Return the longhand version of the IP address as a string."""
394 return self._explode_shorthand_ip_string()
395
396 @property
397 def compressed(self):
398 """Return the shorthand version of the IP address as a string."""
399 return str(self)
400
Nick Coghland9722652012-06-17 16:33:00 +1000401 @property
Eric V. Smithebdaaf42014-04-14 12:58:07 -0400402 def reverse_pointer(self):
403 """The name of the reverse DNS pointer for the IP address, e.g.:
404 >>> ipaddress.ip_address("127.0.0.1").reverse_pointer
405 '1.0.0.127.in-addr.arpa'
406 >>> ipaddress.ip_address("2001:db8::1").reverse_pointer
407 '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa'
408
409 """
410 return self._reverse_pointer()
411
412 @property
Nick Coghland9722652012-06-17 16:33:00 +1000413 def version(self):
414 msg = '%200s has no version specified' % (type(self),)
415 raise NotImplementedError(msg)
416
Nick Coghlan297b1432012-07-08 17:11:04 +1000417 def _check_int_address(self, address):
418 if address < 0:
419 msg = "%d (< 0) is not permitted as an IPv%d address"
420 raise AddressValueError(msg % (address, self._version))
421 if address > self._ALL_ONES:
422 msg = "%d (>= 2**%d) is not permitted as an IPv%d address"
423 raise AddressValueError(msg % (address, self._max_prefixlen,
424 self._version))
425
426 def _check_packed_address(self, address, expected_len):
427 address_len = len(address)
428 if address_len != expected_len:
429 msg = "%r (len %d != %d) is not permitted as an IPv%d address"
430 raise AddressValueError(msg % (address, address_len,
431 expected_len, self._version))
432
Antoine Pitrou45aba182014-05-15 20:18:41 +0200433 @classmethod
434 def _ip_int_from_prefix(cls, prefixlen):
Nick Coghlan932346f2014-02-08 23:17:36 +1000435 """Turn the prefix length into a bitwise netmask
Nick Coghlandc9b2552012-05-20 21:01:57 +1000436
437 Args:
438 prefixlen: An integer, the prefix length.
439
440 Returns:
441 An integer.
442
443 """
Antoine Pitrou45aba182014-05-15 20:18:41 +0200444 return cls._ALL_ONES ^ (cls._ALL_ONES >> prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000445
Antoine Pitrou45aba182014-05-15 20:18:41 +0200446 @classmethod
447 def _prefix_from_ip_int(cls, ip_int):
Nick Coghlan932346f2014-02-08 23:17:36 +1000448 """Return prefix length from the bitwise netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000449
450 Args:
Berker Peksagf23530f2014-10-19 18:04:38 +0300451 ip_int: An integer, the netmask in expanded bitwise format
Nick Coghlandc9b2552012-05-20 21:01:57 +1000452
453 Returns:
454 An integer, the prefix length.
455
Nick Coghlan932346f2014-02-08 23:17:36 +1000456 Raises:
457 ValueError: If the input intermingles zeroes & ones
Nick Coghlandc9b2552012-05-20 21:01:57 +1000458 """
Nick Coghlan932346f2014-02-08 23:17:36 +1000459 trailing_zeroes = _count_righthand_zero_bits(ip_int,
Antoine Pitrou45aba182014-05-15 20:18:41 +0200460 cls._max_prefixlen)
461 prefixlen = cls._max_prefixlen - trailing_zeroes
Nick Coghlan932346f2014-02-08 23:17:36 +1000462 leading_ones = ip_int >> trailing_zeroes
463 all_ones = (1 << prefixlen) - 1
464 if leading_ones != all_ones:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200465 byteslen = cls._max_prefixlen // 8
Nick Coghlan932346f2014-02-08 23:17:36 +1000466 details = ip_int.to_bytes(byteslen, 'big')
467 msg = 'Netmask pattern %r mixes zeroes & ones'
468 raise ValueError(msg % details)
469 return prefixlen
Nick Coghlandc9b2552012-05-20 21:01:57 +1000470
Antoine Pitrou45aba182014-05-15 20:18:41 +0200471 @classmethod
472 def _report_invalid_netmask(cls, netmask_str):
Nick Coghlan932346f2014-02-08 23:17:36 +1000473 msg = '%r is not a valid netmask' % netmask_str
474 raise NetmaskValueError(msg) from None
475
Antoine Pitrou45aba182014-05-15 20:18:41 +0200476 @classmethod
477 def _prefix_from_prefix_string(cls, prefixlen_str):
Nick Coghlan932346f2014-02-08 23:17:36 +1000478 """Return prefix length from a numeric string
Nick Coghlandc9b2552012-05-20 21:01:57 +1000479
480 Args:
Nick Coghlan932346f2014-02-08 23:17:36 +1000481 prefixlen_str: The string to be converted
Nick Coghlandc9b2552012-05-20 21:01:57 +1000482
483 Returns:
Nick Coghlan932346f2014-02-08 23:17:36 +1000484 An integer, the prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000485
Nick Coghlan932346f2014-02-08 23:17:36 +1000486 Raises:
487 NetmaskValueError: If the input is not a valid netmask
Nick Coghlandc9b2552012-05-20 21:01:57 +1000488 """
Nick Coghlan932346f2014-02-08 23:17:36 +1000489 # int allows a leading +/- as well as surrounding whitespace,
490 # so we ensure that isn't the case
INADA Naoki58a10962018-02-23 20:02:41 +0900491 if not (prefixlen_str.isascii() and prefixlen_str.isdigit()):
Antoine Pitrou45aba182014-05-15 20:18:41 +0200492 cls._report_invalid_netmask(prefixlen_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000493 try:
494 prefixlen = int(prefixlen_str)
495 except ValueError:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200496 cls._report_invalid_netmask(prefixlen_str)
497 if not (0 <= prefixlen <= cls._max_prefixlen):
498 cls._report_invalid_netmask(prefixlen_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000499 return prefixlen
500
Antoine Pitrou45aba182014-05-15 20:18:41 +0200501 @classmethod
502 def _prefix_from_ip_string(cls, ip_str):
Nick Coghlan932346f2014-02-08 23:17:36 +1000503 """Turn a netmask/hostmask string into a prefix length
504
505 Args:
506 ip_str: The netmask/hostmask to be converted
507
508 Returns:
509 An integer, the prefix length.
510
511 Raises:
512 NetmaskValueError: If the input is not a valid netmask/hostmask
513 """
514 # Parse the netmask/hostmask like an IP address.
515 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200516 ip_int = cls._ip_int_from_string(ip_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000517 except AddressValueError:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200518 cls._report_invalid_netmask(ip_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000519
520 # Try matching a netmask (this would be /1*0*/ as a bitwise regexp).
521 # Note that the two ambiguous cases (all-ones and all-zeroes) are
522 # treated as netmasks.
523 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200524 return cls._prefix_from_ip_int(ip_int)
Nick Coghlan932346f2014-02-08 23:17:36 +1000525 except ValueError:
526 pass
527
528 # Invert the bits, and try matching a /0+1+/ hostmask instead.
Antoine Pitrou45aba182014-05-15 20:18:41 +0200529 ip_int ^= cls._ALL_ONES
Nick Coghlan932346f2014-02-08 23:17:36 +1000530 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200531 return cls._prefix_from_ip_int(ip_int)
Nick Coghlan932346f2014-02-08 23:17:36 +1000532 except ValueError:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200533 cls._report_invalid_netmask(ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000534
Inada Naoki6fa84bd2019-04-16 08:32:28 +0900535 @classmethod
536 def _split_addr_prefix(cls, address):
537 """Helper function to parse address of Network/Interface.
538
539 Arg:
540 address: Argument of Network/Interface.
541
542 Returns:
543 (addr, prefix) tuple.
544 """
545 # a packed address or integer
546 if isinstance(address, (bytes, int)):
547 return address, cls._max_prefixlen
548
549 if not isinstance(address, tuple):
550 # Assume input argument to be string or any object representation
551 # which converts into a formatted IP prefix string.
552 address = _split_optional_netmask(address)
553
554 # Constructing from a tuple (addr, [mask])
555 if len(address) > 1:
556 return address
557 return address[0], cls._max_prefixlen
558
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +0200559 def __reduce__(self):
560 return self.__class__, (str(self),)
561
Nick Coghlan730f67f2012-08-05 22:02:18 +1000562
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200563@functools.total_ordering
Nick Coghlandc9b2552012-05-20 21:01:57 +1000564class _BaseAddress(_IPAddressBase):
565
566 """A generic IP object.
567
568 This IP class contains the version independent methods which are
569 used by single IP addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000570 """
571
Serhiy Storchaka88f64f32015-03-07 20:08:34 +0200572 __slots__ = ()
573
Nick Coghlandc9b2552012-05-20 21:01:57 +1000574 def __int__(self):
575 return self._ip
576
Nick Coghlandc9b2552012-05-20 21:01:57 +1000577 def __eq__(self, other):
578 try:
579 return (self._ip == other._ip
580 and self._version == other._version)
581 except AttributeError:
582 return NotImplemented
583
Nick Coghlandc9b2552012-05-20 21:01:57 +1000584 def __lt__(self, other):
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200585 if not isinstance(other, _BaseAddress):
586 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000587 if self._version != other._version:
588 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000589 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000590 if self._ip != other._ip:
591 return self._ip < other._ip
592 return False
593
Nick Coghlandc9b2552012-05-20 21:01:57 +1000594 # Shorthand for Integer addition and subtraction. This is not
595 # meant to ever support addition/subtraction of addresses.
596 def __add__(self, other):
597 if not isinstance(other, int):
598 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000599 return self.__class__(int(self) + other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000600
601 def __sub__(self, other):
602 if not isinstance(other, int):
603 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000604 return self.__class__(int(self) - other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000605
606 def __repr__(self):
607 return '%s(%r)' % (self.__class__.__name__, str(self))
608
609 def __str__(self):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200610 return str(self._string_from_ip_int(self._ip))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000611
612 def __hash__(self):
613 return hash(hex(int(self._ip)))
614
615 def _get_address_key(self):
616 return (self._version, self)
617
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +0200618 def __reduce__(self):
619 return self.__class__, (self._ip,)
620
ewosbornef9c95a42019-09-12 05:03:31 -0400621 def __format__(self, fmt):
622 """Returns an IP address as a formatted string.
623
624 Supported presentation types are:
625 's': returns the IP address as a string (default)
626 'b' or 'n': converts to binary and returns a zero-padded string
627 'X' or 'x': converts to upper- or lower-case hex and returns a zero-padded string
628
629 For binary and hex presentation types, the alternate form specifier
630 '#' and the grouping option '_' are supported.
631 """
632
633
634 # Support string formatting
635 if not fmt or fmt[-1] == 's':
636 # let format() handle it
637 return format(str(self), fmt)
638
639 # From here on down, support for 'bnXx'
640
641 import re
642 fmt_re = '^(?P<alternate>#?)(?P<grouping>_?)(?P<fmt_base>[xbnX]){1}$'
643 m = re.match(fmt_re, fmt)
644 if not m:
645 return super().__format__(fmt)
646
647 groupdict = m.groupdict()
648 alternate = groupdict['alternate']
649 grouping = groupdict['grouping']
650 fmt_base = groupdict['fmt_base']
651
652 # Set some defaults
653 if fmt_base == 'n':
654 if self._version == 4:
655 fmt_base = 'b' # Binary is default for ipv4
656 if self._version == 6:
657 fmt_base = 'x' # Hex is default for ipv6
658
659 # Handle binary formatting
660 if fmt_base == 'b':
661 if self._version == 4:
662 # resulting string is '0b' + 32 bits
663 # plus 7 _ if needed
664 padlen = IPV4LENGTH+2 + (7*len(grouping))
665 elif self._version == 6:
666 # resulting string is '0b' + 128 bits
667 # plus 31 _ if needed
668 padlen = IPV6LENGTH+2 + (31*len(grouping))
669
670 # Handle hex formatting
671 elif fmt_base in 'Xx':
672 if self._version == 4:
673 # resulting string is '0x' + 8 hex digits
674 # plus a single _ if needed
675 padlen = int(IPV4LENGTH/4)+2 + len(grouping)
676 elif self._version == 6:
677 # resulting string is '0x' + 32 hex digits
678 # plus 7 _ if needed
679 padlen = int(IPV6LENGTH/4)+2 + (7*len(grouping))
680
681 retstr = f'{int(self):#0{padlen}{grouping}{fmt_base}}'
682
683 if fmt_base == 'X':
684 retstr = retstr.upper()
685
686 # If alternate is not set, strip the two leftmost
687 # characters ('0b')
688 if not alternate:
689 retstr = retstr[2:]
690
691 return retstr
692
Nick Coghlandc9b2552012-05-20 21:01:57 +1000693
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200694@functools.total_ordering
Nick Coghlandc9b2552012-05-20 21:01:57 +1000695class _BaseNetwork(_IPAddressBase):
Nick Coghlan51c30672012-05-27 00:25:58 +1000696 """A generic IP network object.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000697
698 This IP class contains the version independent methods which are
699 used by networks.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000700 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000701
Nick Coghlandc9b2552012-05-20 21:01:57 +1000702 def __repr__(self):
703 return '%s(%r)' % (self.__class__.__name__, str(self))
704
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200705 def __str__(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000706 return '%s/%d' % (self.network_address, self.prefixlen)
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200707
Nick Coghlandc9b2552012-05-20 21:01:57 +1000708 def hosts(self):
709 """Generate Iterator over usable hosts in a network.
710
Sandro Tosib95c6342012-05-23 23:17:22 +0200711 This is like __iter__ except it doesn't return the network
712 or broadcast addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000713
714 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000715 network = int(self.network_address)
716 broadcast = int(self.broadcast_address)
717 for x in range(network + 1, broadcast):
718 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000719
720 def __iter__(self):
Nick Coghlan7319f692012-07-07 21:43:30 +1000721 network = int(self.network_address)
722 broadcast = int(self.broadcast_address)
723 for x in range(network, broadcast + 1):
724 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000725
726 def __getitem__(self, n):
727 network = int(self.network_address)
728 broadcast = int(self.broadcast_address)
729 if n >= 0:
730 if network + n > broadcast:
Berker Peksag28dc1182016-06-11 22:30:05 +0300731 raise IndexError('address out of range')
Nick Coghlan51c30672012-05-27 00:25:58 +1000732 return self._address_class(network + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000733 else:
734 n += 1
735 if broadcast + n < network:
Berker Peksag28dc1182016-06-11 22:30:05 +0300736 raise IndexError('address out of range')
Nick Coghlan51c30672012-05-27 00:25:58 +1000737 return self._address_class(broadcast + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000738
739 def __lt__(self, other):
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200740 if not isinstance(other, _BaseNetwork):
741 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000742 if self._version != other._version:
743 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000744 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000745 if self.network_address != other.network_address:
746 return self.network_address < other.network_address
747 if self.netmask != other.netmask:
748 return self.netmask < other.netmask
749 return False
750
Nick Coghlandc9b2552012-05-20 21:01:57 +1000751 def __eq__(self, other):
Nick Coghlan9a9c28c2012-07-07 23:05:59 +1000752 try:
753 return (self._version == other._version and
754 self.network_address == other.network_address and
755 int(self.netmask) == int(other.netmask))
756 except AttributeError:
757 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000758
Nick Coghlandc9b2552012-05-20 21:01:57 +1000759 def __hash__(self):
760 return hash(int(self.network_address) ^ int(self.netmask))
761
762 def __contains__(self, other):
763 # always false if one is v4 and the other is v6.
764 if self._version != other._version:
765 return False
766 # dealing with another network.
767 if isinstance(other, _BaseNetwork):
768 return False
769 # dealing with another address
770 else:
771 # address
gescheit3bbcc922019-04-30 10:54:30 +0300772 return other._ip & self.netmask._ip == self.network_address._ip
Nick Coghlandc9b2552012-05-20 21:01:57 +1000773
774 def overlaps(self, other):
775 """Tell if self is partly contained in other."""
776 return self.network_address in other or (
777 self.broadcast_address in other or (
778 other.network_address in self or (
779 other.broadcast_address in self)))
780
Inada Naoki2430d532019-04-15 16:01:00 +0900781 @functools.cached_property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000782 def broadcast_address(self):
Inada Naoki2430d532019-04-15 16:01:00 +0900783 return self._address_class(int(self.network_address) |
784 int(self.hostmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000785
Inada Naoki2430d532019-04-15 16:01:00 +0900786 @functools.cached_property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000787 def hostmask(self):
Inada Naoki2430d532019-04-15 16:01:00 +0900788 return self._address_class(int(self.netmask) ^ self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000789
790 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000791 def with_prefixlen(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000792 return '%s/%d' % (self.network_address, self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000793
794 @property
795 def with_netmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000796 return '%s/%s' % (self.network_address, self.netmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000797
798 @property
799 def with_hostmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000800 return '%s/%s' % (self.network_address, self.hostmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000801
802 @property
803 def num_addresses(self):
804 """Number of hosts in the current subnet."""
805 return int(self.broadcast_address) - int(self.network_address) + 1
806
807 @property
Nick Coghlan51c30672012-05-27 00:25:58 +1000808 def _address_class(self):
Nick Coghland9722652012-06-17 16:33:00 +1000809 # Returning bare address objects (rather than interfaces) allows for
810 # more consistent behaviour across the network address, broadcast
811 # address and individual host addresses.
812 msg = '%200s has no associated address class' % (type(self),)
813 raise NotImplementedError(msg)
Nick Coghlan51c30672012-05-27 00:25:58 +1000814
815 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000816 def prefixlen(self):
817 return self._prefixlen
818
819 def address_exclude(self, other):
820 """Remove an address from a larger block.
821
822 For example:
823
824 addr1 = ip_network('192.0.2.0/28')
825 addr2 = ip_network('192.0.2.1/32')
Serhiy Storchakabb0dbd52016-03-01 10:25:45 +0200826 list(addr1.address_exclude(addr2)) =
Nick Coghlandc9b2552012-05-20 21:01:57 +1000827 [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
Serhiy Storchakabb0dbd52016-03-01 10:25:45 +0200828 IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
Nick Coghlandc9b2552012-05-20 21:01:57 +1000829
830 or IPv6:
831
832 addr1 = ip_network('2001:db8::1/32')
833 addr2 = ip_network('2001:db8::1/128')
Serhiy Storchakabb0dbd52016-03-01 10:25:45 +0200834 list(addr1.address_exclude(addr2)) =
Nick Coghlandc9b2552012-05-20 21:01:57 +1000835 [ip_network('2001:db8::1/128'),
Serhiy Storchakabb0dbd52016-03-01 10:25:45 +0200836 ip_network('2001:db8::2/127'),
837 ip_network('2001:db8::4/126'),
838 ip_network('2001:db8::8/125'),
839 ...
840 ip_network('2001:db8:8000::/33')]
Nick Coghlandc9b2552012-05-20 21:01:57 +1000841
842 Args:
843 other: An IPv4Network or IPv6Network object of the same type.
844
845 Returns:
Ezio Melotti3f5db392013-01-27 06:20:14 +0200846 An iterator of the IPv(4|6)Network objects which is self
Nick Coghlandc9b2552012-05-20 21:01:57 +1000847 minus other.
848
849 Raises:
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300850 TypeError: If self and other are of differing address
Nick Coghlandc9b2552012-05-20 21:01:57 +1000851 versions, or if other is not a network object.
852 ValueError: If other is not completely contained by self.
853
854 """
855 if not self._version == other._version:
856 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000857 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000858
859 if not isinstance(other, _BaseNetwork):
Nick Coghlan912238e2012-07-07 13:34:50 +1000860 raise TypeError("%s is not a network object" % other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000861
Cheryl Sabella91dc64b2017-10-22 17:39:49 -0400862 if not other.subnet_of(self):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200863 raise ValueError('%s not contained in %s' % (other, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000864 if other == self:
Raymond Hettingerbb6c0aa2014-11-22 22:14:41 -0800865 return
Nick Coghlandc9b2552012-05-20 21:01:57 +1000866
Nick Coghlandc9b2552012-05-20 21:01:57 +1000867 # Make sure we're comparing the network of other.
Nick Coghlan912238e2012-07-07 13:34:50 +1000868 other = other.__class__('%s/%s' % (other.network_address,
869 other.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000870
871 s1, s2 = self.subnets()
872 while s1 != other and s2 != other:
Cheryl Sabella91dc64b2017-10-22 17:39:49 -0400873 if other.subnet_of(s1):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000874 yield s2
875 s1, s2 = s1.subnets()
Cheryl Sabella91dc64b2017-10-22 17:39:49 -0400876 elif other.subnet_of(s2):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000877 yield s1
878 s1, s2 = s2.subnets()
879 else:
880 # If we got here, there's a bug somewhere.
881 raise AssertionError('Error performing exclusion: '
882 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000883 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000884 if s1 == other:
885 yield s2
886 elif s2 == other:
887 yield s1
888 else:
889 # If we got here, there's a bug somewhere.
890 raise AssertionError('Error performing exclusion: '
891 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000892 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000893
894 def compare_networks(self, other):
895 """Compare two IP objects.
896
897 This is only concerned about the comparison of the integer
898 representation of the network addresses. This means that the
899 host bits aren't considered at all in this method. If you want
900 to compare host bits, you can easily enough do a
901 'HostA._ip < HostB._ip'
902
903 Args:
904 other: An IP object.
905
906 Returns:
907 If the IP versions of self and other are the same, returns:
908
909 -1 if self < other:
910 eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
911 IPv6Network('2001:db8::1000/124') <
912 IPv6Network('2001:db8::2000/124')
913 0 if self == other
914 eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
915 IPv6Network('2001:db8::1000/124') ==
916 IPv6Network('2001:db8::1000/124')
917 1 if self > other
918 eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
919 IPv6Network('2001:db8::2000/124') >
920 IPv6Network('2001:db8::1000/124')
921
922 Raises:
923 TypeError if the IP versions are different.
924
925 """
926 # does this need to raise a ValueError?
927 if self._version != other._version:
928 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000929 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000930 # self._version == other._version below here:
931 if self.network_address < other.network_address:
932 return -1
933 if self.network_address > other.network_address:
934 return 1
935 # self.network_address == other.network_address below here:
936 if self.netmask < other.netmask:
937 return -1
938 if self.netmask > other.netmask:
939 return 1
940 return 0
941
942 def _get_networks_key(self):
943 """Network-only key function.
944
945 Returns an object that identifies this address' network and
946 netmask. This function is a suitable "key" argument for sorted()
947 and list.sort().
948
949 """
950 return (self._version, self.network_address, self.netmask)
951
952 def subnets(self, prefixlen_diff=1, new_prefix=None):
953 """The subnets which join to make the current subnet.
954
955 In the case that self contains only one IP
956 (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
957 for IPv6), yield an iterator with just ourself.
958
959 Args:
960 prefixlen_diff: An integer, the amount the prefix length
961 should be increased by. This should not be set if
962 new_prefix is also set.
963 new_prefix: The desired new prefix length. This must be a
964 larger number (smaller prefix) than the existing prefix.
965 This should not be set if prefixlen_diff is also set.
966
967 Returns:
968 An iterator of IPv(4|6) objects.
969
970 Raises:
971 ValueError: The prefixlen_diff is too small or too large.
972 OR
973 prefixlen_diff and new_prefix are both set or new_prefix
974 is a smaller number than the current prefix (smaller
975 number means a larger network)
976
977 """
978 if self._prefixlen == self._max_prefixlen:
979 yield self
980 return
981
982 if new_prefix is not None:
983 if new_prefix < self._prefixlen:
984 raise ValueError('new prefix must be longer')
985 if prefixlen_diff != 1:
986 raise ValueError('cannot set prefixlen_diff and new_prefix')
987 prefixlen_diff = new_prefix - self._prefixlen
988
989 if prefixlen_diff < 0:
990 raise ValueError('prefix length diff must be > 0')
991 new_prefixlen = self._prefixlen + prefixlen_diff
992
Nick Coghlan932346f2014-02-08 23:17:36 +1000993 if new_prefixlen > self._max_prefixlen:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000994 raise ValueError(
995 'prefix length diff %d is invalid for netblock %s' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000996 new_prefixlen, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000997
Antoine Pitrou824db302014-05-15 20:21:48 +0200998 start = int(self.network_address)
Serhiy Storchakabb0dbd52016-03-01 10:25:45 +0200999 end = int(self.broadcast_address) + 1
Antoine Pitrou824db302014-05-15 20:21:48 +02001000 step = (int(self.hostmask) + 1) >> prefixlen_diff
1001 for new_addr in range(start, end, step):
1002 current = self.__class__((new_addr, new_prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001003 yield current
1004
Nick Coghlandc9b2552012-05-20 21:01:57 +10001005 def supernet(self, prefixlen_diff=1, new_prefix=None):
1006 """The supernet containing the current network.
1007
1008 Args:
1009 prefixlen_diff: An integer, the amount the prefix length of
1010 the network should be decreased by. For example, given a
1011 /24 network and a prefixlen_diff of 3, a supernet with a
1012 /21 netmask is returned.
1013
1014 Returns:
1015 An IPv4 network object.
1016
1017 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001018 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
1019 a negative prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001020 OR
1021 If prefixlen_diff and new_prefix are both set or new_prefix is a
1022 larger number than the current prefix (larger number means a
1023 smaller network)
1024
1025 """
1026 if self._prefixlen == 0:
1027 return self
1028
1029 if new_prefix is not None:
1030 if new_prefix > self._prefixlen:
1031 raise ValueError('new prefix must be shorter')
1032 if prefixlen_diff != 1:
1033 raise ValueError('cannot set prefixlen_diff and new_prefix')
1034 prefixlen_diff = self._prefixlen - new_prefix
1035
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001036 new_prefixlen = self.prefixlen - prefixlen_diff
1037 if new_prefixlen < 0:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001038 raise ValueError(
1039 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
1040 (self.prefixlen, prefixlen_diff))
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001041 return self.__class__((
1042 int(self.network_address) & (int(self.netmask) << prefixlen_diff),
1043 new_prefixlen
1044 ))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001045
Nick Coghlan730f67f2012-08-05 22:02:18 +10001046 @property
1047 def is_multicast(self):
1048 """Test if the address is reserved for multicast use.
1049
1050 Returns:
1051 A boolean, True if the address is a multicast address.
1052 See RFC 2373 2.7 for details.
1053
1054 """
1055 return (self.network_address.is_multicast and
1056 self.broadcast_address.is_multicast)
1057
Cheryl Sabella91dc64b2017-10-22 17:39:49 -04001058 @staticmethod
1059 def _is_subnet_of(a, b):
1060 try:
1061 # Always false if one is v4 and the other is v6.
1062 if a._version != b._version:
1063 raise TypeError(f"{a} and {b} are not of the same version")
1064 return (b.network_address <= a.network_address and
1065 b.broadcast_address >= a.broadcast_address)
1066 except AttributeError:
1067 raise TypeError(f"Unable to test subnet containment "
1068 f"between {a} and {b}")
1069
1070 def subnet_of(self, other):
1071 """Return True if this network is a subnet of other."""
1072 return self._is_subnet_of(self, other)
1073
1074 def supernet_of(self, other):
1075 """Return True if this network is a supernet of other."""
1076 return self._is_subnet_of(other, self)
1077
Nick Coghlan730f67f2012-08-05 22:02:18 +10001078 @property
1079 def is_reserved(self):
1080 """Test if the address is otherwise IETF reserved.
1081
1082 Returns:
1083 A boolean, True if the address is within one of the
1084 reserved IPv6 Network ranges.
1085
1086 """
1087 return (self.network_address.is_reserved and
1088 self.broadcast_address.is_reserved)
1089
1090 @property
1091 def is_link_local(self):
1092 """Test if the address is reserved for link-local.
1093
1094 Returns:
1095 A boolean, True if the address is reserved per RFC 4291.
1096
1097 """
1098 return (self.network_address.is_link_local and
1099 self.broadcast_address.is_link_local)
1100
1101 @property
1102 def is_private(self):
1103 """Test if this address is allocated for private networks.
1104
1105 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001106 A boolean, True if the address is reserved per
1107 iana-ipv4-special-registry or iana-ipv6-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001108
1109 """
1110 return (self.network_address.is_private and
1111 self.broadcast_address.is_private)
1112
1113 @property
Peter Moody22c31762013-10-21 13:58:06 -07001114 def is_global(self):
Peter Moodybe9c1b12013-10-22 12:36:21 -07001115 """Test if this address is allocated for public networks.
Peter Moody22c31762013-10-21 13:58:06 -07001116
1117 Returns:
1118 A boolean, True if the address is not reserved per
1119 iana-ipv4-special-registry or iana-ipv6-special-registry.
1120
1121 """
1122 return not self.is_private
1123
1124 @property
Nick Coghlan730f67f2012-08-05 22:02:18 +10001125 def is_unspecified(self):
1126 """Test if the address is unspecified.
1127
1128 Returns:
1129 A boolean, True if this is the unspecified address as defined in
1130 RFC 2373 2.5.2.
1131
1132 """
1133 return (self.network_address.is_unspecified and
1134 self.broadcast_address.is_unspecified)
1135
1136 @property
1137 def is_loopback(self):
1138 """Test if the address is a loopback address.
1139
1140 Returns:
1141 A boolean, True if the address is a loopback address as defined in
1142 RFC 2373 2.5.3.
1143
1144 """
1145 return (self.network_address.is_loopback and
1146 self.broadcast_address.is_loopback)
1147
Nick Coghlandc9b2552012-05-20 21:01:57 +10001148
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001149class _BaseV4:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001150
1151 """Base IPv4 object.
1152
1153 The following methods are used by IPv4 objects in both single IP
1154 addresses and networks.
1155
1156 """
1157
Serhiy Storchaka88f64f32015-03-07 20:08:34 +02001158 __slots__ = ()
1159 _version = 4
Nick Coghlandc9b2552012-05-20 21:01:57 +10001160 # Equivalent to 255.255.255.255 or 32 bits of 1's.
1161 _ALL_ONES = (2**IPV4LENGTH) - 1
Nick Coghlandc9b2552012-05-20 21:01:57 +10001162
Antoine Pitrou45aba182014-05-15 20:18:41 +02001163 _max_prefixlen = IPV4LENGTH
1164 # There are only a handful of valid v4 netmasks, so we cache them all
1165 # when constructed (see _make_netmask()).
1166 _netmask_cache = {}
1167
Nick Coghlandc9b2552012-05-20 21:01:57 +10001168 def _explode_shorthand_ip_string(self):
1169 return str(self)
1170
Antoine Pitrou45aba182014-05-15 20:18:41 +02001171 @classmethod
1172 def _make_netmask(cls, arg):
1173 """Make a (netmask, prefix_len) tuple from the given argument.
1174
1175 Argument can be:
1176 - an integer (the prefix length)
1177 - a string representing the prefix length (e.g. "24")
1178 - a string representing the prefix netmask (e.g. "255.255.255.0")
1179 """
1180 if arg not in cls._netmask_cache:
1181 if isinstance(arg, int):
1182 prefixlen = arg
Nicolai Moore5e48e3d2019-05-14 20:32:59 +10001183 if not (0 <= prefixlen <= cls._max_prefixlen):
1184 cls._report_invalid_netmask(prefixlen)
Antoine Pitrou45aba182014-05-15 20:18:41 +02001185 else:
1186 try:
1187 # Check for a netmask in prefix length form
1188 prefixlen = cls._prefix_from_prefix_string(arg)
1189 except NetmaskValueError:
1190 # Check for a netmask or hostmask in dotted-quad form.
1191 # This may raise NetmaskValueError.
1192 prefixlen = cls._prefix_from_ip_string(arg)
1193 netmask = IPv4Address(cls._ip_int_from_prefix(prefixlen))
1194 cls._netmask_cache[arg] = netmask, prefixlen
1195 return cls._netmask_cache[arg]
1196
1197 @classmethod
1198 def _ip_int_from_string(cls, ip_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001199 """Turn the given IP string into an integer for comparison.
1200
1201 Args:
1202 ip_str: A string, the IP ip_str.
1203
1204 Returns:
1205 The IP ip_str as an integer.
1206
1207 Raises:
1208 AddressValueError: if ip_str isn't a valid IPv4 Address.
1209
1210 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001211 if not ip_str:
1212 raise AddressValueError('Address cannot be empty')
1213
Nick Coghlandc9b2552012-05-20 21:01:57 +10001214 octets = ip_str.split('.')
1215 if len(octets) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001216 raise AddressValueError("Expected 4 octets in %r" % ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001217
Nick Coghlan7319f692012-07-07 21:43:30 +10001218 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001219 return int.from_bytes(map(cls._parse_octet, octets), 'big')
Nick Coghlan7319f692012-07-07 21:43:30 +10001220 except ValueError as exc:
1221 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001222
Antoine Pitrou45aba182014-05-15 20:18:41 +02001223 @classmethod
1224 def _parse_octet(cls, octet_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001225 """Convert a decimal octet into an integer.
1226
1227 Args:
1228 octet_str: A string, the number to parse.
1229
1230 Returns:
1231 The octet as an integer.
1232
1233 Raises:
1234 ValueError: if the octet isn't strictly a decimal from [0..255].
1235
1236 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001237 if not octet_str:
1238 raise ValueError("Empty octet not permitted")
Nick Coghlandc9b2552012-05-20 21:01:57 +10001239 # Whitelist the characters, since int() allows a lot of bizarre stuff.
INADA Naoki58a10962018-02-23 20:02:41 +09001240 if not (octet_str.isascii() and octet_str.isdigit()):
Nick Coghlan07c4e332012-07-08 23:06:45 +10001241 msg = "Only decimal digits permitted in %r"
1242 raise ValueError(msg % octet_str)
1243 # We do the length check second, since the invalid character error
1244 # is likely to be more informative for the user
1245 if len(octet_str) > 3:
1246 msg = "At most 3 characters permitted in %r"
1247 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001248 # Convert to integer (we know digits are legal)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001249 octet_int = int(octet_str, 10)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001250 if octet_int > 255:
Nick Coghlanb582ecc2012-07-07 22:15:22 +10001251 raise ValueError("Octet %d (> 255) not permitted" % octet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001252 return octet_int
1253
Antoine Pitrou45aba182014-05-15 20:18:41 +02001254 @classmethod
1255 def _string_from_ip_int(cls, ip_int):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001256 """Turns a 32-bit integer into dotted decimal notation.
1257
1258 Args:
1259 ip_int: An integer, the IP address.
1260
1261 Returns:
1262 The IP address as a string in dotted decimal notation.
1263
1264 """
Nick Coghlan7319f692012-07-07 21:43:30 +10001265 return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001266
Eric V. Smithebdaaf42014-04-14 12:58:07 -04001267 def _reverse_pointer(self):
1268 """Return the reverse DNS pointer name for the IPv4 address.
1269
1270 This implements the method described in RFC1035 3.5.
1271
1272 """
1273 reverse_octets = str(self).split('.')[::-1]
1274 return '.'.join(reverse_octets) + '.in-addr.arpa'
1275
Nick Coghlandc9b2552012-05-20 21:01:57 +10001276 @property
1277 def max_prefixlen(self):
1278 return self._max_prefixlen
1279
1280 @property
1281 def version(self):
1282 return self._version
1283
Nick Coghlandc9b2552012-05-20 21:01:57 +10001284
1285class IPv4Address(_BaseV4, _BaseAddress):
1286
1287 """Represent and manipulate single IPv4 Addresses."""
1288
Serhiy Storchaka88f64f32015-03-07 20:08:34 +02001289 __slots__ = ('_ip', '__weakref__')
1290
Nick Coghlandc9b2552012-05-20 21:01:57 +10001291 def __init__(self, address):
1292
1293 """
1294 Args:
1295 address: A string or integer representing the IP
1296
1297 Additionally, an integer can be passed, so
1298 IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1299 or, more generally
1300 IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1301 IPv4Address('192.0.2.1')
1302
1303 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001304 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001305
1306 """
Nick Coghlandc9b2552012-05-20 21:01:57 +10001307 # Efficient constructor from integer.
1308 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001309 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001310 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001311 return
1312
1313 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001314 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001315 self._check_packed_address(address, 4)
Nick Coghlandb7920b2012-08-20 10:19:12 +10001316 self._ip = int.from_bytes(address, 'big')
Nick Coghlandc9b2552012-05-20 21:01:57 +10001317 return
1318
1319 # Assume input argument to be string or any object representation
1320 # which converts into a formatted IP string.
1321 addr_str = str(address)
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +02001322 if '/' in addr_str:
1323 raise AddressValueError("Unexpected '/' in %r" % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001324 self._ip = self._ip_int_from_string(addr_str)
1325
1326 @property
1327 def packed(self):
1328 """The binary representation of this address."""
1329 return v4_int_to_packed(self._ip)
1330
Nick Coghlan730f67f2012-08-05 22:02:18 +10001331 @property
1332 def is_reserved(self):
1333 """Test if the address is otherwise IETF reserved.
1334
1335 Returns:
1336 A boolean, True if the address is within the
1337 reserved IPv4 Network range.
1338
1339 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001340 return self in self._constants._reserved_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001341
1342 @property
Peter Moodybe9c1b12013-10-22 12:36:21 -07001343 @functools.lru_cache()
Nick Coghlan730f67f2012-08-05 22:02:18 +10001344 def is_private(self):
1345 """Test if this address is allocated for private networks.
1346
1347 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001348 A boolean, True if the address is reserved per
1349 iana-ipv4-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001350
1351 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001352 return any(self in net for net in self._constants._private_networks)
Nick Coghlan730f67f2012-08-05 22:02:18 +10001353
1354 @property
Berker Peksag742192a2016-06-11 22:11:47 +03001355 @functools.lru_cache()
1356 def is_global(self):
1357 return self not in self._constants._public_network and not self.is_private
1358
1359 @property
Nick Coghlan730f67f2012-08-05 22:02:18 +10001360 def is_multicast(self):
1361 """Test if the address is reserved for multicast use.
1362
1363 Returns:
1364 A boolean, True if the address is multicast.
1365 See RFC 3171 for details.
1366
1367 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001368 return self in self._constants._multicast_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001369
1370 @property
1371 def is_unspecified(self):
1372 """Test if the address is unspecified.
1373
1374 Returns:
1375 A boolean, True if this is the unspecified address as defined in
1376 RFC 5735 3.
1377
1378 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001379 return self == self._constants._unspecified_address
Nick Coghlan730f67f2012-08-05 22:02:18 +10001380
1381 @property
1382 def is_loopback(self):
1383 """Test if the address is a loopback address.
1384
1385 Returns:
1386 A boolean, True if the address is a loopback per RFC 3330.
1387
1388 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001389 return self in self._constants._loopback_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001390
1391 @property
1392 def is_link_local(self):
1393 """Test if the address is reserved for link-local.
1394
1395 Returns:
1396 A boolean, True if the address is link-local per RFC 3927.
1397
1398 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001399 return self in self._constants._linklocal_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001400
Nick Coghlandc9b2552012-05-20 21:01:57 +10001401
1402class IPv4Interface(IPv4Address):
1403
Nick Coghlandc9b2552012-05-20 21:01:57 +10001404 def __init__(self, address):
Inada Naoki6fa84bd2019-04-16 08:32:28 +09001405 addr, mask = self._split_addr_prefix(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001406
Inada Naoki6fa84bd2019-04-16 08:32:28 +09001407 IPv4Address.__init__(self, addr)
1408 self.network = IPv4Network((addr, mask), strict=False)
1409 self.netmask = self.network.netmask
Nick Coghlandc9b2552012-05-20 21:01:57 +10001410 self._prefixlen = self.network._prefixlen
1411
Inada Naoki6fa84bd2019-04-16 08:32:28 +09001412 @functools.cached_property
1413 def hostmask(self):
1414 return self.network.hostmask
Nick Coghlandc9b2552012-05-20 21:01:57 +10001415
Nick Coghlandc9b2552012-05-20 21:01:57 +10001416 def __str__(self):
1417 return '%s/%d' % (self._string_from_ip_int(self._ip),
Inada Naoki2430d532019-04-15 16:01:00 +09001418 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001419
1420 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001421 address_equal = IPv4Address.__eq__(self, other)
1422 if not address_equal or address_equal is NotImplemented:
1423 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001424 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001425 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001426 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001427 # An interface with an associated network is NOT the
1428 # same as an unassociated address. That's why the hash
1429 # takes the extra info into account.
1430 return False
1431
1432 def __lt__(self, other):
1433 address_less = IPv4Address.__lt__(self, other)
1434 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001435 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001436 try:
s-sanjay7bd8d3e2017-03-31 23:09:53 -07001437 return (self.network < other.network or
1438 self.network == other.network and address_less)
Nick Coghlan3008ec02012-07-08 00:45:33 +10001439 except AttributeError:
1440 # We *do* allow addresses and interfaces to be sorted. The
1441 # unassociated address is considered less than all interfaces.
1442 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001443
1444 def __hash__(self):
1445 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1446
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +02001447 __reduce__ = _IPAddressBase.__reduce__
1448
Nick Coghlandc9b2552012-05-20 21:01:57 +10001449 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001450 def ip(self):
1451 return IPv4Address(self._ip)
1452
1453 @property
1454 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10001455 return '%s/%s' % (self._string_from_ip_int(self._ip),
1456 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001457
1458 @property
1459 def with_netmask(self):
1460 return '%s/%s' % (self._string_from_ip_int(self._ip),
1461 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001462
Nick Coghlandc9b2552012-05-20 21:01:57 +10001463 @property
1464 def with_hostmask(self):
1465 return '%s/%s' % (self._string_from_ip_int(self._ip),
1466 self.hostmask)
1467
1468
1469class IPv4Network(_BaseV4, _BaseNetwork):
1470
1471 """This class represents and manipulates 32-bit IPv4 network + addresses..
1472
1473 Attributes: [examples for IPv4Network('192.0.2.0/27')]
1474 .network_address: IPv4Address('192.0.2.0')
1475 .hostmask: IPv4Address('0.0.0.31')
1476 .broadcast_address: IPv4Address('192.0.2.32')
1477 .netmask: IPv4Address('255.255.255.224')
1478 .prefixlen: 27
1479
1480 """
Nick Coghlan51c30672012-05-27 00:25:58 +10001481 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001482 _address_class = IPv4Address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001483
Nick Coghlandc9b2552012-05-20 21:01:57 +10001484 def __init__(self, address, strict=True):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001485 """Instantiate a new IPv4 network object.
1486
1487 Args:
1488 address: A string or integer representing the IP [& network].
1489 '192.0.2.0/24'
1490 '192.0.2.0/255.255.255.0'
1491 '192.0.0.2/0.0.0.255'
1492 are all functionally the same in IPv4. Similarly,
1493 '192.0.2.1'
1494 '192.0.2.1/255.255.255.255'
1495 '192.0.2.1/32'
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001496 are also functionally equivalent. That is to say, failing to
Nick Coghlandc9b2552012-05-20 21:01:57 +10001497 provide a subnetmask will create an object with a mask of /32.
1498
1499 If the mask (portion after the / in the argument) is given in
1500 dotted quad form, it is treated as a netmask if it starts with a
1501 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1502 starts with a zero field (e.g. 0.255.255.255 == /8), with the
1503 single exception of an all-zero mask which is treated as a
1504 netmask == /0. If no mask is given, a default of /32 is used.
1505
1506 Additionally, an integer can be passed, so
1507 IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1508 or, more generally
1509 IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1510 IPv4Interface('192.0.2.1')
1511
1512 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001513 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001514 NetmaskValueError: If the netmask isn't valid for
1515 an IPv4 address.
Sandro Tosib4386d32012-06-02 17:14:22 +02001516 ValueError: If strict is True and a network address is not
Nick Coghlandc9b2552012-05-20 21:01:57 +10001517 supplied.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001518 """
Inada Naoki6fa84bd2019-04-16 08:32:28 +09001519 addr, mask = self._split_addr_prefix(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001520
Xiang Zhang10b134a2018-03-21 08:25:13 +08001521 self.network_address = IPv4Address(addr)
1522 self.netmask, self._prefixlen = self._make_netmask(mask)
1523 packed = int(self.network_address)
1524 if packed & int(self.netmask) != packed:
1525 if strict:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001526 raise ValueError('%s has host bits set' % self)
Xiang Zhang10b134a2018-03-21 08:25:13 +08001527 else:
1528 self.network_address = IPv4Address(packed &
1529 int(self.netmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001530
1531 if self._prefixlen == (self._max_prefixlen - 1):
1532 self.hosts = self.__iter__
1533
Peter Moodye5019d52013-10-24 09:47:10 -07001534 @property
1535 @functools.lru_cache()
1536 def is_global(self):
1537 """Test if this address is allocated for public networks.
1538
1539 Returns:
1540 A boolean, True if the address is not reserved per
1541 iana-ipv4-special-registry.
1542
1543 """
1544 return (not (self.network_address in IPv4Network('100.64.0.0/10') and
1545 self.broadcast_address in IPv4Network('100.64.0.0/10')) and
1546 not self.is_private)
1547
1548
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001549class _IPv4Constants:
1550 _linklocal_network = IPv4Network('169.254.0.0/16')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001551
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001552 _loopback_network = IPv4Network('127.0.0.0/8')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001553
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001554 _multicast_network = IPv4Network('224.0.0.0/4')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001555
Berker Peksag742192a2016-06-11 22:11:47 +03001556 _public_network = IPv4Network('100.64.0.0/10')
1557
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001558 _private_networks = [
1559 IPv4Network('0.0.0.0/8'),
1560 IPv4Network('10.0.0.0/8'),
1561 IPv4Network('127.0.0.0/8'),
1562 IPv4Network('169.254.0.0/16'),
1563 IPv4Network('172.16.0.0/12'),
1564 IPv4Network('192.0.0.0/29'),
1565 IPv4Network('192.0.0.170/31'),
1566 IPv4Network('192.0.2.0/24'),
1567 IPv4Network('192.168.0.0/16'),
1568 IPv4Network('198.18.0.0/15'),
1569 IPv4Network('198.51.100.0/24'),
1570 IPv4Network('203.0.113.0/24'),
1571 IPv4Network('240.0.0.0/4'),
1572 IPv4Network('255.255.255.255/32'),
1573 ]
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001574
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001575 _reserved_network = IPv4Network('240.0.0.0/4')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001576
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001577 _unspecified_address = IPv4Address('0.0.0.0')
1578
1579
1580IPv4Address._constants = _IPv4Constants
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001581
Nick Coghlandc9b2552012-05-20 21:01:57 +10001582
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001583class _BaseV6:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001584
1585 """Base IPv6 object.
1586
1587 The following methods are used by IPv6 objects in both single IP
1588 addresses and networks.
1589
1590 """
1591
Serhiy Storchaka88f64f32015-03-07 20:08:34 +02001592 __slots__ = ()
1593 _version = 6
Nick Coghlandc9b2552012-05-20 21:01:57 +10001594 _ALL_ONES = (2**IPV6LENGTH) - 1
1595 _HEXTET_COUNT = 8
1596 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
Antoine Pitrou45aba182014-05-15 20:18:41 +02001597 _max_prefixlen = IPV6LENGTH
1598
1599 # There are only a bunch of valid v6 netmasks, so we cache them all
1600 # when constructed (see _make_netmask()).
1601 _netmask_cache = {}
Nick Coghlandc9b2552012-05-20 21:01:57 +10001602
Antoine Pitrou45aba182014-05-15 20:18:41 +02001603 @classmethod
1604 def _make_netmask(cls, arg):
1605 """Make a (netmask, prefix_len) tuple from the given argument.
1606
1607 Argument can be:
1608 - an integer (the prefix length)
1609 - a string representing the prefix length (e.g. "24")
1610 - a string representing the prefix netmask (e.g. "255.255.255.0")
1611 """
1612 if arg not in cls._netmask_cache:
1613 if isinstance(arg, int):
1614 prefixlen = arg
Nicolai Moore5e48e3d2019-05-14 20:32:59 +10001615 if not (0 <= prefixlen <= cls._max_prefixlen):
1616 cls._report_invalid_netmask(prefixlen)
Antoine Pitrou45aba182014-05-15 20:18:41 +02001617 else:
1618 prefixlen = cls._prefix_from_prefix_string(arg)
1619 netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen))
1620 cls._netmask_cache[arg] = netmask, prefixlen
1621 return cls._netmask_cache[arg]
1622
1623 @classmethod
1624 def _ip_int_from_string(cls, ip_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001625 """Turn an IPv6 ip_str into an integer.
1626
1627 Args:
1628 ip_str: A string, the IPv6 ip_str.
1629
1630 Returns:
1631 An int, the IPv6 address
1632
1633 Raises:
1634 AddressValueError: if ip_str isn't a valid IPv6 Address.
1635
1636 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001637 if not ip_str:
1638 raise AddressValueError('Address cannot be empty')
1639
Nick Coghlandc9b2552012-05-20 21:01:57 +10001640 parts = ip_str.split(':')
1641
1642 # An IPv6 address needs at least 2 colons (3 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001643 _min_parts = 3
1644 if len(parts) < _min_parts:
1645 msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
1646 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001647
1648 # If the address has an IPv4-style suffix, convert it to hexadecimal.
1649 if '.' in parts[-1]:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001650 try:
1651 ipv4_int = IPv4Address(parts.pop())._ip
1652 except AddressValueError as exc:
1653 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001654 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1655 parts.append('%x' % (ipv4_int & 0xFFFF))
1656
1657 # An IPv6 address can't have more than 8 colons (9 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001658 # The extra colon comes from using the "::" notation for a single
1659 # leading or trailing zero part.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001660 _max_parts = cls._HEXTET_COUNT + 1
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001661 if len(parts) > _max_parts:
1662 msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
1663 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001664
1665 # Disregarding the endpoints, find '::' with nothing in between.
1666 # This indicates that a run of zeroes has been skipped.
Nick Coghlan7319f692012-07-07 21:43:30 +10001667 skip_index = None
1668 for i in range(1, len(parts) - 1):
1669 if not parts[i]:
1670 if skip_index is not None:
1671 # Can't have more than one '::'
1672 msg = "At most one '::' permitted in %r" % ip_str
1673 raise AddressValueError(msg)
1674 skip_index = i
Nick Coghlandc9b2552012-05-20 21:01:57 +10001675
1676 # parts_hi is the number of parts to copy from above/before the '::'
1677 # parts_lo is the number of parts to copy from below/after the '::'
1678 if skip_index is not None:
1679 # If we found a '::', then check if it also covers the endpoints.
1680 parts_hi = skip_index
1681 parts_lo = len(parts) - skip_index - 1
1682 if not parts[0]:
1683 parts_hi -= 1
1684 if parts_hi:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001685 msg = "Leading ':' only permitted as part of '::' in %r"
1686 raise AddressValueError(msg % ip_str) # ^: requires ^::
Nick Coghlandc9b2552012-05-20 21:01:57 +10001687 if not parts[-1]:
1688 parts_lo -= 1
1689 if parts_lo:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001690 msg = "Trailing ':' only permitted as part of '::' in %r"
1691 raise AddressValueError(msg % ip_str) # :$ requires ::$
Antoine Pitrou45aba182014-05-15 20:18:41 +02001692 parts_skipped = cls._HEXTET_COUNT - (parts_hi + parts_lo)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001693 if parts_skipped < 1:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001694 msg = "Expected at most %d other parts with '::' in %r"
Antoine Pitrou45aba182014-05-15 20:18:41 +02001695 raise AddressValueError(msg % (cls._HEXTET_COUNT-1, ip_str))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001696 else:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001697 # Otherwise, allocate the entire address to parts_hi. The
1698 # endpoints could still be empty, but _parse_hextet() will check
1699 # for that.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001700 if len(parts) != cls._HEXTET_COUNT:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001701 msg = "Exactly %d parts expected without '::' in %r"
Antoine Pitrou45aba182014-05-15 20:18:41 +02001702 raise AddressValueError(msg % (cls._HEXTET_COUNT, ip_str))
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001703 if not parts[0]:
1704 msg = "Leading ':' only permitted as part of '::' in %r"
1705 raise AddressValueError(msg % ip_str) # ^: requires ^::
1706 if not parts[-1]:
1707 msg = "Trailing ':' only permitted as part of '::' in %r"
1708 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001709 parts_hi = len(parts)
1710 parts_lo = 0
1711 parts_skipped = 0
1712
1713 try:
1714 # Now, parse the hextets into a 128-bit integer.
1715 ip_int = 0
1716 for i in range(parts_hi):
1717 ip_int <<= 16
Antoine Pitrou45aba182014-05-15 20:18:41 +02001718 ip_int |= cls._parse_hextet(parts[i])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001719 ip_int <<= 16 * parts_skipped
1720 for i in range(-parts_lo, 0):
1721 ip_int <<= 16
Antoine Pitrou45aba182014-05-15 20:18:41 +02001722 ip_int |= cls._parse_hextet(parts[i])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001723 return ip_int
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001724 except ValueError as exc:
1725 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001726
Antoine Pitrou45aba182014-05-15 20:18:41 +02001727 @classmethod
1728 def _parse_hextet(cls, hextet_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001729 """Convert an IPv6 hextet string into an integer.
1730
1731 Args:
1732 hextet_str: A string, the number to parse.
1733
1734 Returns:
1735 The hextet as an integer.
1736
1737 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001738 ValueError: if the input isn't strictly a hex number from
1739 [0..FFFF].
Nick Coghlandc9b2552012-05-20 21:01:57 +10001740
1741 """
1742 # Whitelist the characters, since int() allows a lot of bizarre stuff.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001743 if not cls._HEX_DIGITS.issuperset(hextet_str):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001744 raise ValueError("Only hex digits permitted in %r" % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001745 # We do the length check second, since the invalid character error
1746 # is likely to be more informative for the user
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001747 if len(hextet_str) > 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001748 msg = "At most 4 characters permitted in %r"
1749 raise ValueError(msg % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001750 # Length check means we can skip checking the integer value
1751 return int(hextet_str, 16)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001752
Antoine Pitrou45aba182014-05-15 20:18:41 +02001753 @classmethod
1754 def _compress_hextets(cls, hextets):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001755 """Compresses a list of hextets.
1756
1757 Compresses a list of strings, replacing the longest continuous
1758 sequence of "0" in the list with "" and adding empty strings at
1759 the beginning or at the end of the string such that subsequently
1760 calling ":".join(hextets) will produce the compressed version of
1761 the IPv6 address.
1762
1763 Args:
1764 hextets: A list of strings, the hextets to compress.
1765
1766 Returns:
1767 A list of strings.
1768
1769 """
1770 best_doublecolon_start = -1
1771 best_doublecolon_len = 0
1772 doublecolon_start = -1
1773 doublecolon_len = 0
Nick Coghlandb7920b2012-08-20 10:19:12 +10001774 for index, hextet in enumerate(hextets):
1775 if hextet == '0':
Nick Coghlandc9b2552012-05-20 21:01:57 +10001776 doublecolon_len += 1
1777 if doublecolon_start == -1:
1778 # Start of a sequence of zeros.
1779 doublecolon_start = index
1780 if doublecolon_len > best_doublecolon_len:
1781 # This is the longest sequence of zeros so far.
1782 best_doublecolon_len = doublecolon_len
1783 best_doublecolon_start = doublecolon_start
1784 else:
1785 doublecolon_len = 0
1786 doublecolon_start = -1
1787
1788 if best_doublecolon_len > 1:
1789 best_doublecolon_end = (best_doublecolon_start +
1790 best_doublecolon_len)
1791 # For zeros at the end of the address.
1792 if best_doublecolon_end == len(hextets):
1793 hextets += ['']
1794 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1795 # For zeros at the beginning of the address.
1796 if best_doublecolon_start == 0:
1797 hextets = [''] + hextets
1798
1799 return hextets
1800
Antoine Pitrou45aba182014-05-15 20:18:41 +02001801 @classmethod
1802 def _string_from_ip_int(cls, ip_int=None):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001803 """Turns a 128-bit integer into hexadecimal notation.
1804
1805 Args:
1806 ip_int: An integer, the IP address.
1807
1808 Returns:
1809 A string, the hexadecimal representation of the address.
1810
1811 Raises:
1812 ValueError: The address is bigger than 128 bits of all ones.
1813
1814 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001815 if ip_int is None:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001816 ip_int = int(cls._ip)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001817
Antoine Pitrou45aba182014-05-15 20:18:41 +02001818 if ip_int > cls._ALL_ONES:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001819 raise ValueError('IPv6 address is too large')
1820
1821 hex_str = '%032x' % ip_int
Nick Coghlan7319f692012-07-07 21:43:30 +10001822 hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001823
Antoine Pitrou45aba182014-05-15 20:18:41 +02001824 hextets = cls._compress_hextets(hextets)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001825 return ':'.join(hextets)
1826
1827 def _explode_shorthand_ip_string(self):
1828 """Expand a shortened IPv6 address.
1829
1830 Args:
1831 ip_str: A string, the IPv6 address.
1832
1833 Returns:
1834 A string, the expanded IPv6 address.
1835
1836 """
1837 if isinstance(self, IPv6Network):
1838 ip_str = str(self.network_address)
1839 elif isinstance(self, IPv6Interface):
1840 ip_str = str(self.ip)
1841 else:
1842 ip_str = str(self)
1843
1844 ip_int = self._ip_int_from_string(ip_str)
Nick Coghlan7319f692012-07-07 21:43:30 +10001845 hex_str = '%032x' % ip_int
1846 parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001847 if isinstance(self, (_BaseNetwork, IPv6Interface)):
Nick Coghlane3ded952012-08-05 22:45:22 +10001848 return '%s/%d' % (':'.join(parts), self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001849 return ':'.join(parts)
1850
Eric V. Smithebdaaf42014-04-14 12:58:07 -04001851 def _reverse_pointer(self):
1852 """Return the reverse DNS pointer name for the IPv6 address.
1853
1854 This implements the method described in RFC3596 2.5.
1855
1856 """
1857 reverse_chars = self.exploded[::-1].replace(':', '')
1858 return '.'.join(reverse_chars) + '.ip6.arpa'
1859
Nick Coghlandc9b2552012-05-20 21:01:57 +10001860 @property
1861 def max_prefixlen(self):
1862 return self._max_prefixlen
1863
1864 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001865 def version(self):
1866 return self._version
1867
Nick Coghlandc9b2552012-05-20 21:01:57 +10001868
1869class IPv6Address(_BaseV6, _BaseAddress):
1870
Sandro Tosib95c6342012-05-23 23:17:22 +02001871 """Represent and manipulate single IPv6 Addresses."""
Nick Coghlandc9b2552012-05-20 21:01:57 +10001872
Serhiy Storchaka88f64f32015-03-07 20:08:34 +02001873 __slots__ = ('_ip', '__weakref__')
1874
Nick Coghlandc9b2552012-05-20 21:01:57 +10001875 def __init__(self, address):
1876 """Instantiate a new IPv6 address object.
1877
1878 Args:
1879 address: A string or integer representing the IP
1880
1881 Additionally, an integer can be passed, so
1882 IPv6Address('2001:db8::') ==
1883 IPv6Address(42540766411282592856903984951653826560)
1884 or, more generally
1885 IPv6Address(int(IPv6Address('2001:db8::'))) ==
1886 IPv6Address('2001:db8::')
1887
1888 Raises:
1889 AddressValueError: If address isn't a valid IPv6 address.
1890
1891 """
Nick Coghlandc9b2552012-05-20 21:01:57 +10001892 # Efficient constructor from integer.
1893 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001894 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001895 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001896 return
1897
1898 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001899 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001900 self._check_packed_address(address, 16)
Nick Coghlandb7920b2012-08-20 10:19:12 +10001901 self._ip = int.from_bytes(address, 'big')
Nick Coghlandc9b2552012-05-20 21:01:57 +10001902 return
1903
1904 # Assume input argument to be string or any object representation
1905 # which converts into a formatted IP string.
1906 addr_str = str(address)
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +02001907 if '/' in addr_str:
1908 raise AddressValueError("Unexpected '/' in %r" % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001909 self._ip = self._ip_int_from_string(addr_str)
1910
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001911 @property
1912 def packed(self):
1913 """The binary representation of this address."""
1914 return v6_int_to_packed(self._ip)
1915
Nick Coghlan730f67f2012-08-05 22:02:18 +10001916 @property
1917 def is_multicast(self):
1918 """Test if the address is reserved for multicast use.
1919
1920 Returns:
1921 A boolean, True if the address is a multicast address.
1922 See RFC 2373 2.7 for details.
1923
1924 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001925 return self in self._constants._multicast_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001926
1927 @property
1928 def is_reserved(self):
1929 """Test if the address is otherwise IETF reserved.
1930
1931 Returns:
1932 A boolean, True if the address is within one of the
1933 reserved IPv6 Network ranges.
1934
1935 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001936 return any(self in x for x in self._constants._reserved_networks)
Nick Coghlan730f67f2012-08-05 22:02:18 +10001937
1938 @property
1939 def is_link_local(self):
1940 """Test if the address is reserved for link-local.
1941
1942 Returns:
1943 A boolean, True if the address is reserved per RFC 4291.
1944
1945 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001946 return self in self._constants._linklocal_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001947
1948 @property
1949 def is_site_local(self):
1950 """Test if the address is reserved for site-local.
1951
1952 Note that the site-local address space has been deprecated by RFC 3879.
1953 Use is_private to test if this address is in the space of unique local
1954 addresses as defined by RFC 4193.
1955
1956 Returns:
1957 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1958
1959 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001960 return self in self._constants._sitelocal_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001961
1962 @property
Peter Moodybe9c1b12013-10-22 12:36:21 -07001963 @functools.lru_cache()
Nick Coghlan730f67f2012-08-05 22:02:18 +10001964 def is_private(self):
1965 """Test if this address is allocated for private networks.
1966
1967 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001968 A boolean, True if the address is reserved per
1969 iana-ipv6-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001970
1971 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001972 return any(self in net for net in self._constants._private_networks)
Peter Moody22c31762013-10-21 13:58:06 -07001973
1974 @property
1975 def is_global(self):
1976 """Test if this address is allocated for public networks.
1977
1978 Returns:
1979 A boolean, true if the address is not reserved per
1980 iana-ipv6-special-registry.
1981
1982 """
1983 return not self.is_private
Nick Coghlan730f67f2012-08-05 22:02:18 +10001984
1985 @property
1986 def is_unspecified(self):
1987 """Test if the address is unspecified.
1988
1989 Returns:
1990 A boolean, True if this is the unspecified address as defined in
1991 RFC 2373 2.5.2.
1992
1993 """
1994 return self._ip == 0
1995
1996 @property
1997 def is_loopback(self):
1998 """Test if the address is a loopback address.
1999
2000 Returns:
2001 A boolean, True if the address is a loopback address as defined in
2002 RFC 2373 2.5.3.
2003
2004 """
2005 return self._ip == 1
2006
2007 @property
2008 def ipv4_mapped(self):
2009 """Return the IPv4 mapped address.
2010
2011 Returns:
2012 If the IPv6 address is a v4 mapped address, return the
2013 IPv4 mapped address. Return None otherwise.
2014
2015 """
2016 if (self._ip >> 32) != 0xFFFF:
2017 return None
2018 return IPv4Address(self._ip & 0xFFFFFFFF)
2019
2020 @property
2021 def teredo(self):
2022 """Tuple of embedded teredo IPs.
2023
2024 Returns:
2025 Tuple of the (server, client) IPs or None if the address
2026 doesn't appear to be a teredo address (doesn't start with
2027 2001::/32)
2028
2029 """
2030 if (self._ip >> 96) != 0x20010000:
2031 return None
2032 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
2033 IPv4Address(~self._ip & 0xFFFFFFFF))
2034
2035 @property
2036 def sixtofour(self):
2037 """Return the IPv4 6to4 embedded address.
2038
2039 Returns:
2040 The IPv4 6to4-embedded address if present or None if the
2041 address doesn't appear to contain a 6to4 embedded address.
2042
2043 """
2044 if (self._ip >> 112) != 0x2002:
2045 return None
2046 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
2047
Nick Coghlandc9b2552012-05-20 21:01:57 +10002048
2049class IPv6Interface(IPv6Address):
2050
2051 def __init__(self, address):
Inada Naoki6fa84bd2019-04-16 08:32:28 +09002052 addr, mask = self._split_addr_prefix(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002053
Inada Naoki6fa84bd2019-04-16 08:32:28 +09002054 IPv6Address.__init__(self, addr)
2055 self.network = IPv6Network((addr, mask), strict=False)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002056 self.netmask = self.network.netmask
2057 self._prefixlen = self.network._prefixlen
Inada Naoki6fa84bd2019-04-16 08:32:28 +09002058
2059 @functools.cached_property
2060 def hostmask(self):
2061 return self.network.hostmask
Nick Coghlandc9b2552012-05-20 21:01:57 +10002062
Nick Coghlandc9b2552012-05-20 21:01:57 +10002063 def __str__(self):
2064 return '%s/%d' % (self._string_from_ip_int(self._ip),
Inada Naoki2430d532019-04-15 16:01:00 +09002065 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002066
2067 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10002068 address_equal = IPv6Address.__eq__(self, other)
2069 if not address_equal or address_equal is NotImplemented:
2070 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10002071 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10002072 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10002073 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10002074 # An interface with an associated network is NOT the
2075 # same as an unassociated address. That's why the hash
2076 # takes the extra info into account.
2077 return False
2078
2079 def __lt__(self, other):
2080 address_less = IPv6Address.__lt__(self, other)
2081 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10002082 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10002083 try:
s-sanjay7bd8d3e2017-03-31 23:09:53 -07002084 return (self.network < other.network or
2085 self.network == other.network and address_less)
Nick Coghlan3008ec02012-07-08 00:45:33 +10002086 except AttributeError:
2087 # We *do* allow addresses and interfaces to be sorted. The
2088 # unassociated address is considered less than all interfaces.
2089 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10002090
2091 def __hash__(self):
2092 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
2093
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +02002094 __reduce__ = _IPAddressBase.__reduce__
2095
Nick Coghlandc9b2552012-05-20 21:01:57 +10002096 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10002097 def ip(self):
2098 return IPv6Address(self._ip)
2099
2100 @property
2101 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10002102 return '%s/%s' % (self._string_from_ip_int(self._ip),
2103 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002104
2105 @property
2106 def with_netmask(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10002107 return '%s/%s' % (self._string_from_ip_int(self._ip),
2108 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02002109
Nick Coghlandc9b2552012-05-20 21:01:57 +10002110 @property
2111 def with_hostmask(self):
2112 return '%s/%s' % (self._string_from_ip_int(self._ip),
2113 self.hostmask)
2114
Nick Coghlan730f67f2012-08-05 22:02:18 +10002115 @property
2116 def is_unspecified(self):
2117 return self._ip == 0 and self.network.is_unspecified
2118
2119 @property
2120 def is_loopback(self):
2121 return self._ip == 1 and self.network.is_loopback
2122
Nick Coghlandc9b2552012-05-20 21:01:57 +10002123
2124class IPv6Network(_BaseV6, _BaseNetwork):
2125
2126 """This class represents and manipulates 128-bit IPv6 networks.
2127
2128 Attributes: [examples for IPv6('2001:db8::1000/124')]
2129 .network_address: IPv6Address('2001:db8::1000')
2130 .hostmask: IPv6Address('::f')
2131 .broadcast_address: IPv6Address('2001:db8::100f')
2132 .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
2133 .prefixlen: 124
2134
2135 """
2136
Nick Coghlan51c30672012-05-27 00:25:58 +10002137 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10002138 _address_class = IPv6Address
2139
Nick Coghlandc9b2552012-05-20 21:01:57 +10002140 def __init__(self, address, strict=True):
2141 """Instantiate a new IPv6 Network object.
2142
2143 Args:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02002144 address: A string or integer representing the IPv6 network or the
2145 IP and prefix/netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +10002146 '2001:db8::/128'
2147 '2001:db8:0000:0000:0000:0000:0000:0000/128'
2148 '2001:db8::'
2149 are all functionally the same in IPv6. That is to say,
2150 failing to provide a subnetmask will create an object with
2151 a mask of /128.
2152
2153 Additionally, an integer can be passed, so
2154 IPv6Network('2001:db8::') ==
2155 IPv6Network(42540766411282592856903984951653826560)
2156 or, more generally
2157 IPv6Network(int(IPv6Network('2001:db8::'))) ==
2158 IPv6Network('2001:db8::')
2159
2160 strict: A boolean. If true, ensure that we have been passed
2161 A true network address, eg, 2001:db8::1000/124 and not an
2162 IP address on a network, eg, 2001:db8::1/124.
2163
2164 Raises:
2165 AddressValueError: If address isn't a valid IPv6 address.
2166 NetmaskValueError: If the netmask isn't valid for
2167 an IPv6 address.
2168 ValueError: If strict was True and a network address was not
2169 supplied.
Nick Coghlandc9b2552012-05-20 21:01:57 +10002170 """
Inada Naoki6fa84bd2019-04-16 08:32:28 +09002171 addr, mask = self._split_addr_prefix(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002172
Xiang Zhang10b134a2018-03-21 08:25:13 +08002173 self.network_address = IPv6Address(addr)
2174 self.netmask, self._prefixlen = self._make_netmask(mask)
2175 packed = int(self.network_address)
2176 if packed & int(self.netmask) != packed:
2177 if strict:
Nick Coghlan912238e2012-07-07 13:34:50 +10002178 raise ValueError('%s has host bits set' % self)
Xiang Zhang10b134a2018-03-21 08:25:13 +08002179 else:
2180 self.network_address = IPv6Address(packed &
2181 int(self.netmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +10002182
2183 if self._prefixlen == (self._max_prefixlen - 1):
2184 self.hosts = self.__iter__
2185
Peter Moody1243c7d2014-03-11 09:55:46 -07002186 def hosts(self):
2187 """Generate Iterator over usable hosts in a network.
2188
2189 This is like __iter__ except it doesn't return the
2190 Subnet-Router anycast address.
2191
2192 """
2193 network = int(self.network_address)
2194 broadcast = int(self.broadcast_address)
2195 for x in range(network + 1, broadcast + 1):
2196 yield self._address_class(x)
2197
Nick Coghlan730f67f2012-08-05 22:02:18 +10002198 @property
2199 def is_site_local(self):
2200 """Test if the address is reserved for site-local.
2201
2202 Note that the site-local address space has been deprecated by RFC 3879.
2203 Use is_private to test if this address is in the space of unique local
2204 addresses as defined by RFC 4193.
2205
2206 Returns:
2207 A boolean, True if the address is reserved per RFC 3513 2.5.6.
2208
2209 """
2210 return (self.network_address.is_site_local and
2211 self.broadcast_address.is_site_local)
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002212
2213
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002214class _IPv6Constants:
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002215
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002216 _linklocal_network = IPv6Network('fe80::/10')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002217
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002218 _multicast_network = IPv6Network('ff00::/8')
2219
2220 _private_networks = [
2221 IPv6Network('::1/128'),
2222 IPv6Network('::/128'),
2223 IPv6Network('::ffff:0:0/96'),
2224 IPv6Network('100::/64'),
2225 IPv6Network('2001::/23'),
2226 IPv6Network('2001:2::/48'),
2227 IPv6Network('2001:db8::/32'),
2228 IPv6Network('2001:10::/28'),
2229 IPv6Network('fc00::/7'),
2230 IPv6Network('fe80::/10'),
2231 ]
2232
2233 _reserved_networks = [
2234 IPv6Network('::/8'), IPv6Network('100::/8'),
2235 IPv6Network('200::/7'), IPv6Network('400::/6'),
2236 IPv6Network('800::/5'), IPv6Network('1000::/4'),
2237 IPv6Network('4000::/3'), IPv6Network('6000::/3'),
2238 IPv6Network('8000::/3'), IPv6Network('A000::/3'),
2239 IPv6Network('C000::/3'), IPv6Network('E000::/4'),
2240 IPv6Network('F000::/5'), IPv6Network('F800::/6'),
2241 IPv6Network('FE00::/9'),
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002242 ]
2243
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002244 _sitelocal_network = IPv6Network('fec0::/10')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002245
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002246
2247IPv6Address._constants = _IPv6Constants