blob: 4a6496a5da3ef8586f98650d866986e196fdbf16 [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
Miss Islington (bot)a44bb6d2021-05-17 12:42:08 -070019
Nick Coghlandc9b2552012-05-20 21:01:57 +100020class AddressValueError(ValueError):
21 """A Value Error related to the address."""
22
23
24class NetmaskValueError(ValueError):
25 """A Value Error related to the netmask."""
26
27
Nick Coghlan51c30672012-05-27 00:25:58 +100028def ip_address(address):
Nick Coghlandc9b2552012-05-20 21:01:57 +100029 """Take an IP string/int and return an object of the correct type.
30
31 Args:
32 address: A string or integer, the IP address. Either IPv4 or
33 IPv6 addresses may be supplied; integers less than 2**32 will
34 be considered to be IPv4 by default.
Nick Coghlandc9b2552012-05-20 21:01:57 +100035
36 Returns:
37 An IPv4Address or IPv6Address object.
38
39 Raises:
Sandro Tosi876ecad2012-05-23 22:26:55 +020040 ValueError: if the *address* passed isn't either a v4 or a v6
Nick Coghlan51c30672012-05-27 00:25:58 +100041 address
Nick Coghlandc9b2552012-05-20 21:01:57 +100042
43 """
Nick Coghlandc9b2552012-05-20 21:01:57 +100044 try:
45 return IPv4Address(address)
46 except (AddressValueError, NetmaskValueError):
47 pass
48
49 try:
50 return IPv6Address(address)
51 except (AddressValueError, NetmaskValueError):
52 pass
53
54 raise ValueError('%r does not appear to be an IPv4 or IPv6 address' %
55 address)
56
57
Nick Coghlan51c30672012-05-27 00:25:58 +100058def ip_network(address, strict=True):
Nick Coghlandc9b2552012-05-20 21:01:57 +100059 """Take an IP string/int and return an object of the correct type.
60
61 Args:
62 address: A string or integer, the IP network. Either IPv4 or
63 IPv6 networks may be supplied; integers less than 2**32 will
64 be considered to be IPv4 by default.
Nick Coghlandc9b2552012-05-20 21:01:57 +100065
66 Returns:
67 An IPv4Network or IPv6Network object.
68
69 Raises:
70 ValueError: if the string passed isn't either a v4 or a v6
Nick Coghlan51c30672012-05-27 00:25:58 +100071 address. Or if the network has host bits set.
Nick Coghlandc9b2552012-05-20 21:01:57 +100072
73 """
Nick Coghlandc9b2552012-05-20 21:01:57 +100074 try:
75 return IPv4Network(address, strict)
76 except (AddressValueError, NetmaskValueError):
77 pass
78
79 try:
80 return IPv6Network(address, strict)
81 except (AddressValueError, NetmaskValueError):
82 pass
83
84 raise ValueError('%r does not appear to be an IPv4 or IPv6 network' %
85 address)
86
87
Nick Coghlan51c30672012-05-27 00:25:58 +100088def ip_interface(address):
Nick Coghlandc9b2552012-05-20 21:01:57 +100089 """Take an IP string/int and return an object of the correct type.
90
91 Args:
92 address: A string or integer, the IP address. Either IPv4 or
93 IPv6 addresses may be supplied; integers less than 2**32 will
94 be considered to be IPv4 by default.
Nick Coghlandc9b2552012-05-20 21:01:57 +100095
96 Returns:
Sandro Tosi876ecad2012-05-23 22:26:55 +020097 An IPv4Interface or IPv6Interface object.
Nick Coghlandc9b2552012-05-20 21:01:57 +100098
99 Raises:
100 ValueError: if the string passed isn't either a v4 or a v6
Nick Coghlan51c30672012-05-27 00:25:58 +1000101 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000102
103 Notes:
104 The IPv?Interface classes describe an Address on a particular
105 Network, so they're basically a combination of both the Address
106 and Network classes.
Sandro Tosib95c6342012-05-23 23:17:22 +0200107
Nick Coghlandc9b2552012-05-20 21:01:57 +1000108 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000109 try:
110 return IPv4Interface(address)
111 except (AddressValueError, NetmaskValueError):
112 pass
113
114 try:
115 return IPv6Interface(address)
116 except (AddressValueError, NetmaskValueError):
117 pass
118
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000119 raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' %
Nick Coghlandc9b2552012-05-20 21:01:57 +1000120 address)
121
122
123def v4_int_to_packed(address):
Sandro Tosi876ecad2012-05-23 22:26:55 +0200124 """Represent an address as 4 packed bytes in network (big-endian) order.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000125
126 Args:
127 address: An integer representation of an IPv4 IP address.
128
129 Returns:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200130 The integer address packed as 4 bytes in network (big-endian) order.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000131
132 Raises:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200133 ValueError: If the integer is negative or too large to be an
134 IPv4 IP address.
Sandro Tosib95c6342012-05-23 23:17:22 +0200135
Nick Coghlandc9b2552012-05-20 21:01:57 +1000136 """
Sandro Tosi876ecad2012-05-23 22:26:55 +0200137 try:
Nick Coghlandb7920b2012-08-20 10:19:12 +1000138 return address.to_bytes(4, 'big')
Serhiy Storchakaba9ac5b2015-05-20 10:33:40 +0300139 except OverflowError:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200140 raise ValueError("Address negative or too large for IPv4")
Nick Coghlandc9b2552012-05-20 21:01:57 +1000141
142
143def v6_int_to_packed(address):
Sandro Tosi876ecad2012-05-23 22:26:55 +0200144 """Represent an address as 16 packed bytes in network (big-endian) order.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000145
146 Args:
Sandro Tosib4386d32012-06-02 17:14:22 +0200147 address: An integer representation of an IPv6 IP address.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000148
149 Returns:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200150 The integer address packed as 16 bytes in network (big-endian) order.
Sandro Tosib95c6342012-05-23 23:17:22 +0200151
Nick Coghlandc9b2552012-05-20 21:01:57 +1000152 """
Sandro Tosi876ecad2012-05-23 22:26:55 +0200153 try:
Nick Coghlandb7920b2012-08-20 10:19:12 +1000154 return address.to_bytes(16, 'big')
Serhiy Storchakaba9ac5b2015-05-20 10:33:40 +0300155 except OverflowError:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200156 raise ValueError("Address negative or too large for IPv6")
Nick Coghlandc9b2552012-05-20 21:01:57 +1000157
158
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000159def _split_optional_netmask(address):
160 """Helper to split the netmask and raise AddressValueError if needed"""
161 addr = str(address).split('/')
162 if len(addr) > 2:
163 raise AddressValueError("Only one '/' permitted in %r" % address)
164 return addr
165
Nick Coghlan297b1432012-07-08 17:11:04 +1000166
Nick Coghlandc9b2552012-05-20 21:01:57 +1000167def _find_address_range(addresses):
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200168 """Find a sequence of sorted deduplicated IPv#Address.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000169
170 Args:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200171 addresses: a list of IPv#Address objects.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000172
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200173 Yields:
174 A tuple containing the first and last IP addresses in the sequence.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000175
176 """
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200177 it = iter(addresses)
178 first = last = next(it)
179 for ip in it:
180 if ip._ip != last._ip + 1:
181 yield first, last
182 first = ip
183 last = ip
184 yield first, last
Nick Coghlandc9b2552012-05-20 21:01:57 +1000185
Sandro Tosib95c6342012-05-23 23:17:22 +0200186
Nick Coghlandc9b2552012-05-20 21:01:57 +1000187def _count_righthand_zero_bits(number, bits):
188 """Count the number of zero bits on the right hand side.
189
190 Args:
191 number: an integer.
192 bits: maximum number of bits to count.
193
194 Returns:
195 The number of zero bits on the right hand side of the number.
196
197 """
198 if number == 0:
199 return bits
Antoine Pitrou824db302014-05-15 20:21:48 +0200200 return min(bits, (~number & (number-1)).bit_length())
Nick Coghlandc9b2552012-05-20 21:01:57 +1000201
202
203def summarize_address_range(first, last):
204 """Summarize a network range given the first and last IP addresses.
205
206 Example:
Eli Bendersky948af232012-10-07 07:23:50 -0700207 >>> list(summarize_address_range(IPv4Address('192.0.2.0'),
208 ... IPv4Address('192.0.2.130')))
209 ... #doctest: +NORMALIZE_WHITESPACE
Nick Coghlandc9b2552012-05-20 21:01:57 +1000210 [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'),
Eli Bendersky948af232012-10-07 07:23:50 -0700211 IPv4Network('192.0.2.130/32')]
Nick Coghlandc9b2552012-05-20 21:01:57 +1000212
213 Args:
214 first: the first IPv4Address or IPv6Address in the range.
215 last: the last IPv4Address or IPv6Address in the range.
216
217 Returns:
218 An iterator of the summarized IPv(4|6) network objects.
219
220 Raise:
221 TypeError:
222 If the first and last objects are not IP addresses.
223 If the first and last objects are not the same version.
224 ValueError:
225 If the last object is not greater than the first.
Nick Coghlan51c30672012-05-27 00:25:58 +1000226 If the version of the first address is not 4 or 6.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000227
228 """
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200229 if (not (isinstance(first, _BaseAddress) and
230 isinstance(last, _BaseAddress))):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000231 raise TypeError('first and last must be IP addresses, not networks')
232 if first.version != last.version:
233 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000234 first, last))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000235 if first > last:
236 raise ValueError('last IP address must be greater than first')
237
Nick Coghlandc9b2552012-05-20 21:01:57 +1000238 if first.version == 4:
239 ip = IPv4Network
240 elif first.version == 6:
241 ip = IPv6Network
242 else:
243 raise ValueError('unknown IP version')
244
245 ip_bits = first._max_prefixlen
246 first_int = first._ip
247 last_int = last._ip
248 while first_int <= last_int:
Nick Coghlan7319f692012-07-07 21:43:30 +1000249 nbits = min(_count_righthand_zero_bits(first_int, ip_bits),
250 (last_int - first_int + 1).bit_length() - 1)
Antoine Pitrou824db302014-05-15 20:21:48 +0200251 net = ip((first_int, ip_bits - nbits))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000252 yield net
Nick Coghlan7319f692012-07-07 21:43:30 +1000253 first_int += 1 << nbits
254 if first_int - 1 == ip._ALL_ONES:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000255 break
Nick Coghlandc9b2552012-05-20 21:01:57 +1000256
Sandro Tosib95c6342012-05-23 23:17:22 +0200257
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200258def _collapse_addresses_internal(addresses):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000259 """Loops through the addresses, collapsing concurrent netblocks.
260
261 Example:
262
263 ip1 = IPv4Network('192.0.2.0/26')
264 ip2 = IPv4Network('192.0.2.64/26')
265 ip3 = IPv4Network('192.0.2.128/26')
266 ip4 = IPv4Network('192.0.2.192/26')
267
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200268 _collapse_addresses_internal([ip1, ip2, ip3, ip4]) ->
Nick Coghlandc9b2552012-05-20 21:01:57 +1000269 [IPv4Network('192.0.2.0/24')]
270
271 This shouldn't be called directly; it is called via
272 collapse_addresses([]).
273
274 Args:
275 addresses: A list of IPv4Network's or IPv6Network's
276
277 Returns:
278 A list of IPv4Network's or IPv6Network's depending on what we were
279 passed.
280
281 """
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200282 # First merge
283 to_merge = list(addresses)
284 subnets = {}
285 while to_merge:
286 net = to_merge.pop()
287 supernet = net.supernet()
288 existing = subnets.get(supernet)
289 if existing is None:
290 subnets[supernet] = net
291 elif existing != net:
292 # Merge consecutive subnets
293 del subnets[supernet]
294 to_merge.append(supernet)
295 # Then iterate over resulting networks, skipping subsumed subnets
296 last = None
297 for net in sorted(subnets.values()):
298 if last is not None:
299 # Since they are sorted, last.network_address <= net.network_address
300 # is a given.
301 if last.broadcast_address >= net.broadcast_address:
302 continue
303 yield net
304 last = net
Nick Coghlandc9b2552012-05-20 21:01:57 +1000305
306
307def collapse_addresses(addresses):
308 """Collapse a list of IP objects.
309
310 Example:
311 collapse_addresses([IPv4Network('192.0.2.0/25'),
312 IPv4Network('192.0.2.128/25')]) ->
313 [IPv4Network('192.0.2.0/24')]
314
315 Args:
316 addresses: An iterator of IPv4Network or IPv6Network objects.
317
318 Returns:
319 An iterator of the collapsed IPv(4|6)Network objects.
320
321 Raises:
322 TypeError: If passed a list of mixed version objects.
323
324 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000325 addrs = []
326 ips = []
327 nets = []
328
329 # split IP addresses and networks
330 for ip in addresses:
331 if isinstance(ip, _BaseAddress):
332 if ips and ips[-1]._version != ip._version:
333 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000334 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000335 ips.append(ip)
336 elif ip._prefixlen == ip._max_prefixlen:
337 if ips and ips[-1]._version != ip._version:
338 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000339 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000340 try:
341 ips.append(ip.ip)
342 except AttributeError:
343 ips.append(ip.network_address)
344 else:
345 if nets and nets[-1]._version != ip._version:
346 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000347 ip, nets[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000348 nets.append(ip)
349
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200350 # sort and dedup
351 ips = sorted(set(ips))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000352
Antoine Pitroue6f250e2015-01-18 16:22:47 +0100353 # find consecutive address ranges in the sorted sequence and summarize them
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200354 if ips:
355 for first, last in _find_address_range(ips):
356 addrs.extend(summarize_address_range(first, last))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000357
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200358 return _collapse_addresses_internal(addrs + nets)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000359
360
361def get_mixed_type_key(obj):
362 """Return a key suitable for sorting between networks and addresses.
363
364 Address and Network objects are not sortable by default; they're
365 fundamentally different so the expression
366
367 IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
368
369 doesn't make any sense. There are some times however, where you may wish
370 to have ipaddress sort these for you anyway. If you need to do this, you
371 can use this function as the key= argument to sorted().
372
373 Args:
374 obj: either a Network or Address object.
375 Returns:
376 appropriate key.
377
378 """
379 if isinstance(obj, _BaseNetwork):
380 return obj._get_networks_key()
381 elif isinstance(obj, _BaseAddress):
382 return obj._get_address_key()
383 return NotImplemented
384
385
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200386class _IPAddressBase:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000387
388 """The mother class."""
389
Serhiy Storchaka88f64f32015-03-07 20:08:34 +0200390 __slots__ = ()
391
Nick Coghlandc9b2552012-05-20 21:01:57 +1000392 @property
393 def exploded(self):
394 """Return the longhand version of the IP address as a string."""
395 return self._explode_shorthand_ip_string()
396
397 @property
398 def compressed(self):
399 """Return the shorthand version of the IP address as a string."""
400 return str(self)
401
Nick Coghland9722652012-06-17 16:33:00 +1000402 @property
Eric V. Smithebdaaf42014-04-14 12:58:07 -0400403 def reverse_pointer(self):
404 """The name of the reverse DNS pointer for the IP address, e.g.:
405 >>> ipaddress.ip_address("127.0.0.1").reverse_pointer
406 '1.0.0.127.in-addr.arpa'
407 >>> ipaddress.ip_address("2001:db8::1").reverse_pointer
408 '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'
409
410 """
411 return self._reverse_pointer()
412
413 @property
Nick Coghland9722652012-06-17 16:33:00 +1000414 def version(self):
415 msg = '%200s has no version specified' % (type(self),)
416 raise NotImplementedError(msg)
417
Nick Coghlan297b1432012-07-08 17:11:04 +1000418 def _check_int_address(self, address):
419 if address < 0:
420 msg = "%d (< 0) is not permitted as an IPv%d address"
421 raise AddressValueError(msg % (address, self._version))
422 if address > self._ALL_ONES:
423 msg = "%d (>= 2**%d) is not permitted as an IPv%d address"
424 raise AddressValueError(msg % (address, self._max_prefixlen,
425 self._version))
426
427 def _check_packed_address(self, address, expected_len):
428 address_len = len(address)
429 if address_len != expected_len:
430 msg = "%r (len %d != %d) is not permitted as an IPv%d address"
431 raise AddressValueError(msg % (address, address_len,
432 expected_len, self._version))
433
Antoine Pitrou45aba182014-05-15 20:18:41 +0200434 @classmethod
435 def _ip_int_from_prefix(cls, prefixlen):
Nick Coghlan932346f2014-02-08 23:17:36 +1000436 """Turn the prefix length into a bitwise netmask
Nick Coghlandc9b2552012-05-20 21:01:57 +1000437
438 Args:
439 prefixlen: An integer, the prefix length.
440
441 Returns:
442 An integer.
443
444 """
Antoine Pitrou45aba182014-05-15 20:18:41 +0200445 return cls._ALL_ONES ^ (cls._ALL_ONES >> prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000446
Antoine Pitrou45aba182014-05-15 20:18:41 +0200447 @classmethod
448 def _prefix_from_ip_int(cls, ip_int):
Nick Coghlan932346f2014-02-08 23:17:36 +1000449 """Return prefix length from the bitwise netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000450
451 Args:
Berker Peksagf23530f2014-10-19 18:04:38 +0300452 ip_int: An integer, the netmask in expanded bitwise format
Nick Coghlandc9b2552012-05-20 21:01:57 +1000453
454 Returns:
455 An integer, the prefix length.
456
Nick Coghlan932346f2014-02-08 23:17:36 +1000457 Raises:
458 ValueError: If the input intermingles zeroes & ones
Nick Coghlandc9b2552012-05-20 21:01:57 +1000459 """
Nick Coghlan932346f2014-02-08 23:17:36 +1000460 trailing_zeroes = _count_righthand_zero_bits(ip_int,
Antoine Pitrou45aba182014-05-15 20:18:41 +0200461 cls._max_prefixlen)
462 prefixlen = cls._max_prefixlen - trailing_zeroes
Nick Coghlan932346f2014-02-08 23:17:36 +1000463 leading_ones = ip_int >> trailing_zeroes
464 all_ones = (1 << prefixlen) - 1
465 if leading_ones != all_ones:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200466 byteslen = cls._max_prefixlen // 8
Nick Coghlan932346f2014-02-08 23:17:36 +1000467 details = ip_int.to_bytes(byteslen, 'big')
468 msg = 'Netmask pattern %r mixes zeroes & ones'
469 raise ValueError(msg % details)
470 return prefixlen
Nick Coghlandc9b2552012-05-20 21:01:57 +1000471
Antoine Pitrou45aba182014-05-15 20:18:41 +0200472 @classmethod
473 def _report_invalid_netmask(cls, netmask_str):
Nick Coghlan932346f2014-02-08 23:17:36 +1000474 msg = '%r is not a valid netmask' % netmask_str
475 raise NetmaskValueError(msg) from None
476
Antoine Pitrou45aba182014-05-15 20:18:41 +0200477 @classmethod
478 def _prefix_from_prefix_string(cls, prefixlen_str):
Nick Coghlan932346f2014-02-08 23:17:36 +1000479 """Return prefix length from a numeric string
Nick Coghlandc9b2552012-05-20 21:01:57 +1000480
481 Args:
Nick Coghlan932346f2014-02-08 23:17:36 +1000482 prefixlen_str: The string to be converted
Nick Coghlandc9b2552012-05-20 21:01:57 +1000483
484 Returns:
Nick Coghlan932346f2014-02-08 23:17:36 +1000485 An integer, the prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000486
Nick Coghlan932346f2014-02-08 23:17:36 +1000487 Raises:
488 NetmaskValueError: If the input is not a valid netmask
Nick Coghlandc9b2552012-05-20 21:01:57 +1000489 """
Nick Coghlan932346f2014-02-08 23:17:36 +1000490 # int allows a leading +/- as well as surrounding whitespace,
491 # so we ensure that isn't the case
INADA Naoki58a10962018-02-23 20:02:41 +0900492 if not (prefixlen_str.isascii() and prefixlen_str.isdigit()):
Antoine Pitrou45aba182014-05-15 20:18:41 +0200493 cls._report_invalid_netmask(prefixlen_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000494 try:
495 prefixlen = int(prefixlen_str)
496 except ValueError:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200497 cls._report_invalid_netmask(prefixlen_str)
498 if not (0 <= prefixlen <= cls._max_prefixlen):
499 cls._report_invalid_netmask(prefixlen_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000500 return prefixlen
501
Antoine Pitrou45aba182014-05-15 20:18:41 +0200502 @classmethod
503 def _prefix_from_ip_string(cls, ip_str):
Nick Coghlan932346f2014-02-08 23:17:36 +1000504 """Turn a netmask/hostmask string into a prefix length
505
506 Args:
507 ip_str: The netmask/hostmask to be converted
508
509 Returns:
510 An integer, the prefix length.
511
512 Raises:
513 NetmaskValueError: If the input is not a valid netmask/hostmask
514 """
515 # Parse the netmask/hostmask like an IP address.
516 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200517 ip_int = cls._ip_int_from_string(ip_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000518 except AddressValueError:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200519 cls._report_invalid_netmask(ip_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000520
521 # Try matching a netmask (this would be /1*0*/ as a bitwise regexp).
522 # Note that the two ambiguous cases (all-ones and all-zeroes) are
523 # treated as netmasks.
524 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200525 return cls._prefix_from_ip_int(ip_int)
Nick Coghlan932346f2014-02-08 23:17:36 +1000526 except ValueError:
527 pass
528
529 # Invert the bits, and try matching a /0+1+/ hostmask instead.
Antoine Pitrou45aba182014-05-15 20:18:41 +0200530 ip_int ^= cls._ALL_ONES
Nick Coghlan932346f2014-02-08 23:17:36 +1000531 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200532 return cls._prefix_from_ip_int(ip_int)
Nick Coghlan932346f2014-02-08 23:17:36 +1000533 except ValueError:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200534 cls._report_invalid_netmask(ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000535
Inada Naoki6fa84bd2019-04-16 08:32:28 +0900536 @classmethod
537 def _split_addr_prefix(cls, address):
538 """Helper function to parse address of Network/Interface.
539
540 Arg:
541 address: Argument of Network/Interface.
542
543 Returns:
544 (addr, prefix) tuple.
545 """
546 # a packed address or integer
547 if isinstance(address, (bytes, int)):
548 return address, cls._max_prefixlen
549
550 if not isinstance(address, tuple):
551 # Assume input argument to be string or any object representation
552 # which converts into a formatted IP prefix string.
553 address = _split_optional_netmask(address)
554
555 # Constructing from a tuple (addr, [mask])
556 if len(address) > 1:
557 return address
558 return address[0], cls._max_prefixlen
559
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +0200560 def __reduce__(self):
561 return self.__class__, (str(self),)
562
Nick Coghlan730f67f2012-08-05 22:02:18 +1000563
Serhiy Storchaka5d6f5b62019-09-27 20:02:58 +0300564_address_fmt_re = None
565
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200566@functools.total_ordering
Nick Coghlandc9b2552012-05-20 21:01:57 +1000567class _BaseAddress(_IPAddressBase):
568
569 """A generic IP object.
570
571 This IP class contains the version independent methods which are
572 used by single IP addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000573 """
574
Serhiy Storchaka88f64f32015-03-07 20:08:34 +0200575 __slots__ = ()
576
Nick Coghlandc9b2552012-05-20 21:01:57 +1000577 def __int__(self):
578 return self._ip
579
Nick Coghlandc9b2552012-05-20 21:01:57 +1000580 def __eq__(self, other):
581 try:
582 return (self._ip == other._ip
583 and self._version == other._version)
584 except AttributeError:
585 return NotImplemented
586
Nick Coghlandc9b2552012-05-20 21:01:57 +1000587 def __lt__(self, other):
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200588 if not isinstance(other, _BaseAddress):
589 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000590 if self._version != other._version:
591 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000592 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000593 if self._ip != other._ip:
594 return self._ip < other._ip
595 return False
596
Nick Coghlandc9b2552012-05-20 21:01:57 +1000597 # Shorthand for Integer addition and subtraction. This is not
598 # meant to ever support addition/subtraction of addresses.
599 def __add__(self, other):
600 if not isinstance(other, int):
601 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000602 return self.__class__(int(self) + other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000603
604 def __sub__(self, other):
605 if not isinstance(other, int):
606 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000607 return self.__class__(int(self) - other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000608
609 def __repr__(self):
610 return '%s(%r)' % (self.__class__.__name__, str(self))
611
612 def __str__(self):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200613 return str(self._string_from_ip_int(self._ip))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000614
615 def __hash__(self):
616 return hash(hex(int(self._ip)))
617
618 def _get_address_key(self):
619 return (self._version, self)
620
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +0200621 def __reduce__(self):
622 return self.__class__, (self._ip,)
623
ewosbornef9c95a42019-09-12 05:03:31 -0400624 def __format__(self, fmt):
625 """Returns an IP address as a formatted string.
626
627 Supported presentation types are:
628 's': returns the IP address as a string (default)
Serhiy Storchaka5d6f5b62019-09-27 20:02:58 +0300629 'b': converts to binary and returns a zero-padded string
ewosbornef9c95a42019-09-12 05:03:31 -0400630 'X' or 'x': converts to upper- or lower-case hex and returns a zero-padded string
Serhiy Storchaka5d6f5b62019-09-27 20:02:58 +0300631 'n': the same as 'b' for IPv4 and 'x' for IPv6
ewosbornef9c95a42019-09-12 05:03:31 -0400632
633 For binary and hex presentation types, the alternate form specifier
634 '#' and the grouping option '_' are supported.
635 """
636
ewosbornef9c95a42019-09-12 05:03:31 -0400637 # Support string formatting
638 if not fmt or fmt[-1] == 's':
ewosbornef9c95a42019-09-12 05:03:31 -0400639 return format(str(self), fmt)
640
641 # From here on down, support for 'bnXx'
Serhiy Storchaka5d6f5b62019-09-27 20:02:58 +0300642 global _address_fmt_re
643 if _address_fmt_re is None:
644 import re
645 _address_fmt_re = re.compile('(#?)(_?)([xbnX])')
ewosbornef9c95a42019-09-12 05:03:31 -0400646
Serhiy Storchaka5d6f5b62019-09-27 20:02:58 +0300647 m = _address_fmt_re.fullmatch(fmt)
ewosbornef9c95a42019-09-12 05:03:31 -0400648 if not m:
649 return super().__format__(fmt)
650
Serhiy Storchaka5d6f5b62019-09-27 20:02:58 +0300651 alternate, grouping, fmt_base = m.groups()
ewosbornef9c95a42019-09-12 05:03:31 -0400652
653 # Set some defaults
654 if fmt_base == 'n':
655 if self._version == 4:
656 fmt_base = 'b' # Binary is default for ipv4
Serhiy Storchaka5d6f5b62019-09-27 20:02:58 +0300657 else:
ewosbornef9c95a42019-09-12 05:03:31 -0400658 fmt_base = 'x' # Hex is default for ipv6
659
ewosbornef9c95a42019-09-12 05:03:31 -0400660 if fmt_base == 'b':
Serhiy Storchaka5d6f5b62019-09-27 20:02:58 +0300661 padlen = self._max_prefixlen
662 else:
663 padlen = self._max_prefixlen // 4
ewosbornef9c95a42019-09-12 05:03:31 -0400664
Serhiy Storchaka5d6f5b62019-09-27 20:02:58 +0300665 if grouping:
666 padlen += padlen // 4 - 1
ewosbornef9c95a42019-09-12 05:03:31 -0400667
Serhiy Storchaka5d6f5b62019-09-27 20:02:58 +0300668 if alternate:
669 padlen += 2 # 0b or 0x
ewosbornef9c95a42019-09-12 05:03:31 -0400670
Serhiy Storchaka5d6f5b62019-09-27 20:02:58 +0300671 return format(int(self), f'{alternate}0{padlen}{grouping}{fmt_base}')
ewosbornef9c95a42019-09-12 05:03:31 -0400672
Nick Coghlandc9b2552012-05-20 21:01:57 +1000673
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200674@functools.total_ordering
Nick Coghlandc9b2552012-05-20 21:01:57 +1000675class _BaseNetwork(_IPAddressBase):
Nick Coghlan51c30672012-05-27 00:25:58 +1000676 """A generic IP network object.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000677
678 This IP class contains the version independent methods which are
679 used by networks.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000680 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000681
Nick Coghlandc9b2552012-05-20 21:01:57 +1000682 def __repr__(self):
683 return '%s(%r)' % (self.__class__.__name__, str(self))
684
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200685 def __str__(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000686 return '%s/%d' % (self.network_address, self.prefixlen)
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200687
Nick Coghlandc9b2552012-05-20 21:01:57 +1000688 def hosts(self):
689 """Generate Iterator over usable hosts in a network.
690
Sandro Tosib95c6342012-05-23 23:17:22 +0200691 This is like __iter__ except it doesn't return the network
692 or broadcast addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000693
694 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000695 network = int(self.network_address)
696 broadcast = int(self.broadcast_address)
697 for x in range(network + 1, broadcast):
698 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000699
700 def __iter__(self):
Nick Coghlan7319f692012-07-07 21:43:30 +1000701 network = int(self.network_address)
702 broadcast = int(self.broadcast_address)
703 for x in range(network, broadcast + 1):
704 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000705
706 def __getitem__(self, n):
707 network = int(self.network_address)
708 broadcast = int(self.broadcast_address)
709 if n >= 0:
710 if network + n > broadcast:
Berker Peksag28dc1182016-06-11 22:30:05 +0300711 raise IndexError('address out of range')
Nick Coghlan51c30672012-05-27 00:25:58 +1000712 return self._address_class(network + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000713 else:
714 n += 1
715 if broadcast + n < network:
Berker Peksag28dc1182016-06-11 22:30:05 +0300716 raise IndexError('address out of range')
Nick Coghlan51c30672012-05-27 00:25:58 +1000717 return self._address_class(broadcast + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000718
719 def __lt__(self, other):
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200720 if not isinstance(other, _BaseNetwork):
721 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000722 if self._version != other._version:
723 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000724 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000725 if self.network_address != other.network_address:
726 return self.network_address < other.network_address
727 if self.netmask != other.netmask:
728 return self.netmask < other.netmask
729 return False
730
Nick Coghlandc9b2552012-05-20 21:01:57 +1000731 def __eq__(self, other):
Nick Coghlan9a9c28c2012-07-07 23:05:59 +1000732 try:
733 return (self._version == other._version and
734 self.network_address == other.network_address and
735 int(self.netmask) == int(other.netmask))
736 except AttributeError:
737 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000738
Nick Coghlandc9b2552012-05-20 21:01:57 +1000739 def __hash__(self):
740 return hash(int(self.network_address) ^ int(self.netmask))
741
742 def __contains__(self, other):
743 # always false if one is v4 and the other is v6.
744 if self._version != other._version:
745 return False
746 # dealing with another network.
747 if isinstance(other, _BaseNetwork):
748 return False
749 # dealing with another address
750 else:
751 # address
gescheit3bbcc922019-04-30 10:54:30 +0300752 return other._ip & self.netmask._ip == self.network_address._ip
Nick Coghlandc9b2552012-05-20 21:01:57 +1000753
754 def overlaps(self, other):
755 """Tell if self is partly contained in other."""
756 return self.network_address in other or (
757 self.broadcast_address in other or (
758 other.network_address in self or (
759 other.broadcast_address in self)))
760
Inada Naoki2430d532019-04-15 16:01:00 +0900761 @functools.cached_property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000762 def broadcast_address(self):
Inada Naoki2430d532019-04-15 16:01:00 +0900763 return self._address_class(int(self.network_address) |
764 int(self.hostmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000765
Inada Naoki2430d532019-04-15 16:01:00 +0900766 @functools.cached_property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000767 def hostmask(self):
Inada Naoki2430d532019-04-15 16:01:00 +0900768 return self._address_class(int(self.netmask) ^ self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000769
770 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000771 def with_prefixlen(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000772 return '%s/%d' % (self.network_address, self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000773
774 @property
775 def with_netmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000776 return '%s/%s' % (self.network_address, self.netmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000777
778 @property
779 def with_hostmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000780 return '%s/%s' % (self.network_address, self.hostmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000781
782 @property
783 def num_addresses(self):
784 """Number of hosts in the current subnet."""
785 return int(self.broadcast_address) - int(self.network_address) + 1
786
787 @property
Nick Coghlan51c30672012-05-27 00:25:58 +1000788 def _address_class(self):
Nick Coghland9722652012-06-17 16:33:00 +1000789 # Returning bare address objects (rather than interfaces) allows for
790 # more consistent behaviour across the network address, broadcast
791 # address and individual host addresses.
792 msg = '%200s has no associated address class' % (type(self),)
793 raise NotImplementedError(msg)
Nick Coghlan51c30672012-05-27 00:25:58 +1000794
795 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000796 def prefixlen(self):
797 return self._prefixlen
798
799 def address_exclude(self, other):
800 """Remove an address from a larger block.
801
802 For example:
803
804 addr1 = ip_network('192.0.2.0/28')
805 addr2 = ip_network('192.0.2.1/32')
Serhiy Storchakabb0dbd52016-03-01 10:25:45 +0200806 list(addr1.address_exclude(addr2)) =
Nick Coghlandc9b2552012-05-20 21:01:57 +1000807 [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
Serhiy Storchakabb0dbd52016-03-01 10:25:45 +0200808 IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
Nick Coghlandc9b2552012-05-20 21:01:57 +1000809
810 or IPv6:
811
812 addr1 = ip_network('2001:db8::1/32')
813 addr2 = ip_network('2001:db8::1/128')
Serhiy Storchakabb0dbd52016-03-01 10:25:45 +0200814 list(addr1.address_exclude(addr2)) =
Nick Coghlandc9b2552012-05-20 21:01:57 +1000815 [ip_network('2001:db8::1/128'),
Serhiy Storchakabb0dbd52016-03-01 10:25:45 +0200816 ip_network('2001:db8::2/127'),
817 ip_network('2001:db8::4/126'),
818 ip_network('2001:db8::8/125'),
819 ...
820 ip_network('2001:db8:8000::/33')]
Nick Coghlandc9b2552012-05-20 21:01:57 +1000821
822 Args:
823 other: An IPv4Network or IPv6Network object of the same type.
824
825 Returns:
Ezio Melotti3f5db392013-01-27 06:20:14 +0200826 An iterator of the IPv(4|6)Network objects which is self
Nick Coghlandc9b2552012-05-20 21:01:57 +1000827 minus other.
828
829 Raises:
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300830 TypeError: If self and other are of differing address
Nick Coghlandc9b2552012-05-20 21:01:57 +1000831 versions, or if other is not a network object.
832 ValueError: If other is not completely contained by self.
833
834 """
835 if not self._version == other._version:
836 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000837 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000838
839 if not isinstance(other, _BaseNetwork):
Nick Coghlan912238e2012-07-07 13:34:50 +1000840 raise TypeError("%s is not a network object" % other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000841
Cheryl Sabella91dc64b2017-10-22 17:39:49 -0400842 if not other.subnet_of(self):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200843 raise ValueError('%s not contained in %s' % (other, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000844 if other == self:
Raymond Hettingerbb6c0aa2014-11-22 22:14:41 -0800845 return
Nick Coghlandc9b2552012-05-20 21:01:57 +1000846
Nick Coghlandc9b2552012-05-20 21:01:57 +1000847 # Make sure we're comparing the network of other.
Nick Coghlan912238e2012-07-07 13:34:50 +1000848 other = other.__class__('%s/%s' % (other.network_address,
849 other.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000850
851 s1, s2 = self.subnets()
852 while s1 != other and s2 != other:
Cheryl Sabella91dc64b2017-10-22 17:39:49 -0400853 if other.subnet_of(s1):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000854 yield s2
855 s1, s2 = s1.subnets()
Cheryl Sabella91dc64b2017-10-22 17:39:49 -0400856 elif other.subnet_of(s2):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000857 yield s1
858 s1, s2 = s2.subnets()
859 else:
860 # If we got here, there's a bug somewhere.
861 raise AssertionError('Error performing exclusion: '
862 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000863 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000864 if s1 == other:
865 yield s2
866 elif s2 == other:
867 yield s1
868 else:
869 # If we got here, there's a bug somewhere.
870 raise AssertionError('Error performing exclusion: '
871 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000872 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000873
874 def compare_networks(self, other):
875 """Compare two IP objects.
876
877 This is only concerned about the comparison of the integer
878 representation of the network addresses. This means that the
879 host bits aren't considered at all in this method. If you want
880 to compare host bits, you can easily enough do a
881 'HostA._ip < HostB._ip'
882
883 Args:
884 other: An IP object.
885
886 Returns:
887 If the IP versions of self and other are the same, returns:
888
889 -1 if self < other:
890 eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
891 IPv6Network('2001:db8::1000/124') <
892 IPv6Network('2001:db8::2000/124')
893 0 if self == other
894 eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
895 IPv6Network('2001:db8::1000/124') ==
896 IPv6Network('2001:db8::1000/124')
897 1 if self > other
898 eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
899 IPv6Network('2001:db8::2000/124') >
900 IPv6Network('2001:db8::1000/124')
901
902 Raises:
903 TypeError if the IP versions are different.
904
905 """
906 # does this need to raise a ValueError?
907 if self._version != other._version:
908 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000909 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000910 # self._version == other._version below here:
911 if self.network_address < other.network_address:
912 return -1
913 if self.network_address > other.network_address:
914 return 1
915 # self.network_address == other.network_address below here:
916 if self.netmask < other.netmask:
917 return -1
918 if self.netmask > other.netmask:
919 return 1
920 return 0
921
922 def _get_networks_key(self):
923 """Network-only key function.
924
925 Returns an object that identifies this address' network and
926 netmask. This function is a suitable "key" argument for sorted()
927 and list.sort().
928
929 """
930 return (self._version, self.network_address, self.netmask)
931
932 def subnets(self, prefixlen_diff=1, new_prefix=None):
933 """The subnets which join to make the current subnet.
934
935 In the case that self contains only one IP
936 (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
937 for IPv6), yield an iterator with just ourself.
938
939 Args:
940 prefixlen_diff: An integer, the amount the prefix length
941 should be increased by. This should not be set if
942 new_prefix is also set.
943 new_prefix: The desired new prefix length. This must be a
944 larger number (smaller prefix) than the existing prefix.
945 This should not be set if prefixlen_diff is also set.
946
947 Returns:
948 An iterator of IPv(4|6) objects.
949
950 Raises:
951 ValueError: The prefixlen_diff is too small or too large.
952 OR
953 prefixlen_diff and new_prefix are both set or new_prefix
954 is a smaller number than the current prefix (smaller
955 number means a larger network)
956
957 """
958 if self._prefixlen == self._max_prefixlen:
959 yield self
960 return
961
962 if new_prefix is not None:
963 if new_prefix < self._prefixlen:
964 raise ValueError('new prefix must be longer')
965 if prefixlen_diff != 1:
966 raise ValueError('cannot set prefixlen_diff and new_prefix')
967 prefixlen_diff = new_prefix - self._prefixlen
968
969 if prefixlen_diff < 0:
970 raise ValueError('prefix length diff must be > 0')
971 new_prefixlen = self._prefixlen + prefixlen_diff
972
Nick Coghlan932346f2014-02-08 23:17:36 +1000973 if new_prefixlen > self._max_prefixlen:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000974 raise ValueError(
975 'prefix length diff %d is invalid for netblock %s' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000976 new_prefixlen, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000977
Antoine Pitrou824db302014-05-15 20:21:48 +0200978 start = int(self.network_address)
Serhiy Storchakabb0dbd52016-03-01 10:25:45 +0200979 end = int(self.broadcast_address) + 1
Antoine Pitrou824db302014-05-15 20:21:48 +0200980 step = (int(self.hostmask) + 1) >> prefixlen_diff
981 for new_addr in range(start, end, step):
982 current = self.__class__((new_addr, new_prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000983 yield current
984
Nick Coghlandc9b2552012-05-20 21:01:57 +1000985 def supernet(self, prefixlen_diff=1, new_prefix=None):
986 """The supernet containing the current network.
987
988 Args:
989 prefixlen_diff: An integer, the amount the prefix length of
990 the network should be decreased by. For example, given a
991 /24 network and a prefixlen_diff of 3, a supernet with a
992 /21 netmask is returned.
993
994 Returns:
995 An IPv4 network object.
996
997 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200998 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
999 a negative prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001000 OR
1001 If prefixlen_diff and new_prefix are both set or new_prefix is a
1002 larger number than the current prefix (larger number means a
1003 smaller network)
1004
1005 """
1006 if self._prefixlen == 0:
1007 return self
1008
1009 if new_prefix is not None:
1010 if new_prefix > self._prefixlen:
1011 raise ValueError('new prefix must be shorter')
1012 if prefixlen_diff != 1:
1013 raise ValueError('cannot set prefixlen_diff and new_prefix')
1014 prefixlen_diff = self._prefixlen - new_prefix
1015
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001016 new_prefixlen = self.prefixlen - prefixlen_diff
1017 if new_prefixlen < 0:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001018 raise ValueError(
1019 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
1020 (self.prefixlen, prefixlen_diff))
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001021 return self.__class__((
1022 int(self.network_address) & (int(self.netmask) << prefixlen_diff),
1023 new_prefixlen
1024 ))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001025
Nick Coghlan730f67f2012-08-05 22:02:18 +10001026 @property
1027 def is_multicast(self):
1028 """Test if the address is reserved for multicast use.
1029
1030 Returns:
1031 A boolean, True if the address is a multicast address.
1032 See RFC 2373 2.7 for details.
1033
1034 """
1035 return (self.network_address.is_multicast and
1036 self.broadcast_address.is_multicast)
1037
Cheryl Sabella91dc64b2017-10-22 17:39:49 -04001038 @staticmethod
1039 def _is_subnet_of(a, b):
1040 try:
1041 # Always false if one is v4 and the other is v6.
1042 if a._version != b._version:
1043 raise TypeError(f"{a} and {b} are not of the same version")
1044 return (b.network_address <= a.network_address and
1045 b.broadcast_address >= a.broadcast_address)
1046 except AttributeError:
1047 raise TypeError(f"Unable to test subnet containment "
1048 f"between {a} and {b}")
1049
1050 def subnet_of(self, other):
1051 """Return True if this network is a subnet of other."""
1052 return self._is_subnet_of(self, other)
1053
1054 def supernet_of(self, other):
1055 """Return True if this network is a supernet of other."""
1056 return self._is_subnet_of(other, self)
1057
Nick Coghlan730f67f2012-08-05 22:02:18 +10001058 @property
1059 def is_reserved(self):
1060 """Test if the address is otherwise IETF reserved.
1061
1062 Returns:
1063 A boolean, True if the address is within one of the
1064 reserved IPv6 Network ranges.
1065
1066 """
1067 return (self.network_address.is_reserved and
1068 self.broadcast_address.is_reserved)
1069
1070 @property
1071 def is_link_local(self):
1072 """Test if the address is reserved for link-local.
1073
1074 Returns:
1075 A boolean, True if the address is reserved per RFC 4291.
1076
1077 """
1078 return (self.network_address.is_link_local and
1079 self.broadcast_address.is_link_local)
1080
1081 @property
1082 def is_private(self):
1083 """Test if this address is allocated for private networks.
1084
1085 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001086 A boolean, True if the address is reserved per
1087 iana-ipv4-special-registry or iana-ipv6-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001088
1089 """
1090 return (self.network_address.is_private and
1091 self.broadcast_address.is_private)
1092
1093 @property
Peter Moody22c31762013-10-21 13:58:06 -07001094 def is_global(self):
Peter Moodybe9c1b12013-10-22 12:36:21 -07001095 """Test if this address is allocated for public networks.
Peter Moody22c31762013-10-21 13:58:06 -07001096
1097 Returns:
1098 A boolean, True if the address is not reserved per
1099 iana-ipv4-special-registry or iana-ipv6-special-registry.
1100
1101 """
1102 return not self.is_private
1103
1104 @property
Nick Coghlan730f67f2012-08-05 22:02:18 +10001105 def is_unspecified(self):
1106 """Test if the address is unspecified.
1107
1108 Returns:
1109 A boolean, True if this is the unspecified address as defined in
1110 RFC 2373 2.5.2.
1111
1112 """
1113 return (self.network_address.is_unspecified and
1114 self.broadcast_address.is_unspecified)
1115
1116 @property
1117 def is_loopback(self):
1118 """Test if the address is a loopback address.
1119
1120 Returns:
1121 A boolean, True if the address is a loopback address as defined in
1122 RFC 2373 2.5.3.
1123
1124 """
1125 return (self.network_address.is_loopback and
1126 self.broadcast_address.is_loopback)
1127
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001128class _BaseV4:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001129
1130 """Base IPv4 object.
1131
1132 The following methods are used by IPv4 objects in both single IP
1133 addresses and networks.
1134
1135 """
1136
Serhiy Storchaka88f64f32015-03-07 20:08:34 +02001137 __slots__ = ()
1138 _version = 4
Nick Coghlandc9b2552012-05-20 21:01:57 +10001139 # Equivalent to 255.255.255.255 or 32 bits of 1's.
1140 _ALL_ONES = (2**IPV4LENGTH) - 1
Nick Coghlandc9b2552012-05-20 21:01:57 +10001141
Antoine Pitrou45aba182014-05-15 20:18:41 +02001142 _max_prefixlen = IPV4LENGTH
1143 # There are only a handful of valid v4 netmasks, so we cache them all
1144 # when constructed (see _make_netmask()).
1145 _netmask_cache = {}
1146
Nick Coghlandc9b2552012-05-20 21:01:57 +10001147 def _explode_shorthand_ip_string(self):
1148 return str(self)
1149
Antoine Pitrou45aba182014-05-15 20:18:41 +02001150 @classmethod
1151 def _make_netmask(cls, arg):
1152 """Make a (netmask, prefix_len) tuple from the given argument.
1153
1154 Argument can be:
1155 - an integer (the prefix length)
1156 - a string representing the prefix length (e.g. "24")
1157 - a string representing the prefix netmask (e.g. "255.255.255.0")
1158 """
1159 if arg not in cls._netmask_cache:
1160 if isinstance(arg, int):
1161 prefixlen = arg
Nicolai Moore5e48e3d2019-05-14 20:32:59 +10001162 if not (0 <= prefixlen <= cls._max_prefixlen):
1163 cls._report_invalid_netmask(prefixlen)
Antoine Pitrou45aba182014-05-15 20:18:41 +02001164 else:
1165 try:
1166 # Check for a netmask in prefix length form
1167 prefixlen = cls._prefix_from_prefix_string(arg)
1168 except NetmaskValueError:
1169 # Check for a netmask or hostmask in dotted-quad form.
1170 # This may raise NetmaskValueError.
1171 prefixlen = cls._prefix_from_ip_string(arg)
1172 netmask = IPv4Address(cls._ip_int_from_prefix(prefixlen))
1173 cls._netmask_cache[arg] = netmask, prefixlen
1174 return cls._netmask_cache[arg]
1175
1176 @classmethod
1177 def _ip_int_from_string(cls, ip_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001178 """Turn the given IP string into an integer for comparison.
1179
1180 Args:
1181 ip_str: A string, the IP ip_str.
1182
1183 Returns:
1184 The IP ip_str as an integer.
1185
1186 Raises:
1187 AddressValueError: if ip_str isn't a valid IPv4 Address.
1188
1189 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001190 if not ip_str:
1191 raise AddressValueError('Address cannot be empty')
1192
Nick Coghlandc9b2552012-05-20 21:01:57 +10001193 octets = ip_str.split('.')
1194 if len(octets) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001195 raise AddressValueError("Expected 4 octets in %r" % ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001196
Nick Coghlan7319f692012-07-07 21:43:30 +10001197 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001198 return int.from_bytes(map(cls._parse_octet, octets), 'big')
Nick Coghlan7319f692012-07-07 21:43:30 +10001199 except ValueError as exc:
1200 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001201
Antoine Pitrou45aba182014-05-15 20:18:41 +02001202 @classmethod
1203 def _parse_octet(cls, octet_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001204 """Convert a decimal octet into an integer.
1205
1206 Args:
1207 octet_str: A string, the number to parse.
1208
1209 Returns:
1210 The octet as an integer.
1211
1212 Raises:
1213 ValueError: if the octet isn't strictly a decimal from [0..255].
1214
1215 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001216 if not octet_str:
1217 raise ValueError("Empty octet not permitted")
Victor Stinnerfabd7bb2020-08-11 15:26:59 +02001218 # Reject non-ASCII digits.
INADA Naoki58a10962018-02-23 20:02:41 +09001219 if not (octet_str.isascii() and octet_str.isdigit()):
Nick Coghlan07c4e332012-07-08 23:06:45 +10001220 msg = "Only decimal digits permitted in %r"
1221 raise ValueError(msg % octet_str)
1222 # We do the length check second, since the invalid character error
1223 # is likely to be more informative for the user
1224 if len(octet_str) > 3:
1225 msg = "At most 3 characters permitted in %r"
1226 raise ValueError(msg % octet_str)
Christian Heimes60ce8f02021-05-02 14:00:35 +02001227 # Handle leading zeros as strict as glibc's inet_pton()
1228 # See security bug bpo-36384
1229 if octet_str != '0' and octet_str[0] == '0':
1230 msg = "Leading zeros are not permitted in %r"
1231 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001232 # Convert to integer (we know digits are legal)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001233 octet_int = int(octet_str, 10)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001234 if octet_int > 255:
Nick Coghlanb582ecc2012-07-07 22:15:22 +10001235 raise ValueError("Octet %d (> 255) not permitted" % octet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001236 return octet_int
1237
Antoine Pitrou45aba182014-05-15 20:18:41 +02001238 @classmethod
1239 def _string_from_ip_int(cls, ip_int):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001240 """Turns a 32-bit integer into dotted decimal notation.
1241
1242 Args:
1243 ip_int: An integer, the IP address.
1244
1245 Returns:
1246 The IP address as a string in dotted decimal notation.
1247
1248 """
Nick Coghlan7319f692012-07-07 21:43:30 +10001249 return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001250
Eric V. Smithebdaaf42014-04-14 12:58:07 -04001251 def _reverse_pointer(self):
1252 """Return the reverse DNS pointer name for the IPv4 address.
1253
1254 This implements the method described in RFC1035 3.5.
1255
1256 """
1257 reverse_octets = str(self).split('.')[::-1]
1258 return '.'.join(reverse_octets) + '.in-addr.arpa'
1259
Nick Coghlandc9b2552012-05-20 21:01:57 +10001260 @property
1261 def max_prefixlen(self):
1262 return self._max_prefixlen
1263
1264 @property
1265 def version(self):
1266 return self._version
1267
Nick Coghlandc9b2552012-05-20 21:01:57 +10001268
1269class IPv4Address(_BaseV4, _BaseAddress):
1270
1271 """Represent and manipulate single IPv4 Addresses."""
1272
Serhiy Storchaka88f64f32015-03-07 20:08:34 +02001273 __slots__ = ('_ip', '__weakref__')
1274
Nick Coghlandc9b2552012-05-20 21:01:57 +10001275 def __init__(self, address):
1276
1277 """
1278 Args:
1279 address: A string or integer representing the IP
1280
1281 Additionally, an integer can be passed, so
1282 IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1283 or, more generally
1284 IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1285 IPv4Address('192.0.2.1')
1286
1287 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001288 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001289
1290 """
Nick Coghlandc9b2552012-05-20 21:01:57 +10001291 # Efficient constructor from integer.
1292 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001293 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001294 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001295 return
1296
1297 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001298 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001299 self._check_packed_address(address, 4)
Nick Coghlandb7920b2012-08-20 10:19:12 +10001300 self._ip = int.from_bytes(address, 'big')
Nick Coghlandc9b2552012-05-20 21:01:57 +10001301 return
1302
1303 # Assume input argument to be string or any object representation
1304 # which converts into a formatted IP string.
1305 addr_str = str(address)
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +02001306 if '/' in addr_str:
1307 raise AddressValueError("Unexpected '/' in %r" % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001308 self._ip = self._ip_int_from_string(addr_str)
1309
1310 @property
1311 def packed(self):
1312 """The binary representation of this address."""
1313 return v4_int_to_packed(self._ip)
1314
Nick Coghlan730f67f2012-08-05 22:02:18 +10001315 @property
1316 def is_reserved(self):
1317 """Test if the address is otherwise IETF reserved.
1318
1319 Returns:
1320 A boolean, True if the address is within the
1321 reserved IPv4 Network range.
1322
1323 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001324 return self in self._constants._reserved_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001325
1326 @property
Peter Moodybe9c1b12013-10-22 12:36:21 -07001327 @functools.lru_cache()
Nick Coghlan730f67f2012-08-05 22:02:18 +10001328 def is_private(self):
1329 """Test if this address is allocated for private networks.
1330
1331 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001332 A boolean, True if the address is reserved per
1333 iana-ipv4-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001334
1335 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001336 return any(self in net for net in self._constants._private_networks)
Nick Coghlan730f67f2012-08-05 22:02:18 +10001337
1338 @property
Berker Peksag742192a2016-06-11 22:11:47 +03001339 @functools.lru_cache()
1340 def is_global(self):
1341 return self not in self._constants._public_network and not self.is_private
1342
1343 @property
Nick Coghlan730f67f2012-08-05 22:02:18 +10001344 def is_multicast(self):
1345 """Test if the address is reserved for multicast use.
1346
1347 Returns:
1348 A boolean, True if the address is multicast.
1349 See RFC 3171 for details.
1350
1351 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001352 return self in self._constants._multicast_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001353
1354 @property
1355 def is_unspecified(self):
1356 """Test if the address is unspecified.
1357
1358 Returns:
1359 A boolean, True if this is the unspecified address as defined in
1360 RFC 5735 3.
1361
1362 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001363 return self == self._constants._unspecified_address
Nick Coghlan730f67f2012-08-05 22:02:18 +10001364
1365 @property
1366 def is_loopback(self):
1367 """Test if the address is a loopback address.
1368
1369 Returns:
1370 A boolean, True if the address is a loopback per RFC 3330.
1371
1372 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001373 return self in self._constants._loopback_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001374
1375 @property
1376 def is_link_local(self):
1377 """Test if the address is reserved for link-local.
1378
1379 Returns:
1380 A boolean, True if the address is link-local per RFC 3927.
1381
1382 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001383 return self in self._constants._linklocal_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001384
Nick Coghlandc9b2552012-05-20 21:01:57 +10001385
1386class IPv4Interface(IPv4Address):
1387
Nick Coghlandc9b2552012-05-20 21:01:57 +10001388 def __init__(self, address):
Inada Naoki6fa84bd2019-04-16 08:32:28 +09001389 addr, mask = self._split_addr_prefix(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001390
Inada Naoki6fa84bd2019-04-16 08:32:28 +09001391 IPv4Address.__init__(self, addr)
1392 self.network = IPv4Network((addr, mask), strict=False)
1393 self.netmask = self.network.netmask
Nick Coghlandc9b2552012-05-20 21:01:57 +10001394 self._prefixlen = self.network._prefixlen
1395
Inada Naoki6fa84bd2019-04-16 08:32:28 +09001396 @functools.cached_property
1397 def hostmask(self):
1398 return self.network.hostmask
Nick Coghlandc9b2552012-05-20 21:01:57 +10001399
Nick Coghlandc9b2552012-05-20 21:01:57 +10001400 def __str__(self):
1401 return '%s/%d' % (self._string_from_ip_int(self._ip),
Inada Naoki2430d532019-04-15 16:01:00 +09001402 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001403
1404 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001405 address_equal = IPv4Address.__eq__(self, other)
MojoVampire469325c2020-03-03 18:50:17 +00001406 if address_equal is NotImplemented or not address_equal:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001407 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001408 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001409 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001410 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001411 # An interface with an associated network is NOT the
1412 # same as an unassociated address. That's why the hash
1413 # takes the extra info into account.
1414 return False
1415
1416 def __lt__(self, other):
1417 address_less = IPv4Address.__lt__(self, other)
1418 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001419 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001420 try:
s-sanjay7bd8d3e2017-03-31 23:09:53 -07001421 return (self.network < other.network or
1422 self.network == other.network and address_less)
Nick Coghlan3008ec02012-07-08 00:45:33 +10001423 except AttributeError:
1424 # We *do* allow addresses and interfaces to be sorted. The
1425 # unassociated address is considered less than all interfaces.
1426 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001427
1428 def __hash__(self):
Ravi Teja Pb30ee262020-06-29 23:09:29 +05301429 return hash((self._ip, self._prefixlen, int(self.network.network_address)))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001430
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +02001431 __reduce__ = _IPAddressBase.__reduce__
1432
Nick Coghlandc9b2552012-05-20 21:01:57 +10001433 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001434 def ip(self):
1435 return IPv4Address(self._ip)
1436
1437 @property
1438 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10001439 return '%s/%s' % (self._string_from_ip_int(self._ip),
1440 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001441
1442 @property
1443 def with_netmask(self):
1444 return '%s/%s' % (self._string_from_ip_int(self._ip),
1445 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001446
Nick Coghlandc9b2552012-05-20 21:01:57 +10001447 @property
1448 def with_hostmask(self):
1449 return '%s/%s' % (self._string_from_ip_int(self._ip),
1450 self.hostmask)
1451
1452
1453class IPv4Network(_BaseV4, _BaseNetwork):
1454
1455 """This class represents and manipulates 32-bit IPv4 network + addresses..
1456
1457 Attributes: [examples for IPv4Network('192.0.2.0/27')]
1458 .network_address: IPv4Address('192.0.2.0')
1459 .hostmask: IPv4Address('0.0.0.31')
1460 .broadcast_address: IPv4Address('192.0.2.32')
1461 .netmask: IPv4Address('255.255.255.224')
1462 .prefixlen: 27
1463
1464 """
Nick Coghlan51c30672012-05-27 00:25:58 +10001465 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001466 _address_class = IPv4Address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001467
Nick Coghlandc9b2552012-05-20 21:01:57 +10001468 def __init__(self, address, strict=True):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001469 """Instantiate a new IPv4 network object.
1470
1471 Args:
1472 address: A string or integer representing the IP [& network].
1473 '192.0.2.0/24'
1474 '192.0.2.0/255.255.255.0'
Eric L. Frederich52f98422020-08-05 14:44:53 -04001475 '192.0.2.0/0.0.0.255'
Nick Coghlandc9b2552012-05-20 21:01:57 +10001476 are all functionally the same in IPv4. Similarly,
1477 '192.0.2.1'
1478 '192.0.2.1/255.255.255.255'
1479 '192.0.2.1/32'
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001480 are also functionally equivalent. That is to say, failing to
Nick Coghlandc9b2552012-05-20 21:01:57 +10001481 provide a subnetmask will create an object with a mask of /32.
1482
1483 If the mask (portion after the / in the argument) is given in
1484 dotted quad form, it is treated as a netmask if it starts with a
1485 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1486 starts with a zero field (e.g. 0.255.255.255 == /8), with the
1487 single exception of an all-zero mask which is treated as a
1488 netmask == /0. If no mask is given, a default of /32 is used.
1489
1490 Additionally, an integer can be passed, so
1491 IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1492 or, more generally
1493 IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1494 IPv4Interface('192.0.2.1')
1495
1496 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001497 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001498 NetmaskValueError: If the netmask isn't valid for
1499 an IPv4 address.
Sandro Tosib4386d32012-06-02 17:14:22 +02001500 ValueError: If strict is True and a network address is not
Nick Coghlandc9b2552012-05-20 21:01:57 +10001501 supplied.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001502 """
Inada Naoki6fa84bd2019-04-16 08:32:28 +09001503 addr, mask = self._split_addr_prefix(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001504
Xiang Zhang10b134a2018-03-21 08:25:13 +08001505 self.network_address = IPv4Address(addr)
1506 self.netmask, self._prefixlen = self._make_netmask(mask)
1507 packed = int(self.network_address)
1508 if packed & int(self.netmask) != packed:
1509 if strict:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001510 raise ValueError('%s has host bits set' % self)
Xiang Zhang10b134a2018-03-21 08:25:13 +08001511 else:
1512 self.network_address = IPv4Address(packed &
1513 int(self.netmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001514
1515 if self._prefixlen == (self._max_prefixlen - 1):
1516 self.hosts = self.__iter__
Pete Wicken8e9c47a2020-03-09 22:33:45 +00001517 elif self._prefixlen == (self._max_prefixlen):
1518 self.hosts = lambda: [IPv4Address(addr)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001519
Peter Moodye5019d52013-10-24 09:47:10 -07001520 @property
1521 @functools.lru_cache()
1522 def is_global(self):
1523 """Test if this address is allocated for public networks.
1524
1525 Returns:
1526 A boolean, True if the address is not reserved per
1527 iana-ipv4-special-registry.
1528
1529 """
1530 return (not (self.network_address in IPv4Network('100.64.0.0/10') and
1531 self.broadcast_address in IPv4Network('100.64.0.0/10')) and
1532 not self.is_private)
1533
1534
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001535class _IPv4Constants:
1536 _linklocal_network = IPv4Network('169.254.0.0/16')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001537
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001538 _loopback_network = IPv4Network('127.0.0.0/8')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001539
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001540 _multicast_network = IPv4Network('224.0.0.0/4')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001541
Berker Peksag742192a2016-06-11 22:11:47 +03001542 _public_network = IPv4Network('100.64.0.0/10')
1543
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001544 _private_networks = [
1545 IPv4Network('0.0.0.0/8'),
1546 IPv4Network('10.0.0.0/8'),
1547 IPv4Network('127.0.0.0/8'),
1548 IPv4Network('169.254.0.0/16'),
1549 IPv4Network('172.16.0.0/12'),
1550 IPv4Network('192.0.0.0/29'),
1551 IPv4Network('192.0.0.170/31'),
1552 IPv4Network('192.0.2.0/24'),
1553 IPv4Network('192.168.0.0/16'),
1554 IPv4Network('198.18.0.0/15'),
1555 IPv4Network('198.51.100.0/24'),
1556 IPv4Network('203.0.113.0/24'),
1557 IPv4Network('240.0.0.0/4'),
1558 IPv4Network('255.255.255.255/32'),
1559 ]
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001560
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001561 _reserved_network = IPv4Network('240.0.0.0/4')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001562
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001563 _unspecified_address = IPv4Address('0.0.0.0')
1564
1565
1566IPv4Address._constants = _IPv4Constants
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001567
Nick Coghlandc9b2552012-05-20 21:01:57 +10001568
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001569class _BaseV6:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001570
1571 """Base IPv6 object.
1572
1573 The following methods are used by IPv6 objects in both single IP
1574 addresses and networks.
1575
1576 """
1577
Serhiy Storchaka88f64f32015-03-07 20:08:34 +02001578 __slots__ = ()
1579 _version = 6
Nick Coghlandc9b2552012-05-20 21:01:57 +10001580 _ALL_ONES = (2**IPV6LENGTH) - 1
1581 _HEXTET_COUNT = 8
1582 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
Antoine Pitrou45aba182014-05-15 20:18:41 +02001583 _max_prefixlen = IPV6LENGTH
1584
1585 # There are only a bunch of valid v6 netmasks, so we cache them all
1586 # when constructed (see _make_netmask()).
1587 _netmask_cache = {}
Nick Coghlandc9b2552012-05-20 21:01:57 +10001588
Antoine Pitrou45aba182014-05-15 20:18:41 +02001589 @classmethod
1590 def _make_netmask(cls, arg):
1591 """Make a (netmask, prefix_len) tuple from the given argument.
1592
1593 Argument can be:
1594 - an integer (the prefix length)
1595 - a string representing the prefix length (e.g. "24")
1596 - a string representing the prefix netmask (e.g. "255.255.255.0")
1597 """
1598 if arg not in cls._netmask_cache:
1599 if isinstance(arg, int):
1600 prefixlen = arg
Nicolai Moore5e48e3d2019-05-14 20:32:59 +10001601 if not (0 <= prefixlen <= cls._max_prefixlen):
1602 cls._report_invalid_netmask(prefixlen)
Antoine Pitrou45aba182014-05-15 20:18:41 +02001603 else:
1604 prefixlen = cls._prefix_from_prefix_string(arg)
1605 netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen))
1606 cls._netmask_cache[arg] = netmask, prefixlen
1607 return cls._netmask_cache[arg]
1608
1609 @classmethod
1610 def _ip_int_from_string(cls, ip_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001611 """Turn an IPv6 ip_str into an integer.
1612
1613 Args:
1614 ip_str: A string, the IPv6 ip_str.
1615
1616 Returns:
1617 An int, the IPv6 address
1618
1619 Raises:
1620 AddressValueError: if ip_str isn't a valid IPv6 Address.
1621
1622 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001623 if not ip_str:
1624 raise AddressValueError('Address cannot be empty')
1625
Nick Coghlandc9b2552012-05-20 21:01:57 +10001626 parts = ip_str.split(':')
1627
1628 # An IPv6 address needs at least 2 colons (3 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001629 _min_parts = 3
1630 if len(parts) < _min_parts:
1631 msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
1632 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001633
1634 # If the address has an IPv4-style suffix, convert it to hexadecimal.
1635 if '.' in parts[-1]:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001636 try:
1637 ipv4_int = IPv4Address(parts.pop())._ip
1638 except AddressValueError as exc:
1639 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001640 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1641 parts.append('%x' % (ipv4_int & 0xFFFF))
1642
1643 # An IPv6 address can't have more than 8 colons (9 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001644 # The extra colon comes from using the "::" notation for a single
1645 # leading or trailing zero part.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001646 _max_parts = cls._HEXTET_COUNT + 1
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001647 if len(parts) > _max_parts:
1648 msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
1649 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001650
1651 # Disregarding the endpoints, find '::' with nothing in between.
1652 # This indicates that a run of zeroes has been skipped.
Nick Coghlan7319f692012-07-07 21:43:30 +10001653 skip_index = None
1654 for i in range(1, len(parts) - 1):
1655 if not parts[i]:
1656 if skip_index is not None:
1657 # Can't have more than one '::'
1658 msg = "At most one '::' permitted in %r" % ip_str
1659 raise AddressValueError(msg)
1660 skip_index = i
Nick Coghlandc9b2552012-05-20 21:01:57 +10001661
1662 # parts_hi is the number of parts to copy from above/before the '::'
1663 # parts_lo is the number of parts to copy from below/after the '::'
1664 if skip_index is not None:
1665 # If we found a '::', then check if it also covers the endpoints.
1666 parts_hi = skip_index
1667 parts_lo = len(parts) - skip_index - 1
1668 if not parts[0]:
1669 parts_hi -= 1
1670 if parts_hi:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001671 msg = "Leading ':' only permitted as part of '::' in %r"
1672 raise AddressValueError(msg % ip_str) # ^: requires ^::
Nick Coghlandc9b2552012-05-20 21:01:57 +10001673 if not parts[-1]:
1674 parts_lo -= 1
1675 if parts_lo:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001676 msg = "Trailing ':' only permitted as part of '::' in %r"
1677 raise AddressValueError(msg % ip_str) # :$ requires ::$
Antoine Pitrou45aba182014-05-15 20:18:41 +02001678 parts_skipped = cls._HEXTET_COUNT - (parts_hi + parts_lo)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001679 if parts_skipped < 1:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001680 msg = "Expected at most %d other parts with '::' in %r"
Antoine Pitrou45aba182014-05-15 20:18:41 +02001681 raise AddressValueError(msg % (cls._HEXTET_COUNT-1, ip_str))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001682 else:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001683 # Otherwise, allocate the entire address to parts_hi. The
1684 # endpoints could still be empty, but _parse_hextet() will check
1685 # for that.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001686 if len(parts) != cls._HEXTET_COUNT:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001687 msg = "Exactly %d parts expected without '::' in %r"
Antoine Pitrou45aba182014-05-15 20:18:41 +02001688 raise AddressValueError(msg % (cls._HEXTET_COUNT, ip_str))
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001689 if not parts[0]:
1690 msg = "Leading ':' only permitted as part of '::' in %r"
1691 raise AddressValueError(msg % ip_str) # ^: requires ^::
1692 if not parts[-1]:
1693 msg = "Trailing ':' only permitted as part of '::' in %r"
1694 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001695 parts_hi = len(parts)
1696 parts_lo = 0
1697 parts_skipped = 0
1698
1699 try:
1700 # Now, parse the hextets into a 128-bit integer.
1701 ip_int = 0
1702 for i in range(parts_hi):
1703 ip_int <<= 16
Antoine Pitrou45aba182014-05-15 20:18:41 +02001704 ip_int |= cls._parse_hextet(parts[i])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001705 ip_int <<= 16 * parts_skipped
1706 for i in range(-parts_lo, 0):
1707 ip_int <<= 16
Antoine Pitrou45aba182014-05-15 20:18:41 +02001708 ip_int |= cls._parse_hextet(parts[i])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001709 return ip_int
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001710 except ValueError as exc:
1711 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001712
Antoine Pitrou45aba182014-05-15 20:18:41 +02001713 @classmethod
1714 def _parse_hextet(cls, hextet_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001715 """Convert an IPv6 hextet string into an integer.
1716
1717 Args:
1718 hextet_str: A string, the number to parse.
1719
1720 Returns:
1721 The hextet as an integer.
1722
1723 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001724 ValueError: if the input isn't strictly a hex number from
1725 [0..FFFF].
Nick Coghlandc9b2552012-05-20 21:01:57 +10001726
1727 """
Victor Stinnerfabd7bb2020-08-11 15:26:59 +02001728 # Reject non-ASCII digits.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001729 if not cls._HEX_DIGITS.issuperset(hextet_str):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001730 raise ValueError("Only hex digits permitted in %r" % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001731 # We do the length check second, since the invalid character error
1732 # is likely to be more informative for the user
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001733 if len(hextet_str) > 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001734 msg = "At most 4 characters permitted in %r"
1735 raise ValueError(msg % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001736 # Length check means we can skip checking the integer value
1737 return int(hextet_str, 16)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001738
Antoine Pitrou45aba182014-05-15 20:18:41 +02001739 @classmethod
1740 def _compress_hextets(cls, hextets):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001741 """Compresses a list of hextets.
1742
1743 Compresses a list of strings, replacing the longest continuous
1744 sequence of "0" in the list with "" and adding empty strings at
1745 the beginning or at the end of the string such that subsequently
1746 calling ":".join(hextets) will produce the compressed version of
1747 the IPv6 address.
1748
1749 Args:
1750 hextets: A list of strings, the hextets to compress.
1751
1752 Returns:
1753 A list of strings.
1754
1755 """
1756 best_doublecolon_start = -1
1757 best_doublecolon_len = 0
1758 doublecolon_start = -1
1759 doublecolon_len = 0
Nick Coghlandb7920b2012-08-20 10:19:12 +10001760 for index, hextet in enumerate(hextets):
1761 if hextet == '0':
Nick Coghlandc9b2552012-05-20 21:01:57 +10001762 doublecolon_len += 1
1763 if doublecolon_start == -1:
1764 # Start of a sequence of zeros.
1765 doublecolon_start = index
1766 if doublecolon_len > best_doublecolon_len:
1767 # This is the longest sequence of zeros so far.
1768 best_doublecolon_len = doublecolon_len
1769 best_doublecolon_start = doublecolon_start
1770 else:
1771 doublecolon_len = 0
1772 doublecolon_start = -1
1773
1774 if best_doublecolon_len > 1:
1775 best_doublecolon_end = (best_doublecolon_start +
1776 best_doublecolon_len)
1777 # For zeros at the end of the address.
1778 if best_doublecolon_end == len(hextets):
1779 hextets += ['']
1780 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1781 # For zeros at the beginning of the address.
1782 if best_doublecolon_start == 0:
1783 hextets = [''] + hextets
1784
1785 return hextets
1786
Antoine Pitrou45aba182014-05-15 20:18:41 +02001787 @classmethod
1788 def _string_from_ip_int(cls, ip_int=None):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001789 """Turns a 128-bit integer into hexadecimal notation.
1790
1791 Args:
1792 ip_int: An integer, the IP address.
1793
1794 Returns:
1795 A string, the hexadecimal representation of the address.
1796
1797 Raises:
1798 ValueError: The address is bigger than 128 bits of all ones.
1799
1800 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001801 if ip_int is None:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001802 ip_int = int(cls._ip)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001803
Antoine Pitrou45aba182014-05-15 20:18:41 +02001804 if ip_int > cls._ALL_ONES:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001805 raise ValueError('IPv6 address is too large')
1806
1807 hex_str = '%032x' % ip_int
Nick Coghlan7319f692012-07-07 21:43:30 +10001808 hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001809
Antoine Pitrou45aba182014-05-15 20:18:41 +02001810 hextets = cls._compress_hextets(hextets)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001811 return ':'.join(hextets)
1812
1813 def _explode_shorthand_ip_string(self):
1814 """Expand a shortened IPv6 address.
1815
1816 Args:
1817 ip_str: A string, the IPv6 address.
1818
1819 Returns:
1820 A string, the expanded IPv6 address.
1821
1822 """
1823 if isinstance(self, IPv6Network):
1824 ip_str = str(self.network_address)
1825 elif isinstance(self, IPv6Interface):
1826 ip_str = str(self.ip)
1827 else:
1828 ip_str = str(self)
1829
1830 ip_int = self._ip_int_from_string(ip_str)
Nick Coghlan7319f692012-07-07 21:43:30 +10001831 hex_str = '%032x' % ip_int
1832 parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001833 if isinstance(self, (_BaseNetwork, IPv6Interface)):
Nick Coghlane3ded952012-08-05 22:45:22 +10001834 return '%s/%d' % (':'.join(parts), self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001835 return ':'.join(parts)
1836
Eric V. Smithebdaaf42014-04-14 12:58:07 -04001837 def _reverse_pointer(self):
1838 """Return the reverse DNS pointer name for the IPv6 address.
1839
1840 This implements the method described in RFC3596 2.5.
1841
1842 """
1843 reverse_chars = self.exploded[::-1].replace(':', '')
1844 return '.'.join(reverse_chars) + '.ip6.arpa'
1845
opavlyuk21da76d2020-02-26 16:33:57 +02001846 @staticmethod
1847 def _split_scope_id(ip_str):
1848 """Helper function to parse IPv6 string address with scope id.
1849
1850 See RFC 4007 for details.
1851
1852 Args:
1853 ip_str: A string, the IPv6 address.
1854
1855 Returns:
1856 (addr, scope_id) tuple.
1857
1858 """
1859 addr, sep, scope_id = ip_str.partition('%')
1860 if not sep:
1861 scope_id = None
1862 elif not scope_id or '%' in scope_id:
1863 raise AddressValueError('Invalid IPv6 address: "%r"' % ip_str)
1864 return addr, scope_id
1865
Nick Coghlandc9b2552012-05-20 21:01:57 +10001866 @property
1867 def max_prefixlen(self):
1868 return self._max_prefixlen
1869
1870 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001871 def version(self):
1872 return self._version
1873
Nick Coghlandc9b2552012-05-20 21:01:57 +10001874
1875class IPv6Address(_BaseV6, _BaseAddress):
1876
Sandro Tosib95c6342012-05-23 23:17:22 +02001877 """Represent and manipulate single IPv6 Addresses."""
Nick Coghlandc9b2552012-05-20 21:01:57 +10001878
opavlyuk21da76d2020-02-26 16:33:57 +02001879 __slots__ = ('_ip', '_scope_id', '__weakref__')
Serhiy Storchaka88f64f32015-03-07 20:08:34 +02001880
Nick Coghlandc9b2552012-05-20 21:01:57 +10001881 def __init__(self, address):
1882 """Instantiate a new IPv6 address object.
1883
1884 Args:
1885 address: A string or integer representing the IP
1886
1887 Additionally, an integer can be passed, so
1888 IPv6Address('2001:db8::') ==
1889 IPv6Address(42540766411282592856903984951653826560)
1890 or, more generally
1891 IPv6Address(int(IPv6Address('2001:db8::'))) ==
1892 IPv6Address('2001:db8::')
1893
1894 Raises:
1895 AddressValueError: If address isn't a valid IPv6 address.
1896
1897 """
Nick Coghlandc9b2552012-05-20 21:01:57 +10001898 # Efficient constructor from integer.
1899 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001900 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001901 self._ip = address
opavlyuk21da76d2020-02-26 16:33:57 +02001902 self._scope_id = None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001903 return
1904
1905 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001906 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001907 self._check_packed_address(address, 16)
Nick Coghlandb7920b2012-08-20 10:19:12 +10001908 self._ip = int.from_bytes(address, 'big')
opavlyuk21da76d2020-02-26 16:33:57 +02001909 self._scope_id = None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001910 return
1911
1912 # Assume input argument to be string or any object representation
1913 # which converts into a formatted IP string.
1914 addr_str = str(address)
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +02001915 if '/' in addr_str:
1916 raise AddressValueError("Unexpected '/' in %r" % address)
opavlyuk21da76d2020-02-26 16:33:57 +02001917 addr_str, self._scope_id = self._split_scope_id(addr_str)
1918
Nick Coghlandc9b2552012-05-20 21:01:57 +10001919 self._ip = self._ip_int_from_string(addr_str)
1920
opavlyuk21da76d2020-02-26 16:33:57 +02001921 def __str__(self):
1922 ip_str = super().__str__()
1923 return ip_str + '%' + self._scope_id if self._scope_id else ip_str
1924
1925 def __hash__(self):
1926 return hash((self._ip, self._scope_id))
1927
1928 def __eq__(self, other):
1929 address_equal = super().__eq__(other)
1930 if address_equal is NotImplemented:
1931 return NotImplemented
1932 if not address_equal:
1933 return False
1934 return self._scope_id == getattr(other, '_scope_id', None)
1935
1936 @property
1937 def scope_id(self):
1938 """Identifier of a particular zone of the address's scope.
1939
1940 See RFC 4007 for details.
1941
1942 Returns:
1943 A string identifying the zone of the address if specified, else None.
1944
1945 """
1946 return self._scope_id
1947
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001948 @property
1949 def packed(self):
1950 """The binary representation of this address."""
1951 return v6_int_to_packed(self._ip)
1952
Nick Coghlan730f67f2012-08-05 22:02:18 +10001953 @property
1954 def is_multicast(self):
1955 """Test if the address is reserved for multicast use.
1956
1957 Returns:
1958 A boolean, True if the address is a multicast address.
1959 See RFC 2373 2.7 for details.
1960
1961 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001962 return self in self._constants._multicast_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001963
1964 @property
1965 def is_reserved(self):
1966 """Test if the address is otherwise IETF reserved.
1967
1968 Returns:
1969 A boolean, True if the address is within one of the
1970 reserved IPv6 Network ranges.
1971
1972 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001973 return any(self in x for x in self._constants._reserved_networks)
Nick Coghlan730f67f2012-08-05 22:02:18 +10001974
1975 @property
1976 def is_link_local(self):
1977 """Test if the address is reserved for link-local.
1978
1979 Returns:
1980 A boolean, True if the address is reserved per RFC 4291.
1981
1982 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001983 return self in self._constants._linklocal_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001984
1985 @property
1986 def is_site_local(self):
1987 """Test if the address is reserved for site-local.
1988
1989 Note that the site-local address space has been deprecated by RFC 3879.
1990 Use is_private to test if this address is in the space of unique local
1991 addresses as defined by RFC 4193.
1992
1993 Returns:
1994 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1995
1996 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001997 return self in self._constants._sitelocal_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001998
1999 @property
Peter Moodybe9c1b12013-10-22 12:36:21 -07002000 @functools.lru_cache()
Nick Coghlan730f67f2012-08-05 22:02:18 +10002001 def is_private(self):
2002 """Test if this address is allocated for private networks.
2003
2004 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07002005 A boolean, True if the address is reserved per
Miss Islington (bot)a44bb6d2021-05-17 12:42:08 -07002006 iana-ipv6-special-registry, or is ipv4_mapped and is
2007 reserved in the iana-ipv4-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10002008
2009 """
Miss Islington (bot)a44bb6d2021-05-17 12:42:08 -07002010 ipv4_mapped = self.ipv4_mapped
2011 if ipv4_mapped is not None:
2012 return ipv4_mapped.is_private
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002013 return any(self in net for net in self._constants._private_networks)
Peter Moody22c31762013-10-21 13:58:06 -07002014
2015 @property
2016 def is_global(self):
2017 """Test if this address is allocated for public networks.
2018
2019 Returns:
2020 A boolean, true if the address is not reserved per
2021 iana-ipv6-special-registry.
2022
2023 """
2024 return not self.is_private
Nick Coghlan730f67f2012-08-05 22:02:18 +10002025
2026 @property
2027 def is_unspecified(self):
2028 """Test if the address is unspecified.
2029
2030 Returns:
2031 A boolean, True if this is the unspecified address as defined in
2032 RFC 2373 2.5.2.
2033
2034 """
2035 return self._ip == 0
2036
2037 @property
2038 def is_loopback(self):
2039 """Test if the address is a loopback address.
2040
2041 Returns:
2042 A boolean, True if the address is a loopback address as defined in
2043 RFC 2373 2.5.3.
2044
2045 """
2046 return self._ip == 1
2047
2048 @property
2049 def ipv4_mapped(self):
2050 """Return the IPv4 mapped address.
2051
2052 Returns:
2053 If the IPv6 address is a v4 mapped address, return the
2054 IPv4 mapped address. Return None otherwise.
2055
2056 """
2057 if (self._ip >> 32) != 0xFFFF:
2058 return None
2059 return IPv4Address(self._ip & 0xFFFFFFFF)
2060
2061 @property
2062 def teredo(self):
2063 """Tuple of embedded teredo IPs.
2064
2065 Returns:
2066 Tuple of the (server, client) IPs or None if the address
2067 doesn't appear to be a teredo address (doesn't start with
2068 2001::/32)
2069
2070 """
2071 if (self._ip >> 96) != 0x20010000:
2072 return None
2073 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
2074 IPv4Address(~self._ip & 0xFFFFFFFF))
2075
2076 @property
2077 def sixtofour(self):
2078 """Return the IPv4 6to4 embedded address.
2079
2080 Returns:
2081 The IPv4 6to4-embedded address if present or None if the
2082 address doesn't appear to contain a 6to4 embedded address.
2083
2084 """
2085 if (self._ip >> 112) != 0x2002:
2086 return None
2087 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
2088
Nick Coghlandc9b2552012-05-20 21:01:57 +10002089
2090class IPv6Interface(IPv6Address):
2091
2092 def __init__(self, address):
Inada Naoki6fa84bd2019-04-16 08:32:28 +09002093 addr, mask = self._split_addr_prefix(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002094
Inada Naoki6fa84bd2019-04-16 08:32:28 +09002095 IPv6Address.__init__(self, addr)
2096 self.network = IPv6Network((addr, mask), strict=False)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002097 self.netmask = self.network.netmask
2098 self._prefixlen = self.network._prefixlen
Inada Naoki6fa84bd2019-04-16 08:32:28 +09002099
2100 @functools.cached_property
2101 def hostmask(self):
2102 return self.network.hostmask
Nick Coghlandc9b2552012-05-20 21:01:57 +10002103
Nick Coghlandc9b2552012-05-20 21:01:57 +10002104 def __str__(self):
opavlyuk21da76d2020-02-26 16:33:57 +02002105 return '%s/%d' % (super().__str__(),
Inada Naoki2430d532019-04-15 16:01:00 +09002106 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002107
2108 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10002109 address_equal = IPv6Address.__eq__(self, other)
MojoVampire469325c2020-03-03 18:50:17 +00002110 if address_equal is NotImplemented or not address_equal:
Nick Coghlan3008ec02012-07-08 00:45:33 +10002111 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10002112 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10002113 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10002114 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10002115 # An interface with an associated network is NOT the
2116 # same as an unassociated address. That's why the hash
2117 # takes the extra info into account.
2118 return False
2119
2120 def __lt__(self, other):
2121 address_less = IPv6Address.__lt__(self, other)
2122 if address_less is NotImplemented:
MojoVampire469325c2020-03-03 18:50:17 +00002123 return address_less
Nick Coghlan3008ec02012-07-08 00:45:33 +10002124 try:
s-sanjay7bd8d3e2017-03-31 23:09:53 -07002125 return (self.network < other.network or
2126 self.network == other.network and address_less)
Nick Coghlan3008ec02012-07-08 00:45:33 +10002127 except AttributeError:
2128 # We *do* allow addresses and interfaces to be sorted. The
2129 # unassociated address is considered less than all interfaces.
2130 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10002131
2132 def __hash__(self):
Ravi Teja Pb30ee262020-06-29 23:09:29 +05302133 return hash((self._ip, self._prefixlen, int(self.network.network_address)))
Nick Coghlandc9b2552012-05-20 21:01:57 +10002134
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +02002135 __reduce__ = _IPAddressBase.__reduce__
2136
Nick Coghlandc9b2552012-05-20 21:01:57 +10002137 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10002138 def ip(self):
2139 return IPv6Address(self._ip)
2140
2141 @property
2142 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10002143 return '%s/%s' % (self._string_from_ip_int(self._ip),
2144 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002145
2146 @property
2147 def with_netmask(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10002148 return '%s/%s' % (self._string_from_ip_int(self._ip),
2149 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02002150
Nick Coghlandc9b2552012-05-20 21:01:57 +10002151 @property
2152 def with_hostmask(self):
2153 return '%s/%s' % (self._string_from_ip_int(self._ip),
2154 self.hostmask)
2155
Nick Coghlan730f67f2012-08-05 22:02:18 +10002156 @property
2157 def is_unspecified(self):
2158 return self._ip == 0 and self.network.is_unspecified
2159
2160 @property
2161 def is_loopback(self):
2162 return self._ip == 1 and self.network.is_loopback
2163
Nick Coghlandc9b2552012-05-20 21:01:57 +10002164
2165class IPv6Network(_BaseV6, _BaseNetwork):
2166
2167 """This class represents and manipulates 128-bit IPv6 networks.
2168
2169 Attributes: [examples for IPv6('2001:db8::1000/124')]
2170 .network_address: IPv6Address('2001:db8::1000')
2171 .hostmask: IPv6Address('::f')
2172 .broadcast_address: IPv6Address('2001:db8::100f')
2173 .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
2174 .prefixlen: 124
2175
2176 """
2177
Nick Coghlan51c30672012-05-27 00:25:58 +10002178 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10002179 _address_class = IPv6Address
2180
Nick Coghlandc9b2552012-05-20 21:01:57 +10002181 def __init__(self, address, strict=True):
2182 """Instantiate a new IPv6 Network object.
2183
2184 Args:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02002185 address: A string or integer representing the IPv6 network or the
2186 IP and prefix/netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +10002187 '2001:db8::/128'
2188 '2001:db8:0000:0000:0000:0000:0000:0000/128'
2189 '2001:db8::'
2190 are all functionally the same in IPv6. That is to say,
2191 failing to provide a subnetmask will create an object with
2192 a mask of /128.
2193
2194 Additionally, an integer can be passed, so
2195 IPv6Network('2001:db8::') ==
2196 IPv6Network(42540766411282592856903984951653826560)
2197 or, more generally
2198 IPv6Network(int(IPv6Network('2001:db8::'))) ==
2199 IPv6Network('2001:db8::')
2200
2201 strict: A boolean. If true, ensure that we have been passed
2202 A true network address, eg, 2001:db8::1000/124 and not an
2203 IP address on a network, eg, 2001:db8::1/124.
2204
2205 Raises:
2206 AddressValueError: If address isn't a valid IPv6 address.
2207 NetmaskValueError: If the netmask isn't valid for
2208 an IPv6 address.
2209 ValueError: If strict was True and a network address was not
2210 supplied.
Nick Coghlandc9b2552012-05-20 21:01:57 +10002211 """
Inada Naoki6fa84bd2019-04-16 08:32:28 +09002212 addr, mask = self._split_addr_prefix(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002213
Xiang Zhang10b134a2018-03-21 08:25:13 +08002214 self.network_address = IPv6Address(addr)
2215 self.netmask, self._prefixlen = self._make_netmask(mask)
2216 packed = int(self.network_address)
2217 if packed & int(self.netmask) != packed:
2218 if strict:
Nick Coghlan912238e2012-07-07 13:34:50 +10002219 raise ValueError('%s has host bits set' % self)
Xiang Zhang10b134a2018-03-21 08:25:13 +08002220 else:
2221 self.network_address = IPv6Address(packed &
2222 int(self.netmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +10002223
2224 if self._prefixlen == (self._max_prefixlen - 1):
2225 self.hosts = self.__iter__
Pete Wicken8e9c47a2020-03-09 22:33:45 +00002226 elif self._prefixlen == self._max_prefixlen:
2227 self.hosts = lambda: [IPv6Address(addr)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10002228
Peter Moody1243c7d2014-03-11 09:55:46 -07002229 def hosts(self):
2230 """Generate Iterator over usable hosts in a network.
2231
2232 This is like __iter__ except it doesn't return the
2233 Subnet-Router anycast address.
2234
2235 """
2236 network = int(self.network_address)
2237 broadcast = int(self.broadcast_address)
2238 for x in range(network + 1, broadcast + 1):
2239 yield self._address_class(x)
2240
Nick Coghlan730f67f2012-08-05 22:02:18 +10002241 @property
2242 def is_site_local(self):
2243 """Test if the address is reserved for site-local.
2244
2245 Note that the site-local address space has been deprecated by RFC 3879.
2246 Use is_private to test if this address is in the space of unique local
2247 addresses as defined by RFC 4193.
2248
2249 Returns:
2250 A boolean, True if the address is reserved per RFC 3513 2.5.6.
2251
2252 """
2253 return (self.network_address.is_site_local and
2254 self.broadcast_address.is_site_local)
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002255
2256
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002257class _IPv6Constants:
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002258
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002259 _linklocal_network = IPv6Network('fe80::/10')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002260
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002261 _multicast_network = IPv6Network('ff00::/8')
2262
2263 _private_networks = [
2264 IPv6Network('::1/128'),
2265 IPv6Network('::/128'),
2266 IPv6Network('::ffff:0:0/96'),
2267 IPv6Network('100::/64'),
2268 IPv6Network('2001::/23'),
2269 IPv6Network('2001:2::/48'),
2270 IPv6Network('2001:db8::/32'),
2271 IPv6Network('2001:10::/28'),
2272 IPv6Network('fc00::/7'),
2273 IPv6Network('fe80::/10'),
2274 ]
2275
2276 _reserved_networks = [
2277 IPv6Network('::/8'), IPv6Network('100::/8'),
2278 IPv6Network('200::/7'), IPv6Network('400::/6'),
2279 IPv6Network('800::/5'), IPv6Network('1000::/4'),
2280 IPv6Network('4000::/3'), IPv6Network('6000::/3'),
2281 IPv6Network('8000::/3'), IPv6Network('A000::/3'),
2282 IPv6Network('C000::/3'), IPv6Network('E000::/4'),
2283 IPv6Network('F000::/5'), IPv6Network('F800::/6'),
2284 IPv6Network('FE00::/9'),
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002285 ]
2286
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002287 _sitelocal_network = IPv6Network('fec0::/10')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002288
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002289
2290IPv6Address._constants = _IPv6Constants