blob: 70746f8de85c092368f163caf97071439fc2465f [file] [log] [blame]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001# Copyright 2007 Google Inc.
2# Licensed to PSF under a Contributor Agreement.
Nick Coghlandc9b2552012-05-20 21:01:57 +10003
4"""A fast, lightweight IPv4/IPv6 manipulation library in Python.
5
6This library is used to create/poke/manipulate IPv4 and IPv6 addresses
7and networks.
8
9"""
10
11__version__ = '1.0'
12
Hynek Schlawack91c5a342012-06-05 11:55:58 +020013
Nick Coghlan3008ec02012-07-08 00:45:33 +100014import functools
Hynek Schlawack91c5a342012-06-05 11:55:58 +020015
Nick Coghlandc9b2552012-05-20 21:01:57 +100016IPV4LENGTH = 32
17IPV6LENGTH = 128
18
Nick Coghlandc9b2552012-05-20 21:01:57 +100019class AddressValueError(ValueError):
20 """A Value Error related to the address."""
21
22
23class NetmaskValueError(ValueError):
24 """A Value Error related to the netmask."""
25
26
Nick Coghlan51c30672012-05-27 00:25:58 +100027def ip_address(address):
Nick Coghlandc9b2552012-05-20 21:01:57 +100028 """Take an IP string/int and return an object of the correct type.
29
30 Args:
31 address: A string or integer, the IP address. Either IPv4 or
32 IPv6 addresses may be supplied; integers less than 2**32 will
33 be considered to be IPv4 by default.
Nick Coghlandc9b2552012-05-20 21:01:57 +100034
35 Returns:
36 An IPv4Address or IPv6Address object.
37
38 Raises:
Sandro Tosi876ecad2012-05-23 22:26:55 +020039 ValueError: if the *address* passed isn't either a v4 or a v6
Nick Coghlan51c30672012-05-27 00:25:58 +100040 address
Nick Coghlandc9b2552012-05-20 21:01:57 +100041
42 """
Nick Coghlandc9b2552012-05-20 21:01:57 +100043 try:
44 return IPv4Address(address)
45 except (AddressValueError, NetmaskValueError):
46 pass
47
48 try:
49 return IPv6Address(address)
50 except (AddressValueError, NetmaskValueError):
51 pass
52
53 raise ValueError('%r does not appear to be an IPv4 or IPv6 address' %
54 address)
55
56
Nick Coghlan51c30672012-05-27 00:25:58 +100057def ip_network(address, strict=True):
Nick Coghlandc9b2552012-05-20 21:01:57 +100058 """Take an IP string/int and return an object of the correct type.
59
60 Args:
61 address: A string or integer, the IP network. Either IPv4 or
62 IPv6 networks may be supplied; integers less than 2**32 will
63 be considered to be IPv4 by default.
Nick Coghlandc9b2552012-05-20 21:01:57 +100064
65 Returns:
66 An IPv4Network or IPv6Network object.
67
68 Raises:
69 ValueError: if the string passed isn't either a v4 or a v6
Nick Coghlan51c30672012-05-27 00:25:58 +100070 address. Or if the network has host bits set.
Nick Coghlandc9b2552012-05-20 21:01:57 +100071
72 """
Nick Coghlandc9b2552012-05-20 21:01:57 +100073 try:
74 return IPv4Network(address, strict)
75 except (AddressValueError, NetmaskValueError):
76 pass
77
78 try:
79 return IPv6Network(address, strict)
80 except (AddressValueError, NetmaskValueError):
81 pass
82
83 raise ValueError('%r does not appear to be an IPv4 or IPv6 network' %
84 address)
85
86
Nick Coghlan51c30672012-05-27 00:25:58 +100087def ip_interface(address):
Nick Coghlandc9b2552012-05-20 21:01:57 +100088 """Take an IP string/int and return an object of the correct type.
89
90 Args:
91 address: A string or integer, the IP address. Either IPv4 or
92 IPv6 addresses may be supplied; integers less than 2**32 will
93 be considered to be IPv4 by default.
Nick Coghlandc9b2552012-05-20 21:01:57 +100094
95 Returns:
Sandro Tosi876ecad2012-05-23 22:26:55 +020096 An IPv4Interface or IPv6Interface object.
Nick Coghlandc9b2552012-05-20 21:01:57 +100097
98 Raises:
99 ValueError: if the string passed isn't either a v4 or a v6
Nick Coghlan51c30672012-05-27 00:25:58 +1000100 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000101
102 Notes:
103 The IPv?Interface classes describe an Address on a particular
104 Network, so they're basically a combination of both the Address
105 and Network classes.
Sandro Tosib95c6342012-05-23 23:17:22 +0200106
Nick Coghlandc9b2552012-05-20 21:01:57 +1000107 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000108 try:
109 return IPv4Interface(address)
110 except (AddressValueError, NetmaskValueError):
111 pass
112
113 try:
114 return IPv6Interface(address)
115 except (AddressValueError, NetmaskValueError):
116 pass
117
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000118 raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' %
Nick Coghlandc9b2552012-05-20 21:01:57 +1000119 address)
120
121
122def v4_int_to_packed(address):
Sandro Tosi876ecad2012-05-23 22:26:55 +0200123 """Represent an address as 4 packed bytes in network (big-endian) order.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000124
125 Args:
126 address: An integer representation of an IPv4 IP address.
127
128 Returns:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200129 The integer address packed as 4 bytes in network (big-endian) order.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000130
131 Raises:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200132 ValueError: If the integer is negative or too large to be an
133 IPv4 IP address.
Sandro Tosib95c6342012-05-23 23:17:22 +0200134
Nick Coghlandc9b2552012-05-20 21:01:57 +1000135 """
Sandro Tosi876ecad2012-05-23 22:26:55 +0200136 try:
Nick Coghlandb7920b2012-08-20 10:19:12 +1000137 return address.to_bytes(4, 'big')
Serhiy Storchakaba9ac5b2015-05-20 10:33:40 +0300138 except OverflowError:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200139 raise ValueError("Address negative or too large for IPv4")
Nick Coghlandc9b2552012-05-20 21:01:57 +1000140
141
142def v6_int_to_packed(address):
Sandro Tosi876ecad2012-05-23 22:26:55 +0200143 """Represent an address as 16 packed bytes in network (big-endian) order.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000144
145 Args:
Sandro Tosib4386d32012-06-02 17:14:22 +0200146 address: An integer representation of an IPv6 IP address.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000147
148 Returns:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200149 The integer address packed as 16 bytes in network (big-endian) order.
Sandro Tosib95c6342012-05-23 23:17:22 +0200150
Nick Coghlandc9b2552012-05-20 21:01:57 +1000151 """
Sandro Tosi876ecad2012-05-23 22:26:55 +0200152 try:
Nick Coghlandb7920b2012-08-20 10:19:12 +1000153 return address.to_bytes(16, 'big')
Serhiy Storchakaba9ac5b2015-05-20 10:33:40 +0300154 except OverflowError:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200155 raise ValueError("Address negative or too large for IPv6")
Nick Coghlandc9b2552012-05-20 21:01:57 +1000156
157
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000158def _split_optional_netmask(address):
159 """Helper to split the netmask and raise AddressValueError if needed"""
160 addr = str(address).split('/')
161 if len(addr) > 2:
162 raise AddressValueError("Only one '/' permitted in %r" % address)
163 return addr
164
Nick Coghlan297b1432012-07-08 17:11:04 +1000165
Nick Coghlandc9b2552012-05-20 21:01:57 +1000166def _find_address_range(addresses):
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200167 """Find a sequence of sorted deduplicated IPv#Address.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000168
169 Args:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200170 addresses: a list of IPv#Address objects.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000171
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200172 Yields:
173 A tuple containing the first and last IP addresses in the sequence.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000174
175 """
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200176 it = iter(addresses)
177 first = last = next(it)
178 for ip in it:
179 if ip._ip != last._ip + 1:
180 yield first, last
181 first = ip
182 last = ip
183 yield first, last
Nick Coghlandc9b2552012-05-20 21:01:57 +1000184
Sandro Tosib95c6342012-05-23 23:17:22 +0200185
Nick Coghlandc9b2552012-05-20 21:01:57 +1000186def _count_righthand_zero_bits(number, bits):
187 """Count the number of zero bits on the right hand side.
188
189 Args:
190 number: an integer.
191 bits: maximum number of bits to count.
192
193 Returns:
194 The number of zero bits on the right hand side of the number.
195
196 """
197 if number == 0:
198 return bits
Antoine Pitrou824db302014-05-15 20:21:48 +0200199 return min(bits, (~number & (number-1)).bit_length())
Nick Coghlandc9b2552012-05-20 21:01:57 +1000200
201
202def summarize_address_range(first, last):
203 """Summarize a network range given the first and last IP addresses.
204
205 Example:
Eli Bendersky948af232012-10-07 07:23:50 -0700206 >>> list(summarize_address_range(IPv4Address('192.0.2.0'),
207 ... IPv4Address('192.0.2.130')))
208 ... #doctest: +NORMALIZE_WHITESPACE
Nick Coghlandc9b2552012-05-20 21:01:57 +1000209 [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'),
Eli Bendersky948af232012-10-07 07:23:50 -0700210 IPv4Network('192.0.2.130/32')]
Nick Coghlandc9b2552012-05-20 21:01:57 +1000211
212 Args:
213 first: the first IPv4Address or IPv6Address in the range.
214 last: the last IPv4Address or IPv6Address in the range.
215
216 Returns:
217 An iterator of the summarized IPv(4|6) network objects.
218
219 Raise:
220 TypeError:
221 If the first and last objects are not IP addresses.
222 If the first and last objects are not the same version.
223 ValueError:
224 If the last object is not greater than the first.
Nick Coghlan51c30672012-05-27 00:25:58 +1000225 If the version of the first address is not 4 or 6.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000226
227 """
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200228 if (not (isinstance(first, _BaseAddress) and
229 isinstance(last, _BaseAddress))):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000230 raise TypeError('first and last must be IP addresses, not networks')
231 if first.version != last.version:
232 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000233 first, last))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000234 if first > last:
235 raise ValueError('last IP address must be greater than first')
236
Nick Coghlandc9b2552012-05-20 21:01:57 +1000237 if first.version == 4:
238 ip = IPv4Network
239 elif first.version == 6:
240 ip = IPv6Network
241 else:
242 raise ValueError('unknown IP version')
243
244 ip_bits = first._max_prefixlen
245 first_int = first._ip
246 last_int = last._ip
247 while first_int <= last_int:
Nick Coghlan7319f692012-07-07 21:43:30 +1000248 nbits = min(_count_righthand_zero_bits(first_int, ip_bits),
249 (last_int - first_int + 1).bit_length() - 1)
Antoine Pitrou824db302014-05-15 20:21:48 +0200250 net = ip((first_int, ip_bits - nbits))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000251 yield net
Nick Coghlan7319f692012-07-07 21:43:30 +1000252 first_int += 1 << nbits
253 if first_int - 1 == ip._ALL_ONES:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000254 break
Nick Coghlandc9b2552012-05-20 21:01:57 +1000255
Sandro Tosib95c6342012-05-23 23:17:22 +0200256
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200257def _collapse_addresses_internal(addresses):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000258 """Loops through the addresses, collapsing concurrent netblocks.
259
260 Example:
261
262 ip1 = IPv4Network('192.0.2.0/26')
263 ip2 = IPv4Network('192.0.2.64/26')
264 ip3 = IPv4Network('192.0.2.128/26')
265 ip4 = IPv4Network('192.0.2.192/26')
266
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200267 _collapse_addresses_internal([ip1, ip2, ip3, ip4]) ->
Nick Coghlandc9b2552012-05-20 21:01:57 +1000268 [IPv4Network('192.0.2.0/24')]
269
270 This shouldn't be called directly; it is called via
271 collapse_addresses([]).
272
273 Args:
274 addresses: A list of IPv4Network's or IPv6Network's
275
276 Returns:
277 A list of IPv4Network's or IPv6Network's depending on what we were
278 passed.
279
280 """
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200281 # First merge
282 to_merge = list(addresses)
283 subnets = {}
284 while to_merge:
285 net = to_merge.pop()
286 supernet = net.supernet()
287 existing = subnets.get(supernet)
288 if existing is None:
289 subnets[supernet] = net
290 elif existing != net:
291 # Merge consecutive subnets
292 del subnets[supernet]
293 to_merge.append(supernet)
294 # Then iterate over resulting networks, skipping subsumed subnets
295 last = None
296 for net in sorted(subnets.values()):
297 if last is not None:
298 # Since they are sorted, last.network_address <= net.network_address
299 # is a given.
300 if last.broadcast_address >= net.broadcast_address:
301 continue
302 yield net
303 last = net
Nick Coghlandc9b2552012-05-20 21:01:57 +1000304
305
306def collapse_addresses(addresses):
307 """Collapse a list of IP objects.
308
309 Example:
310 collapse_addresses([IPv4Network('192.0.2.0/25'),
311 IPv4Network('192.0.2.128/25')]) ->
312 [IPv4Network('192.0.2.0/24')]
313
314 Args:
315 addresses: An iterator of IPv4Network or IPv6Network objects.
316
317 Returns:
318 An iterator of the collapsed IPv(4|6)Network objects.
319
320 Raises:
321 TypeError: If passed a list of mixed version objects.
322
323 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000324 addrs = []
325 ips = []
326 nets = []
327
328 # split IP addresses and networks
329 for ip in addresses:
330 if isinstance(ip, _BaseAddress):
331 if ips and ips[-1]._version != ip._version:
332 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000333 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000334 ips.append(ip)
335 elif ip._prefixlen == ip._max_prefixlen:
336 if ips and ips[-1]._version != ip._version:
337 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000338 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000339 try:
340 ips.append(ip.ip)
341 except AttributeError:
342 ips.append(ip.network_address)
343 else:
344 if nets and nets[-1]._version != ip._version:
345 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000346 ip, nets[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000347 nets.append(ip)
348
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200349 # sort and dedup
350 ips = sorted(set(ips))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000351
Antoine Pitroue6f250e2015-01-18 16:22:47 +0100352 # find consecutive address ranges in the sorted sequence and summarize them
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200353 if ips:
354 for first, last in _find_address_range(ips):
355 addrs.extend(summarize_address_range(first, last))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000356
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200357 return _collapse_addresses_internal(addrs + nets)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000358
359
360def get_mixed_type_key(obj):
361 """Return a key suitable for sorting between networks and addresses.
362
363 Address and Network objects are not sortable by default; they're
364 fundamentally different so the expression
365
366 IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
367
368 doesn't make any sense. There are some times however, where you may wish
369 to have ipaddress sort these for you anyway. If you need to do this, you
370 can use this function as the key= argument to sorted().
371
372 Args:
373 obj: either a Network or Address object.
374 Returns:
375 appropriate key.
376
377 """
378 if isinstance(obj, _BaseNetwork):
379 return obj._get_networks_key()
380 elif isinstance(obj, _BaseAddress):
381 return obj._get_address_key()
382 return NotImplemented
383
384
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200385class _IPAddressBase:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000386
387 """The mother class."""
388
Serhiy Storchaka88f64f32015-03-07 20:08:34 +0200389 __slots__ = ()
390
Nick Coghlandc9b2552012-05-20 21:01:57 +1000391 @property
392 def exploded(self):
393 """Return the longhand version of the IP address as a string."""
394 return self._explode_shorthand_ip_string()
395
396 @property
397 def compressed(self):
398 """Return the shorthand version of the IP address as a string."""
399 return str(self)
400
Nick Coghland9722652012-06-17 16:33:00 +1000401 @property
Eric V. Smithebdaaf42014-04-14 12:58:07 -0400402 def reverse_pointer(self):
403 """The name of the reverse DNS pointer for the IP address, e.g.:
404 >>> ipaddress.ip_address("127.0.0.1").reverse_pointer
405 '1.0.0.127.in-addr.arpa'
406 >>> ipaddress.ip_address("2001:db8::1").reverse_pointer
407 '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa'
408
409 """
410 return self._reverse_pointer()
411
412 @property
Nick Coghland9722652012-06-17 16:33:00 +1000413 def version(self):
414 msg = '%200s has no version specified' % (type(self),)
415 raise NotImplementedError(msg)
416
Nick Coghlan297b1432012-07-08 17:11:04 +1000417 def _check_int_address(self, address):
418 if address < 0:
419 msg = "%d (< 0) is not permitted as an IPv%d address"
420 raise AddressValueError(msg % (address, self._version))
421 if address > self._ALL_ONES:
422 msg = "%d (>= 2**%d) is not permitted as an IPv%d address"
423 raise AddressValueError(msg % (address, self._max_prefixlen,
424 self._version))
425
426 def _check_packed_address(self, address, expected_len):
427 address_len = len(address)
428 if address_len != expected_len:
429 msg = "%r (len %d != %d) is not permitted as an IPv%d address"
430 raise AddressValueError(msg % (address, address_len,
431 expected_len, self._version))
432
Antoine Pitrou45aba182014-05-15 20:18:41 +0200433 @classmethod
434 def _ip_int_from_prefix(cls, prefixlen):
Nick Coghlan932346f2014-02-08 23:17:36 +1000435 """Turn the prefix length into a bitwise netmask
Nick Coghlandc9b2552012-05-20 21:01:57 +1000436
437 Args:
438 prefixlen: An integer, the prefix length.
439
440 Returns:
441 An integer.
442
443 """
Antoine Pitrou45aba182014-05-15 20:18:41 +0200444 return cls._ALL_ONES ^ (cls._ALL_ONES >> prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000445
Antoine Pitrou45aba182014-05-15 20:18:41 +0200446 @classmethod
447 def _prefix_from_ip_int(cls, ip_int):
Nick Coghlan932346f2014-02-08 23:17:36 +1000448 """Return prefix length from the bitwise netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000449
450 Args:
Berker Peksagf23530f2014-10-19 18:04:38 +0300451 ip_int: An integer, the netmask in expanded bitwise format
Nick Coghlandc9b2552012-05-20 21:01:57 +1000452
453 Returns:
454 An integer, the prefix length.
455
Nick Coghlan932346f2014-02-08 23:17:36 +1000456 Raises:
457 ValueError: If the input intermingles zeroes & ones
Nick Coghlandc9b2552012-05-20 21:01:57 +1000458 """
Nick Coghlan932346f2014-02-08 23:17:36 +1000459 trailing_zeroes = _count_righthand_zero_bits(ip_int,
Antoine Pitrou45aba182014-05-15 20:18:41 +0200460 cls._max_prefixlen)
461 prefixlen = cls._max_prefixlen - trailing_zeroes
Nick Coghlan932346f2014-02-08 23:17:36 +1000462 leading_ones = ip_int >> trailing_zeroes
463 all_ones = (1 << prefixlen) - 1
464 if leading_ones != all_ones:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200465 byteslen = cls._max_prefixlen // 8
Nick Coghlan932346f2014-02-08 23:17:36 +1000466 details = ip_int.to_bytes(byteslen, 'big')
467 msg = 'Netmask pattern %r mixes zeroes & ones'
468 raise ValueError(msg % details)
469 return prefixlen
Nick Coghlandc9b2552012-05-20 21:01:57 +1000470
Antoine Pitrou45aba182014-05-15 20:18:41 +0200471 @classmethod
472 def _report_invalid_netmask(cls, netmask_str):
Nick Coghlan932346f2014-02-08 23:17:36 +1000473 msg = '%r is not a valid netmask' % netmask_str
474 raise NetmaskValueError(msg) from None
475
Antoine Pitrou45aba182014-05-15 20:18:41 +0200476 @classmethod
477 def _prefix_from_prefix_string(cls, prefixlen_str):
Nick Coghlan932346f2014-02-08 23:17:36 +1000478 """Return prefix length from a numeric string
Nick Coghlandc9b2552012-05-20 21:01:57 +1000479
480 Args:
Nick Coghlan932346f2014-02-08 23:17:36 +1000481 prefixlen_str: The string to be converted
Nick Coghlandc9b2552012-05-20 21:01:57 +1000482
483 Returns:
Nick Coghlan932346f2014-02-08 23:17:36 +1000484 An integer, the prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000485
Nick Coghlan932346f2014-02-08 23:17:36 +1000486 Raises:
487 NetmaskValueError: If the input is not a valid netmask
Nick Coghlandc9b2552012-05-20 21:01:57 +1000488 """
Nick Coghlan932346f2014-02-08 23:17:36 +1000489 # int allows a leading +/- as well as surrounding whitespace,
490 # so we ensure that isn't the case
491 if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
Antoine Pitrou45aba182014-05-15 20:18:41 +0200492 cls._report_invalid_netmask(prefixlen_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000493 try:
494 prefixlen = int(prefixlen_str)
495 except ValueError:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200496 cls._report_invalid_netmask(prefixlen_str)
497 if not (0 <= prefixlen <= cls._max_prefixlen):
498 cls._report_invalid_netmask(prefixlen_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000499 return prefixlen
500
Antoine Pitrou45aba182014-05-15 20:18:41 +0200501 @classmethod
502 def _prefix_from_ip_string(cls, ip_str):
Nick Coghlan932346f2014-02-08 23:17:36 +1000503 """Turn a netmask/hostmask string into a prefix length
504
505 Args:
506 ip_str: The netmask/hostmask to be converted
507
508 Returns:
509 An integer, the prefix length.
510
511 Raises:
512 NetmaskValueError: If the input is not a valid netmask/hostmask
513 """
514 # Parse the netmask/hostmask like an IP address.
515 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200516 ip_int = cls._ip_int_from_string(ip_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000517 except AddressValueError:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200518 cls._report_invalid_netmask(ip_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000519
520 # Try matching a netmask (this would be /1*0*/ as a bitwise regexp).
521 # Note that the two ambiguous cases (all-ones and all-zeroes) are
522 # treated as netmasks.
523 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200524 return cls._prefix_from_ip_int(ip_int)
Nick Coghlan932346f2014-02-08 23:17:36 +1000525 except ValueError:
526 pass
527
528 # Invert the bits, and try matching a /0+1+/ hostmask instead.
Antoine Pitrou45aba182014-05-15 20:18:41 +0200529 ip_int ^= cls._ALL_ONES
Nick Coghlan932346f2014-02-08 23:17:36 +1000530 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200531 return cls._prefix_from_ip_int(ip_int)
Nick Coghlan932346f2014-02-08 23:17:36 +1000532 except ValueError:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200533 cls._report_invalid_netmask(ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000534
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +0200535 def __reduce__(self):
536 return self.__class__, (str(self),)
537
Nick Coghlan730f67f2012-08-05 22:02:18 +1000538
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200539@functools.total_ordering
Nick Coghlandc9b2552012-05-20 21:01:57 +1000540class _BaseAddress(_IPAddressBase):
541
542 """A generic IP object.
543
544 This IP class contains the version independent methods which are
545 used by single IP addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000546 """
547
Serhiy Storchaka88f64f32015-03-07 20:08:34 +0200548 __slots__ = ()
549
Nick Coghlandc9b2552012-05-20 21:01:57 +1000550 def __int__(self):
551 return self._ip
552
Nick Coghlandc9b2552012-05-20 21:01:57 +1000553 def __eq__(self, other):
554 try:
555 return (self._ip == other._ip
556 and self._version == other._version)
557 except AttributeError:
558 return NotImplemented
559
Nick Coghlandc9b2552012-05-20 21:01:57 +1000560 def __lt__(self, other):
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200561 if not isinstance(other, _BaseAddress):
562 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000563 if self._version != other._version:
564 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000565 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000566 if self._ip != other._ip:
567 return self._ip < other._ip
568 return False
569
Nick Coghlandc9b2552012-05-20 21:01:57 +1000570 # Shorthand for Integer addition and subtraction. This is not
571 # meant to ever support addition/subtraction of addresses.
572 def __add__(self, other):
573 if not isinstance(other, int):
574 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000575 return self.__class__(int(self) + other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000576
577 def __sub__(self, other):
578 if not isinstance(other, int):
579 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000580 return self.__class__(int(self) - other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000581
582 def __repr__(self):
583 return '%s(%r)' % (self.__class__.__name__, str(self))
584
585 def __str__(self):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200586 return str(self._string_from_ip_int(self._ip))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000587
588 def __hash__(self):
589 return hash(hex(int(self._ip)))
590
591 def _get_address_key(self):
592 return (self._version, self)
593
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +0200594 def __reduce__(self):
595 return self.__class__, (self._ip,)
596
Nick Coghlandc9b2552012-05-20 21:01:57 +1000597
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200598@functools.total_ordering
Nick Coghlandc9b2552012-05-20 21:01:57 +1000599class _BaseNetwork(_IPAddressBase):
600
Nick Coghlan51c30672012-05-27 00:25:58 +1000601 """A generic IP network object.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000602
603 This IP class contains the version independent methods which are
604 used by networks.
605
606 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000607 def __init__(self, address):
608 self._cache = {}
609
Nick Coghlandc9b2552012-05-20 21:01:57 +1000610 def __repr__(self):
611 return '%s(%r)' % (self.__class__.__name__, str(self))
612
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200613 def __str__(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000614 return '%s/%d' % (self.network_address, self.prefixlen)
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200615
Nick Coghlandc9b2552012-05-20 21:01:57 +1000616 def hosts(self):
617 """Generate Iterator over usable hosts in a network.
618
Sandro Tosib95c6342012-05-23 23:17:22 +0200619 This is like __iter__ except it doesn't return the network
620 or broadcast addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000621
622 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000623 network = int(self.network_address)
624 broadcast = int(self.broadcast_address)
625 for x in range(network + 1, broadcast):
626 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000627
628 def __iter__(self):
Nick Coghlan7319f692012-07-07 21:43:30 +1000629 network = int(self.network_address)
630 broadcast = int(self.broadcast_address)
631 for x in range(network, broadcast + 1):
632 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000633
634 def __getitem__(self, n):
635 network = int(self.network_address)
636 broadcast = int(self.broadcast_address)
637 if n >= 0:
638 if network + n > broadcast:
Berker Peksag28dc1182016-06-11 22:30:05 +0300639 raise IndexError('address out of range')
Nick Coghlan51c30672012-05-27 00:25:58 +1000640 return self._address_class(network + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000641 else:
642 n += 1
643 if broadcast + n < network:
Berker Peksag28dc1182016-06-11 22:30:05 +0300644 raise IndexError('address out of range')
Nick Coghlan51c30672012-05-27 00:25:58 +1000645 return self._address_class(broadcast + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000646
647 def __lt__(self, other):
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200648 if not isinstance(other, _BaseNetwork):
649 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000650 if self._version != other._version:
651 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000652 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000653 if self.network_address != other.network_address:
654 return self.network_address < other.network_address
655 if self.netmask != other.netmask:
656 return self.netmask < other.netmask
657 return False
658
Nick Coghlandc9b2552012-05-20 21:01:57 +1000659 def __eq__(self, other):
Nick Coghlan9a9c28c2012-07-07 23:05:59 +1000660 try:
661 return (self._version == other._version and
662 self.network_address == other.network_address and
663 int(self.netmask) == int(other.netmask))
664 except AttributeError:
665 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000666
Nick Coghlandc9b2552012-05-20 21:01:57 +1000667 def __hash__(self):
668 return hash(int(self.network_address) ^ int(self.netmask))
669
670 def __contains__(self, other):
671 # always false if one is v4 and the other is v6.
672 if self._version != other._version:
673 return False
674 # dealing with another network.
675 if isinstance(other, _BaseNetwork):
676 return False
677 # dealing with another address
678 else:
679 # address
680 return (int(self.network_address) <= int(other._ip) <=
681 int(self.broadcast_address))
682
683 def overlaps(self, other):
684 """Tell if self is partly contained in other."""
685 return self.network_address in other or (
686 self.broadcast_address in other or (
687 other.network_address in self or (
688 other.broadcast_address in self)))
689
690 @property
691 def broadcast_address(self):
692 x = self._cache.get('broadcast_address')
693 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000694 x = self._address_class(int(self.network_address) |
695 int(self.hostmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000696 self._cache['broadcast_address'] = x
697 return x
698
699 @property
700 def hostmask(self):
701 x = self._cache.get('hostmask')
702 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000703 x = self._address_class(int(self.netmask) ^ self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000704 self._cache['hostmask'] = x
705 return x
706
707 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000708 def with_prefixlen(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000709 return '%s/%d' % (self.network_address, self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000710
711 @property
712 def with_netmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000713 return '%s/%s' % (self.network_address, self.netmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000714
715 @property
716 def with_hostmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000717 return '%s/%s' % (self.network_address, self.hostmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000718
719 @property
720 def num_addresses(self):
721 """Number of hosts in the current subnet."""
722 return int(self.broadcast_address) - int(self.network_address) + 1
723
724 @property
Nick Coghlan51c30672012-05-27 00:25:58 +1000725 def _address_class(self):
Nick Coghland9722652012-06-17 16:33:00 +1000726 # Returning bare address objects (rather than interfaces) allows for
727 # more consistent behaviour across the network address, broadcast
728 # address and individual host addresses.
729 msg = '%200s has no associated address class' % (type(self),)
730 raise NotImplementedError(msg)
Nick Coghlan51c30672012-05-27 00:25:58 +1000731
732 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000733 def prefixlen(self):
734 return self._prefixlen
735
736 def address_exclude(self, other):
737 """Remove an address from a larger block.
738
739 For example:
740
741 addr1 = ip_network('192.0.2.0/28')
742 addr2 = ip_network('192.0.2.1/32')
Serhiy Storchakabb0dbd52016-03-01 10:25:45 +0200743 list(addr1.address_exclude(addr2)) =
Nick Coghlandc9b2552012-05-20 21:01:57 +1000744 [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
Serhiy Storchakabb0dbd52016-03-01 10:25:45 +0200745 IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
Nick Coghlandc9b2552012-05-20 21:01:57 +1000746
747 or IPv6:
748
749 addr1 = ip_network('2001:db8::1/32')
750 addr2 = ip_network('2001:db8::1/128')
Serhiy Storchakabb0dbd52016-03-01 10:25:45 +0200751 list(addr1.address_exclude(addr2)) =
Nick Coghlandc9b2552012-05-20 21:01:57 +1000752 [ip_network('2001:db8::1/128'),
Serhiy Storchakabb0dbd52016-03-01 10:25:45 +0200753 ip_network('2001:db8::2/127'),
754 ip_network('2001:db8::4/126'),
755 ip_network('2001:db8::8/125'),
756 ...
757 ip_network('2001:db8:8000::/33')]
Nick Coghlandc9b2552012-05-20 21:01:57 +1000758
759 Args:
760 other: An IPv4Network or IPv6Network object of the same type.
761
762 Returns:
Ezio Melotti3f5db392013-01-27 06:20:14 +0200763 An iterator of the IPv(4|6)Network objects which is self
Nick Coghlandc9b2552012-05-20 21:01:57 +1000764 minus other.
765
766 Raises:
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300767 TypeError: If self and other are of differing address
Nick Coghlandc9b2552012-05-20 21:01:57 +1000768 versions, or if other is not a network object.
769 ValueError: If other is not completely contained by self.
770
771 """
772 if not self._version == other._version:
773 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000774 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000775
776 if not isinstance(other, _BaseNetwork):
Nick Coghlan912238e2012-07-07 13:34:50 +1000777 raise TypeError("%s is not a network object" % other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000778
779 if not (other.network_address >= self.network_address and
780 other.broadcast_address <= self.broadcast_address):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200781 raise ValueError('%s not contained in %s' % (other, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000782 if other == self:
Raymond Hettingerbb6c0aa2014-11-22 22:14:41 -0800783 return
Nick Coghlandc9b2552012-05-20 21:01:57 +1000784
Nick Coghlandc9b2552012-05-20 21:01:57 +1000785 # Make sure we're comparing the network of other.
Nick Coghlan912238e2012-07-07 13:34:50 +1000786 other = other.__class__('%s/%s' % (other.network_address,
787 other.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000788
789 s1, s2 = self.subnets()
790 while s1 != other and s2 != other:
791 if (other.network_address >= s1.network_address and
792 other.broadcast_address <= s1.broadcast_address):
793 yield s2
794 s1, s2 = s1.subnets()
795 elif (other.network_address >= s2.network_address and
796 other.broadcast_address <= s2.broadcast_address):
797 yield s1
798 s1, s2 = s2.subnets()
799 else:
800 # If we got here, there's a bug somewhere.
801 raise AssertionError('Error performing exclusion: '
802 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000803 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000804 if s1 == other:
805 yield s2
806 elif s2 == other:
807 yield s1
808 else:
809 # If we got here, there's a bug somewhere.
810 raise AssertionError('Error performing exclusion: '
811 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000812 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000813
814 def compare_networks(self, other):
815 """Compare two IP objects.
816
817 This is only concerned about the comparison of the integer
818 representation of the network addresses. This means that the
819 host bits aren't considered at all in this method. If you want
820 to compare host bits, you can easily enough do a
821 'HostA._ip < HostB._ip'
822
823 Args:
824 other: An IP object.
825
826 Returns:
827 If the IP versions of self and other are the same, returns:
828
829 -1 if self < other:
830 eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
831 IPv6Network('2001:db8::1000/124') <
832 IPv6Network('2001:db8::2000/124')
833 0 if self == other
834 eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
835 IPv6Network('2001:db8::1000/124') ==
836 IPv6Network('2001:db8::1000/124')
837 1 if self > other
838 eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
839 IPv6Network('2001:db8::2000/124') >
840 IPv6Network('2001:db8::1000/124')
841
842 Raises:
843 TypeError if the IP versions are different.
844
845 """
846 # does this need to raise a ValueError?
847 if self._version != other._version:
848 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000849 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000850 # self._version == other._version below here:
851 if self.network_address < other.network_address:
852 return -1
853 if self.network_address > other.network_address:
854 return 1
855 # self.network_address == other.network_address below here:
856 if self.netmask < other.netmask:
857 return -1
858 if self.netmask > other.netmask:
859 return 1
860 return 0
861
862 def _get_networks_key(self):
863 """Network-only key function.
864
865 Returns an object that identifies this address' network and
866 netmask. This function is a suitable "key" argument for sorted()
867 and list.sort().
868
869 """
870 return (self._version, self.network_address, self.netmask)
871
872 def subnets(self, prefixlen_diff=1, new_prefix=None):
873 """The subnets which join to make the current subnet.
874
875 In the case that self contains only one IP
876 (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
877 for IPv6), yield an iterator with just ourself.
878
879 Args:
880 prefixlen_diff: An integer, the amount the prefix length
881 should be increased by. This should not be set if
882 new_prefix is also set.
883 new_prefix: The desired new prefix length. This must be a
884 larger number (smaller prefix) than the existing prefix.
885 This should not be set if prefixlen_diff is also set.
886
887 Returns:
888 An iterator of IPv(4|6) objects.
889
890 Raises:
891 ValueError: The prefixlen_diff is too small or too large.
892 OR
893 prefixlen_diff and new_prefix are both set or new_prefix
894 is a smaller number than the current prefix (smaller
895 number means a larger network)
896
897 """
898 if self._prefixlen == self._max_prefixlen:
899 yield self
900 return
901
902 if new_prefix is not None:
903 if new_prefix < self._prefixlen:
904 raise ValueError('new prefix must be longer')
905 if prefixlen_diff != 1:
906 raise ValueError('cannot set prefixlen_diff and new_prefix')
907 prefixlen_diff = new_prefix - self._prefixlen
908
909 if prefixlen_diff < 0:
910 raise ValueError('prefix length diff must be > 0')
911 new_prefixlen = self._prefixlen + prefixlen_diff
912
Nick Coghlan932346f2014-02-08 23:17:36 +1000913 if new_prefixlen > self._max_prefixlen:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000914 raise ValueError(
915 'prefix length diff %d is invalid for netblock %s' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000916 new_prefixlen, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000917
Antoine Pitrou824db302014-05-15 20:21:48 +0200918 start = int(self.network_address)
Serhiy Storchakabb0dbd52016-03-01 10:25:45 +0200919 end = int(self.broadcast_address) + 1
Antoine Pitrou824db302014-05-15 20:21:48 +0200920 step = (int(self.hostmask) + 1) >> prefixlen_diff
921 for new_addr in range(start, end, step):
922 current = self.__class__((new_addr, new_prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000923 yield current
924
Nick Coghlandc9b2552012-05-20 21:01:57 +1000925 def supernet(self, prefixlen_diff=1, new_prefix=None):
926 """The supernet containing the current network.
927
928 Args:
929 prefixlen_diff: An integer, the amount the prefix length of
930 the network should be decreased by. For example, given a
931 /24 network and a prefixlen_diff of 3, a supernet with a
932 /21 netmask is returned.
933
934 Returns:
935 An IPv4 network object.
936
937 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200938 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
939 a negative prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000940 OR
941 If prefixlen_diff and new_prefix are both set or new_prefix is a
942 larger number than the current prefix (larger number means a
943 smaller network)
944
945 """
946 if self._prefixlen == 0:
947 return self
948
949 if new_prefix is not None:
950 if new_prefix > self._prefixlen:
951 raise ValueError('new prefix must be shorter')
952 if prefixlen_diff != 1:
953 raise ValueError('cannot set prefixlen_diff and new_prefix')
954 prefixlen_diff = self._prefixlen - new_prefix
955
Antoine Pitrou5fb195f2014-05-12 20:36:46 +0200956 new_prefixlen = self.prefixlen - prefixlen_diff
957 if new_prefixlen < 0:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000958 raise ValueError(
959 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
960 (self.prefixlen, prefixlen_diff))
Antoine Pitrou5fb195f2014-05-12 20:36:46 +0200961 return self.__class__((
962 int(self.network_address) & (int(self.netmask) << prefixlen_diff),
963 new_prefixlen
964 ))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000965
Nick Coghlan730f67f2012-08-05 22:02:18 +1000966 @property
967 def is_multicast(self):
968 """Test if the address is reserved for multicast use.
969
970 Returns:
971 A boolean, True if the address is a multicast address.
972 See RFC 2373 2.7 for details.
973
974 """
975 return (self.network_address.is_multicast and
976 self.broadcast_address.is_multicast)
977
978 @property
979 def is_reserved(self):
980 """Test if the address is otherwise IETF reserved.
981
982 Returns:
983 A boolean, True if the address is within one of the
984 reserved IPv6 Network ranges.
985
986 """
987 return (self.network_address.is_reserved and
988 self.broadcast_address.is_reserved)
989
990 @property
991 def is_link_local(self):
992 """Test if the address is reserved for link-local.
993
994 Returns:
995 A boolean, True if the address is reserved per RFC 4291.
996
997 """
998 return (self.network_address.is_link_local and
999 self.broadcast_address.is_link_local)
1000
1001 @property
1002 def is_private(self):
1003 """Test if this address is allocated for private networks.
1004
1005 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001006 A boolean, True if the address is reserved per
1007 iana-ipv4-special-registry or iana-ipv6-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001008
1009 """
1010 return (self.network_address.is_private and
1011 self.broadcast_address.is_private)
1012
1013 @property
Peter Moody22c31762013-10-21 13:58:06 -07001014 def is_global(self):
Peter Moodybe9c1b12013-10-22 12:36:21 -07001015 """Test if this address is allocated for public networks.
Peter Moody22c31762013-10-21 13:58:06 -07001016
1017 Returns:
1018 A boolean, True if the address is not reserved per
1019 iana-ipv4-special-registry or iana-ipv6-special-registry.
1020
1021 """
1022 return not self.is_private
1023
1024 @property
Nick Coghlan730f67f2012-08-05 22:02:18 +10001025 def is_unspecified(self):
1026 """Test if the address is unspecified.
1027
1028 Returns:
1029 A boolean, True if this is the unspecified address as defined in
1030 RFC 2373 2.5.2.
1031
1032 """
1033 return (self.network_address.is_unspecified and
1034 self.broadcast_address.is_unspecified)
1035
1036 @property
1037 def is_loopback(self):
1038 """Test if the address is a loopback address.
1039
1040 Returns:
1041 A boolean, True if the address is a loopback address as defined in
1042 RFC 2373 2.5.3.
1043
1044 """
1045 return (self.network_address.is_loopback and
1046 self.broadcast_address.is_loopback)
1047
Nick Coghlandc9b2552012-05-20 21:01:57 +10001048
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001049class _BaseV4:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001050
1051 """Base IPv4 object.
1052
1053 The following methods are used by IPv4 objects in both single IP
1054 addresses and networks.
1055
1056 """
1057
Serhiy Storchaka88f64f32015-03-07 20:08:34 +02001058 __slots__ = ()
1059 _version = 4
Nick Coghlandc9b2552012-05-20 21:01:57 +10001060 # Equivalent to 255.255.255.255 or 32 bits of 1's.
1061 _ALL_ONES = (2**IPV4LENGTH) - 1
1062 _DECIMAL_DIGITS = frozenset('0123456789')
1063
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001064 # the valid octets for host and netmasks. only useful for IPv4.
Raymond Hettingerdf1b6992014-11-09 15:56:33 -08001065 _valid_mask_octets = frozenset({255, 254, 252, 248, 240, 224, 192, 128, 0})
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001066
Antoine Pitrou45aba182014-05-15 20:18:41 +02001067 _max_prefixlen = IPV4LENGTH
1068 # There are only a handful of valid v4 netmasks, so we cache them all
1069 # when constructed (see _make_netmask()).
1070 _netmask_cache = {}
1071
Nick Coghlandc9b2552012-05-20 21:01:57 +10001072 def _explode_shorthand_ip_string(self):
1073 return str(self)
1074
Antoine Pitrou45aba182014-05-15 20:18:41 +02001075 @classmethod
1076 def _make_netmask(cls, arg):
1077 """Make a (netmask, prefix_len) tuple from the given argument.
1078
1079 Argument can be:
1080 - an integer (the prefix length)
1081 - a string representing the prefix length (e.g. "24")
1082 - a string representing the prefix netmask (e.g. "255.255.255.0")
1083 """
1084 if arg not in cls._netmask_cache:
1085 if isinstance(arg, int):
1086 prefixlen = arg
1087 else:
1088 try:
1089 # Check for a netmask in prefix length form
1090 prefixlen = cls._prefix_from_prefix_string(arg)
1091 except NetmaskValueError:
1092 # Check for a netmask or hostmask in dotted-quad form.
1093 # This may raise NetmaskValueError.
1094 prefixlen = cls._prefix_from_ip_string(arg)
1095 netmask = IPv4Address(cls._ip_int_from_prefix(prefixlen))
1096 cls._netmask_cache[arg] = netmask, prefixlen
1097 return cls._netmask_cache[arg]
1098
1099 @classmethod
1100 def _ip_int_from_string(cls, ip_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001101 """Turn the given IP string into an integer for comparison.
1102
1103 Args:
1104 ip_str: A string, the IP ip_str.
1105
1106 Returns:
1107 The IP ip_str as an integer.
1108
1109 Raises:
1110 AddressValueError: if ip_str isn't a valid IPv4 Address.
1111
1112 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001113 if not ip_str:
1114 raise AddressValueError('Address cannot be empty')
1115
Nick Coghlandc9b2552012-05-20 21:01:57 +10001116 octets = ip_str.split('.')
1117 if len(octets) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001118 raise AddressValueError("Expected 4 octets in %r" % ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001119
Nick Coghlan7319f692012-07-07 21:43:30 +10001120 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001121 return int.from_bytes(map(cls._parse_octet, octets), 'big')
Nick Coghlan7319f692012-07-07 21:43:30 +10001122 except ValueError as exc:
1123 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001124
Antoine Pitrou45aba182014-05-15 20:18:41 +02001125 @classmethod
1126 def _parse_octet(cls, octet_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001127 """Convert a decimal octet into an integer.
1128
1129 Args:
1130 octet_str: A string, the number to parse.
1131
1132 Returns:
1133 The octet as an integer.
1134
1135 Raises:
1136 ValueError: if the octet isn't strictly a decimal from [0..255].
1137
1138 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001139 if not octet_str:
1140 raise ValueError("Empty octet not permitted")
Nick Coghlandc9b2552012-05-20 21:01:57 +10001141 # Whitelist the characters, since int() allows a lot of bizarre stuff.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001142 if not cls._DECIMAL_DIGITS.issuperset(octet_str):
Nick Coghlan07c4e332012-07-08 23:06:45 +10001143 msg = "Only decimal digits permitted in %r"
1144 raise ValueError(msg % octet_str)
1145 # We do the length check second, since the invalid character error
1146 # is likely to be more informative for the user
1147 if len(octet_str) > 3:
1148 msg = "At most 3 characters permitted in %r"
1149 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001150 # Convert to integer (we know digits are legal)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001151 octet_int = int(octet_str, 10)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001152 # Any octets that look like they *might* be written in octal,
1153 # and which don't look exactly the same in both octal and
1154 # decimal are rejected as ambiguous
1155 if octet_int > 7 and octet_str[0] == '0':
Nick Coghlan07c4e332012-07-08 23:06:45 +10001156 msg = "Ambiguous (octal/decimal) value in %r not permitted"
1157 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001158 if octet_int > 255:
Nick Coghlanb582ecc2012-07-07 22:15:22 +10001159 raise ValueError("Octet %d (> 255) not permitted" % octet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001160 return octet_int
1161
Antoine Pitrou45aba182014-05-15 20:18:41 +02001162 @classmethod
1163 def _string_from_ip_int(cls, ip_int):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001164 """Turns a 32-bit integer into dotted decimal notation.
1165
1166 Args:
1167 ip_int: An integer, the IP address.
1168
1169 Returns:
1170 The IP address as a string in dotted decimal notation.
1171
1172 """
Nick Coghlan7319f692012-07-07 21:43:30 +10001173 return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001174
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001175 def _is_valid_netmask(self, netmask):
1176 """Verify that the netmask is valid.
1177
1178 Args:
1179 netmask: A string, either a prefix or dotted decimal
1180 netmask.
1181
1182 Returns:
1183 A boolean, True if the prefix represents a valid IPv4
1184 netmask.
1185
1186 """
1187 mask = netmask.split('.')
1188 if len(mask) == 4:
Nick Coghlan7319f692012-07-07 21:43:30 +10001189 try:
1190 for x in mask:
1191 if int(x) not in self._valid_mask_octets:
1192 return False
1193 except ValueError:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001194 # Found something that isn't an integer or isn't valid
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001195 return False
Nick Coghlan7319f692012-07-07 21:43:30 +10001196 for idx, y in enumerate(mask):
1197 if idx > 0 and y > mask[idx - 1]:
1198 return False
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001199 return True
1200 try:
1201 netmask = int(netmask)
1202 except ValueError:
1203 return False
1204 return 0 <= netmask <= self._max_prefixlen
1205
1206 def _is_hostmask(self, ip_str):
1207 """Test if the IP string is a hostmask (rather than a netmask).
1208
1209 Args:
1210 ip_str: A string, the potential hostmask.
1211
1212 Returns:
1213 A boolean, True if the IP string is a hostmask.
1214
1215 """
1216 bits = ip_str.split('.')
1217 try:
Nick Coghlan7319f692012-07-07 21:43:30 +10001218 parts = [x for x in map(int, bits) if x in self._valid_mask_octets]
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001219 except ValueError:
1220 return False
1221 if len(parts) != len(bits):
1222 return False
1223 if parts[0] < parts[-1]:
1224 return True
1225 return False
1226
Eric V. Smithebdaaf42014-04-14 12:58:07 -04001227 def _reverse_pointer(self):
1228 """Return the reverse DNS pointer name for the IPv4 address.
1229
1230 This implements the method described in RFC1035 3.5.
1231
1232 """
1233 reverse_octets = str(self).split('.')[::-1]
1234 return '.'.join(reverse_octets) + '.in-addr.arpa'
1235
Nick Coghlandc9b2552012-05-20 21:01:57 +10001236 @property
1237 def max_prefixlen(self):
1238 return self._max_prefixlen
1239
1240 @property
1241 def version(self):
1242 return self._version
1243
Nick Coghlandc9b2552012-05-20 21:01:57 +10001244
1245class IPv4Address(_BaseV4, _BaseAddress):
1246
1247 """Represent and manipulate single IPv4 Addresses."""
1248
Serhiy Storchaka88f64f32015-03-07 20:08:34 +02001249 __slots__ = ('_ip', '__weakref__')
1250
Nick Coghlandc9b2552012-05-20 21:01:57 +10001251 def __init__(self, address):
1252
1253 """
1254 Args:
1255 address: A string or integer representing the IP
1256
1257 Additionally, an integer can be passed, so
1258 IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1259 or, more generally
1260 IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1261 IPv4Address('192.0.2.1')
1262
1263 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001264 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001265
1266 """
Nick Coghlandc9b2552012-05-20 21:01:57 +10001267 # Efficient constructor from integer.
1268 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001269 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001270 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001271 return
1272
1273 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001274 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001275 self._check_packed_address(address, 4)
Nick Coghlandb7920b2012-08-20 10:19:12 +10001276 self._ip = int.from_bytes(address, 'big')
Nick Coghlandc9b2552012-05-20 21:01:57 +10001277 return
1278
1279 # Assume input argument to be string or any object representation
1280 # which converts into a formatted IP string.
1281 addr_str = str(address)
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +02001282 if '/' in addr_str:
1283 raise AddressValueError("Unexpected '/' in %r" % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001284 self._ip = self._ip_int_from_string(addr_str)
1285
1286 @property
1287 def packed(self):
1288 """The binary representation of this address."""
1289 return v4_int_to_packed(self._ip)
1290
Nick Coghlan730f67f2012-08-05 22:02:18 +10001291 @property
1292 def is_reserved(self):
1293 """Test if the address is otherwise IETF reserved.
1294
1295 Returns:
1296 A boolean, True if the address is within the
1297 reserved IPv4 Network range.
1298
1299 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001300 return self in self._constants._reserved_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001301
1302 @property
Peter Moodybe9c1b12013-10-22 12:36:21 -07001303 @functools.lru_cache()
Nick Coghlan730f67f2012-08-05 22:02:18 +10001304 def is_private(self):
1305 """Test if this address is allocated for private networks.
1306
1307 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001308 A boolean, True if the address is reserved per
1309 iana-ipv4-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001310
1311 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001312 return any(self in net for net in self._constants._private_networks)
Nick Coghlan730f67f2012-08-05 22:02:18 +10001313
1314 @property
Berker Peksag742192a2016-06-11 22:11:47 +03001315 @functools.lru_cache()
1316 def is_global(self):
1317 return self not in self._constants._public_network and not self.is_private
1318
1319 @property
Nick Coghlan730f67f2012-08-05 22:02:18 +10001320 def is_multicast(self):
1321 """Test if the address is reserved for multicast use.
1322
1323 Returns:
1324 A boolean, True if the address is multicast.
1325 See RFC 3171 for details.
1326
1327 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001328 return self in self._constants._multicast_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001329
1330 @property
1331 def is_unspecified(self):
1332 """Test if the address is unspecified.
1333
1334 Returns:
1335 A boolean, True if this is the unspecified address as defined in
1336 RFC 5735 3.
1337
1338 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001339 return self == self._constants._unspecified_address
Nick Coghlan730f67f2012-08-05 22:02:18 +10001340
1341 @property
1342 def is_loopback(self):
1343 """Test if the address is a loopback address.
1344
1345 Returns:
1346 A boolean, True if the address is a loopback per RFC 3330.
1347
1348 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001349 return self in self._constants._loopback_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001350
1351 @property
1352 def is_link_local(self):
1353 """Test if the address is reserved for link-local.
1354
1355 Returns:
1356 A boolean, True if the address is link-local per RFC 3927.
1357
1358 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001359 return self in self._constants._linklocal_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001360
Nick Coghlandc9b2552012-05-20 21:01:57 +10001361
1362class IPv4Interface(IPv4Address):
1363
Nick Coghlandc9b2552012-05-20 21:01:57 +10001364 def __init__(self, address):
1365 if isinstance(address, (bytes, int)):
1366 IPv4Address.__init__(self, address)
1367 self.network = IPv4Network(self._ip)
1368 self._prefixlen = self._max_prefixlen
1369 return
1370
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001371 if isinstance(address, tuple):
1372 IPv4Address.__init__(self, address[0])
1373 if len(address) > 1:
1374 self._prefixlen = int(address[1])
1375 else:
1376 self._prefixlen = self._max_prefixlen
1377
1378 self.network = IPv4Network(address, strict=False)
1379 self.netmask = self.network.netmask
1380 self.hostmask = self.network.hostmask
1381 return
1382
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001383 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001384 IPv4Address.__init__(self, addr[0])
1385
1386 self.network = IPv4Network(address, strict=False)
1387 self._prefixlen = self.network._prefixlen
1388
1389 self.netmask = self.network.netmask
1390 self.hostmask = self.network.hostmask
1391
Nick Coghlandc9b2552012-05-20 21:01:57 +10001392 def __str__(self):
1393 return '%s/%d' % (self._string_from_ip_int(self._ip),
1394 self.network.prefixlen)
1395
1396 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001397 address_equal = IPv4Address.__eq__(self, other)
1398 if not address_equal or address_equal is NotImplemented:
1399 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001400 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001401 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001402 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001403 # An interface with an associated network is NOT the
1404 # same as an unassociated address. That's why the hash
1405 # takes the extra info into account.
1406 return False
1407
1408 def __lt__(self, other):
1409 address_less = IPv4Address.__lt__(self, other)
1410 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001411 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001412 try:
s-sanjay7bd8d3e2017-03-31 23:09:53 -07001413 return (self.network < other.network or
1414 self.network == other.network and address_less)
Nick Coghlan3008ec02012-07-08 00:45:33 +10001415 except AttributeError:
1416 # We *do* allow addresses and interfaces to be sorted. The
1417 # unassociated address is considered less than all interfaces.
1418 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001419
1420 def __hash__(self):
1421 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1422
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +02001423 __reduce__ = _IPAddressBase.__reduce__
1424
Nick Coghlandc9b2552012-05-20 21:01:57 +10001425 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001426 def ip(self):
1427 return IPv4Address(self._ip)
1428
1429 @property
1430 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10001431 return '%s/%s' % (self._string_from_ip_int(self._ip),
1432 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001433
1434 @property
1435 def with_netmask(self):
1436 return '%s/%s' % (self._string_from_ip_int(self._ip),
1437 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001438
Nick Coghlandc9b2552012-05-20 21:01:57 +10001439 @property
1440 def with_hostmask(self):
1441 return '%s/%s' % (self._string_from_ip_int(self._ip),
1442 self.hostmask)
1443
1444
1445class IPv4Network(_BaseV4, _BaseNetwork):
1446
1447 """This class represents and manipulates 32-bit IPv4 network + addresses..
1448
1449 Attributes: [examples for IPv4Network('192.0.2.0/27')]
1450 .network_address: IPv4Address('192.0.2.0')
1451 .hostmask: IPv4Address('0.0.0.31')
1452 .broadcast_address: IPv4Address('192.0.2.32')
1453 .netmask: IPv4Address('255.255.255.224')
1454 .prefixlen: 27
1455
1456 """
Nick Coghlan51c30672012-05-27 00:25:58 +10001457 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001458 _address_class = IPv4Address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001459
Nick Coghlandc9b2552012-05-20 21:01:57 +10001460 def __init__(self, address, strict=True):
1461
1462 """Instantiate a new IPv4 network object.
1463
1464 Args:
1465 address: A string or integer representing the IP [& network].
1466 '192.0.2.0/24'
1467 '192.0.2.0/255.255.255.0'
1468 '192.0.0.2/0.0.0.255'
1469 are all functionally the same in IPv4. Similarly,
1470 '192.0.2.1'
1471 '192.0.2.1/255.255.255.255'
1472 '192.0.2.1/32'
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001473 are also functionally equivalent. That is to say, failing to
Nick Coghlandc9b2552012-05-20 21:01:57 +10001474 provide a subnetmask will create an object with a mask of /32.
1475
1476 If the mask (portion after the / in the argument) is given in
1477 dotted quad form, it is treated as a netmask if it starts with a
1478 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1479 starts with a zero field (e.g. 0.255.255.255 == /8), with the
1480 single exception of an all-zero mask which is treated as a
1481 netmask == /0. If no mask is given, a default of /32 is used.
1482
1483 Additionally, an integer can be passed, so
1484 IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1485 or, more generally
1486 IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1487 IPv4Interface('192.0.2.1')
1488
1489 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001490 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001491 NetmaskValueError: If the netmask isn't valid for
1492 an IPv4 address.
Sandro Tosib4386d32012-06-02 17:14:22 +02001493 ValueError: If strict is True and a network address is not
Nick Coghlandc9b2552012-05-20 21:01:57 +10001494 supplied.
1495
1496 """
Nick Coghlandc9b2552012-05-20 21:01:57 +10001497 _BaseNetwork.__init__(self, address)
1498
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001499 # Constructing from a packed address or integer
1500 if isinstance(address, (int, bytes)):
Nick Coghlan297b1432012-07-08 17:11:04 +10001501 self.network_address = IPv4Address(address)
Antoine Pitrou45aba182014-05-15 20:18:41 +02001502 self.netmask, self._prefixlen = self._make_netmask(self._max_prefixlen)
1503 #fixme: address/network test here.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001504 return
1505
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001506 if isinstance(address, tuple):
1507 if len(address) > 1:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001508 arg = address[1]
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001509 else:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001510 # We weren't given an address[1]
1511 arg = self._max_prefixlen
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001512 self.network_address = IPv4Address(address[0])
Antoine Pitrou45aba182014-05-15 20:18:41 +02001513 self.netmask, self._prefixlen = self._make_netmask(arg)
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001514 packed = int(self.network_address)
1515 if packed & int(self.netmask) != packed:
1516 if strict:
1517 raise ValueError('%s has host bits set' % self)
1518 else:
1519 self.network_address = IPv4Address(packed &
1520 int(self.netmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001521 return
1522
1523 # Assume input argument to be string or any object representation
1524 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001525 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001526 self.network_address = IPv4Address(self._ip_int_from_string(addr[0]))
1527
Nick Coghlandc9b2552012-05-20 21:01:57 +10001528 if len(addr) == 2:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001529 arg = addr[1]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001530 else:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001531 arg = self._max_prefixlen
1532 self.netmask, self._prefixlen = self._make_netmask(arg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001533
1534 if strict:
1535 if (IPv4Address(int(self.network_address) & int(self.netmask)) !=
1536 self.network_address):
1537 raise ValueError('%s has host bits set' % self)
1538 self.network_address = IPv4Address(int(self.network_address) &
1539 int(self.netmask))
1540
1541 if self._prefixlen == (self._max_prefixlen - 1):
1542 self.hosts = self.__iter__
1543
Peter Moodye5019d52013-10-24 09:47:10 -07001544 @property
1545 @functools.lru_cache()
1546 def is_global(self):
1547 """Test if this address is allocated for public networks.
1548
1549 Returns:
1550 A boolean, True if the address is not reserved per
1551 iana-ipv4-special-registry.
1552
1553 """
1554 return (not (self.network_address in IPv4Network('100.64.0.0/10') and
1555 self.broadcast_address in IPv4Network('100.64.0.0/10')) and
1556 not self.is_private)
1557
1558
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001559class _IPv4Constants:
1560 _linklocal_network = IPv4Network('169.254.0.0/16')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001561
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001562 _loopback_network = IPv4Network('127.0.0.0/8')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001563
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001564 _multicast_network = IPv4Network('224.0.0.0/4')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001565
Berker Peksag742192a2016-06-11 22:11:47 +03001566 _public_network = IPv4Network('100.64.0.0/10')
1567
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001568 _private_networks = [
1569 IPv4Network('0.0.0.0/8'),
1570 IPv4Network('10.0.0.0/8'),
1571 IPv4Network('127.0.0.0/8'),
1572 IPv4Network('169.254.0.0/16'),
1573 IPv4Network('172.16.0.0/12'),
1574 IPv4Network('192.0.0.0/29'),
1575 IPv4Network('192.0.0.170/31'),
1576 IPv4Network('192.0.2.0/24'),
1577 IPv4Network('192.168.0.0/16'),
1578 IPv4Network('198.18.0.0/15'),
1579 IPv4Network('198.51.100.0/24'),
1580 IPv4Network('203.0.113.0/24'),
1581 IPv4Network('240.0.0.0/4'),
1582 IPv4Network('255.255.255.255/32'),
1583 ]
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001584
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001585 _reserved_network = IPv4Network('240.0.0.0/4')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001586
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001587 _unspecified_address = IPv4Address('0.0.0.0')
1588
1589
1590IPv4Address._constants = _IPv4Constants
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001591
Nick Coghlandc9b2552012-05-20 21:01:57 +10001592
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001593class _BaseV6:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001594
1595 """Base IPv6 object.
1596
1597 The following methods are used by IPv6 objects in both single IP
1598 addresses and networks.
1599
1600 """
1601
Serhiy Storchaka88f64f32015-03-07 20:08:34 +02001602 __slots__ = ()
1603 _version = 6
Nick Coghlandc9b2552012-05-20 21:01:57 +10001604 _ALL_ONES = (2**IPV6LENGTH) - 1
1605 _HEXTET_COUNT = 8
1606 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
Antoine Pitrou45aba182014-05-15 20:18:41 +02001607 _max_prefixlen = IPV6LENGTH
1608
1609 # There are only a bunch of valid v6 netmasks, so we cache them all
1610 # when constructed (see _make_netmask()).
1611 _netmask_cache = {}
Nick Coghlandc9b2552012-05-20 21:01:57 +10001612
Antoine Pitrou45aba182014-05-15 20:18:41 +02001613 @classmethod
1614 def _make_netmask(cls, arg):
1615 """Make a (netmask, prefix_len) tuple from the given argument.
1616
1617 Argument can be:
1618 - an integer (the prefix length)
1619 - a string representing the prefix length (e.g. "24")
1620 - a string representing the prefix netmask (e.g. "255.255.255.0")
1621 """
1622 if arg not in cls._netmask_cache:
1623 if isinstance(arg, int):
1624 prefixlen = arg
1625 else:
1626 prefixlen = cls._prefix_from_prefix_string(arg)
1627 netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen))
1628 cls._netmask_cache[arg] = netmask, prefixlen
1629 return cls._netmask_cache[arg]
1630
1631 @classmethod
1632 def _ip_int_from_string(cls, ip_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001633 """Turn an IPv6 ip_str into an integer.
1634
1635 Args:
1636 ip_str: A string, the IPv6 ip_str.
1637
1638 Returns:
1639 An int, the IPv6 address
1640
1641 Raises:
1642 AddressValueError: if ip_str isn't a valid IPv6 Address.
1643
1644 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001645 if not ip_str:
1646 raise AddressValueError('Address cannot be empty')
1647
Nick Coghlandc9b2552012-05-20 21:01:57 +10001648 parts = ip_str.split(':')
1649
1650 # An IPv6 address needs at least 2 colons (3 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001651 _min_parts = 3
1652 if len(parts) < _min_parts:
1653 msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
1654 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001655
1656 # If the address has an IPv4-style suffix, convert it to hexadecimal.
1657 if '.' in parts[-1]:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001658 try:
1659 ipv4_int = IPv4Address(parts.pop())._ip
1660 except AddressValueError as exc:
1661 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001662 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1663 parts.append('%x' % (ipv4_int & 0xFFFF))
1664
1665 # An IPv6 address can't have more than 8 colons (9 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001666 # The extra colon comes from using the "::" notation for a single
1667 # leading or trailing zero part.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001668 _max_parts = cls._HEXTET_COUNT + 1
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001669 if len(parts) > _max_parts:
1670 msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
1671 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001672
1673 # Disregarding the endpoints, find '::' with nothing in between.
1674 # This indicates that a run of zeroes has been skipped.
Nick Coghlan7319f692012-07-07 21:43:30 +10001675 skip_index = None
1676 for i in range(1, len(parts) - 1):
1677 if not parts[i]:
1678 if skip_index is not None:
1679 # Can't have more than one '::'
1680 msg = "At most one '::' permitted in %r" % ip_str
1681 raise AddressValueError(msg)
1682 skip_index = i
Nick Coghlandc9b2552012-05-20 21:01:57 +10001683
1684 # parts_hi is the number of parts to copy from above/before the '::'
1685 # parts_lo is the number of parts to copy from below/after the '::'
1686 if skip_index is not None:
1687 # If we found a '::', then check if it also covers the endpoints.
1688 parts_hi = skip_index
1689 parts_lo = len(parts) - skip_index - 1
1690 if not parts[0]:
1691 parts_hi -= 1
1692 if parts_hi:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001693 msg = "Leading ':' only permitted as part of '::' in %r"
1694 raise AddressValueError(msg % ip_str) # ^: requires ^::
Nick Coghlandc9b2552012-05-20 21:01:57 +10001695 if not parts[-1]:
1696 parts_lo -= 1
1697 if parts_lo:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001698 msg = "Trailing ':' only permitted as part of '::' in %r"
1699 raise AddressValueError(msg % ip_str) # :$ requires ::$
Antoine Pitrou45aba182014-05-15 20:18:41 +02001700 parts_skipped = cls._HEXTET_COUNT - (parts_hi + parts_lo)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001701 if parts_skipped < 1:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001702 msg = "Expected at most %d other parts with '::' in %r"
Antoine Pitrou45aba182014-05-15 20:18:41 +02001703 raise AddressValueError(msg % (cls._HEXTET_COUNT-1, ip_str))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001704 else:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001705 # Otherwise, allocate the entire address to parts_hi. The
1706 # endpoints could still be empty, but _parse_hextet() will check
1707 # for that.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001708 if len(parts) != cls._HEXTET_COUNT:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001709 msg = "Exactly %d parts expected without '::' in %r"
Antoine Pitrou45aba182014-05-15 20:18:41 +02001710 raise AddressValueError(msg % (cls._HEXTET_COUNT, ip_str))
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001711 if not parts[0]:
1712 msg = "Leading ':' only permitted as part of '::' in %r"
1713 raise AddressValueError(msg % ip_str) # ^: requires ^::
1714 if not parts[-1]:
1715 msg = "Trailing ':' only permitted as part of '::' in %r"
1716 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001717 parts_hi = len(parts)
1718 parts_lo = 0
1719 parts_skipped = 0
1720
1721 try:
1722 # Now, parse the hextets into a 128-bit integer.
1723 ip_int = 0
1724 for i in range(parts_hi):
1725 ip_int <<= 16
Antoine Pitrou45aba182014-05-15 20:18:41 +02001726 ip_int |= cls._parse_hextet(parts[i])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001727 ip_int <<= 16 * parts_skipped
1728 for i in range(-parts_lo, 0):
1729 ip_int <<= 16
Antoine Pitrou45aba182014-05-15 20:18:41 +02001730 ip_int |= cls._parse_hextet(parts[i])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001731 return ip_int
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001732 except ValueError as exc:
1733 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001734
Antoine Pitrou45aba182014-05-15 20:18:41 +02001735 @classmethod
1736 def _parse_hextet(cls, hextet_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001737 """Convert an IPv6 hextet string into an integer.
1738
1739 Args:
1740 hextet_str: A string, the number to parse.
1741
1742 Returns:
1743 The hextet as an integer.
1744
1745 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001746 ValueError: if the input isn't strictly a hex number from
1747 [0..FFFF].
Nick Coghlandc9b2552012-05-20 21:01:57 +10001748
1749 """
1750 # Whitelist the characters, since int() allows a lot of bizarre stuff.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001751 if not cls._HEX_DIGITS.issuperset(hextet_str):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001752 raise ValueError("Only hex digits permitted in %r" % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001753 # We do the length check second, since the invalid character error
1754 # is likely to be more informative for the user
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001755 if len(hextet_str) > 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001756 msg = "At most 4 characters permitted in %r"
1757 raise ValueError(msg % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001758 # Length check means we can skip checking the integer value
1759 return int(hextet_str, 16)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001760
Antoine Pitrou45aba182014-05-15 20:18:41 +02001761 @classmethod
1762 def _compress_hextets(cls, hextets):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001763 """Compresses a list of hextets.
1764
1765 Compresses a list of strings, replacing the longest continuous
1766 sequence of "0" in the list with "" and adding empty strings at
1767 the beginning or at the end of the string such that subsequently
1768 calling ":".join(hextets) will produce the compressed version of
1769 the IPv6 address.
1770
1771 Args:
1772 hextets: A list of strings, the hextets to compress.
1773
1774 Returns:
1775 A list of strings.
1776
1777 """
1778 best_doublecolon_start = -1
1779 best_doublecolon_len = 0
1780 doublecolon_start = -1
1781 doublecolon_len = 0
Nick Coghlandb7920b2012-08-20 10:19:12 +10001782 for index, hextet in enumerate(hextets):
1783 if hextet == '0':
Nick Coghlandc9b2552012-05-20 21:01:57 +10001784 doublecolon_len += 1
1785 if doublecolon_start == -1:
1786 # Start of a sequence of zeros.
1787 doublecolon_start = index
1788 if doublecolon_len > best_doublecolon_len:
1789 # This is the longest sequence of zeros so far.
1790 best_doublecolon_len = doublecolon_len
1791 best_doublecolon_start = doublecolon_start
1792 else:
1793 doublecolon_len = 0
1794 doublecolon_start = -1
1795
1796 if best_doublecolon_len > 1:
1797 best_doublecolon_end = (best_doublecolon_start +
1798 best_doublecolon_len)
1799 # For zeros at the end of the address.
1800 if best_doublecolon_end == len(hextets):
1801 hextets += ['']
1802 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1803 # For zeros at the beginning of the address.
1804 if best_doublecolon_start == 0:
1805 hextets = [''] + hextets
1806
1807 return hextets
1808
Antoine Pitrou45aba182014-05-15 20:18:41 +02001809 @classmethod
1810 def _string_from_ip_int(cls, ip_int=None):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001811 """Turns a 128-bit integer into hexadecimal notation.
1812
1813 Args:
1814 ip_int: An integer, the IP address.
1815
1816 Returns:
1817 A string, the hexadecimal representation of the address.
1818
1819 Raises:
1820 ValueError: The address is bigger than 128 bits of all ones.
1821
1822 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001823 if ip_int is None:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001824 ip_int = int(cls._ip)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001825
Antoine Pitrou45aba182014-05-15 20:18:41 +02001826 if ip_int > cls._ALL_ONES:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001827 raise ValueError('IPv6 address is too large')
1828
1829 hex_str = '%032x' % ip_int
Nick Coghlan7319f692012-07-07 21:43:30 +10001830 hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001831
Antoine Pitrou45aba182014-05-15 20:18:41 +02001832 hextets = cls._compress_hextets(hextets)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001833 return ':'.join(hextets)
1834
1835 def _explode_shorthand_ip_string(self):
1836 """Expand a shortened IPv6 address.
1837
1838 Args:
1839 ip_str: A string, the IPv6 address.
1840
1841 Returns:
1842 A string, the expanded IPv6 address.
1843
1844 """
1845 if isinstance(self, IPv6Network):
1846 ip_str = str(self.network_address)
1847 elif isinstance(self, IPv6Interface):
1848 ip_str = str(self.ip)
1849 else:
1850 ip_str = str(self)
1851
1852 ip_int = self._ip_int_from_string(ip_str)
Nick Coghlan7319f692012-07-07 21:43:30 +10001853 hex_str = '%032x' % ip_int
1854 parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001855 if isinstance(self, (_BaseNetwork, IPv6Interface)):
Nick Coghlane3ded952012-08-05 22:45:22 +10001856 return '%s/%d' % (':'.join(parts), self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001857 return ':'.join(parts)
1858
Eric V. Smithebdaaf42014-04-14 12:58:07 -04001859 def _reverse_pointer(self):
1860 """Return the reverse DNS pointer name for the IPv6 address.
1861
1862 This implements the method described in RFC3596 2.5.
1863
1864 """
1865 reverse_chars = self.exploded[::-1].replace(':', '')
1866 return '.'.join(reverse_chars) + '.ip6.arpa'
1867
Nick Coghlandc9b2552012-05-20 21:01:57 +10001868 @property
1869 def max_prefixlen(self):
1870 return self._max_prefixlen
1871
1872 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001873 def version(self):
1874 return self._version
1875
Nick Coghlandc9b2552012-05-20 21:01:57 +10001876
1877class IPv6Address(_BaseV6, _BaseAddress):
1878
Sandro Tosib95c6342012-05-23 23:17:22 +02001879 """Represent and manipulate single IPv6 Addresses."""
Nick Coghlandc9b2552012-05-20 21:01:57 +10001880
Serhiy Storchaka88f64f32015-03-07 20:08:34 +02001881 __slots__ = ('_ip', '__weakref__')
1882
Nick Coghlandc9b2552012-05-20 21:01:57 +10001883 def __init__(self, address):
1884 """Instantiate a new IPv6 address object.
1885
1886 Args:
1887 address: A string or integer representing the IP
1888
1889 Additionally, an integer can be passed, so
1890 IPv6Address('2001:db8::') ==
1891 IPv6Address(42540766411282592856903984951653826560)
1892 or, more generally
1893 IPv6Address(int(IPv6Address('2001:db8::'))) ==
1894 IPv6Address('2001:db8::')
1895
1896 Raises:
1897 AddressValueError: If address isn't a valid IPv6 address.
1898
1899 """
Nick Coghlandc9b2552012-05-20 21:01:57 +10001900 # Efficient constructor from integer.
1901 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001902 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001903 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001904 return
1905
1906 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001907 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001908 self._check_packed_address(address, 16)
Nick Coghlandb7920b2012-08-20 10:19:12 +10001909 self._ip = int.from_bytes(address, 'big')
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)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001917 self._ip = self._ip_int_from_string(addr_str)
1918
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001919 @property
1920 def packed(self):
1921 """The binary representation of this address."""
1922 return v6_int_to_packed(self._ip)
1923
Nick Coghlan730f67f2012-08-05 22:02:18 +10001924 @property
1925 def is_multicast(self):
1926 """Test if the address is reserved for multicast use.
1927
1928 Returns:
1929 A boolean, True if the address is a multicast address.
1930 See RFC 2373 2.7 for details.
1931
1932 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001933 return self in self._constants._multicast_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001934
1935 @property
1936 def is_reserved(self):
1937 """Test if the address is otherwise IETF reserved.
1938
1939 Returns:
1940 A boolean, True if the address is within one of the
1941 reserved IPv6 Network ranges.
1942
1943 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001944 return any(self in x for x in self._constants._reserved_networks)
Nick Coghlan730f67f2012-08-05 22:02:18 +10001945
1946 @property
1947 def is_link_local(self):
1948 """Test if the address is reserved for link-local.
1949
1950 Returns:
1951 A boolean, True if the address is reserved per RFC 4291.
1952
1953 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001954 return self in self._constants._linklocal_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001955
1956 @property
1957 def is_site_local(self):
1958 """Test if the address is reserved for site-local.
1959
1960 Note that the site-local address space has been deprecated by RFC 3879.
1961 Use is_private to test if this address is in the space of unique local
1962 addresses as defined by RFC 4193.
1963
1964 Returns:
1965 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1966
1967 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001968 return self in self._constants._sitelocal_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001969
1970 @property
Peter Moodybe9c1b12013-10-22 12:36:21 -07001971 @functools.lru_cache()
Nick Coghlan730f67f2012-08-05 22:02:18 +10001972 def is_private(self):
1973 """Test if this address is allocated for private networks.
1974
1975 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001976 A boolean, True if the address is reserved per
1977 iana-ipv6-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001978
1979 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001980 return any(self in net for net in self._constants._private_networks)
Peter Moody22c31762013-10-21 13:58:06 -07001981
1982 @property
1983 def is_global(self):
1984 """Test if this address is allocated for public networks.
1985
1986 Returns:
1987 A boolean, true if the address is not reserved per
1988 iana-ipv6-special-registry.
1989
1990 """
1991 return not self.is_private
Nick Coghlan730f67f2012-08-05 22:02:18 +10001992
1993 @property
1994 def is_unspecified(self):
1995 """Test if the address is unspecified.
1996
1997 Returns:
1998 A boolean, True if this is the unspecified address as defined in
1999 RFC 2373 2.5.2.
2000
2001 """
2002 return self._ip == 0
2003
2004 @property
2005 def is_loopback(self):
2006 """Test if the address is a loopback address.
2007
2008 Returns:
2009 A boolean, True if the address is a loopback address as defined in
2010 RFC 2373 2.5.3.
2011
2012 """
2013 return self._ip == 1
2014
2015 @property
2016 def ipv4_mapped(self):
2017 """Return the IPv4 mapped address.
2018
2019 Returns:
2020 If the IPv6 address is a v4 mapped address, return the
2021 IPv4 mapped address. Return None otherwise.
2022
2023 """
2024 if (self._ip >> 32) != 0xFFFF:
2025 return None
2026 return IPv4Address(self._ip & 0xFFFFFFFF)
2027
2028 @property
2029 def teredo(self):
2030 """Tuple of embedded teredo IPs.
2031
2032 Returns:
2033 Tuple of the (server, client) IPs or None if the address
2034 doesn't appear to be a teredo address (doesn't start with
2035 2001::/32)
2036
2037 """
2038 if (self._ip >> 96) != 0x20010000:
2039 return None
2040 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
2041 IPv4Address(~self._ip & 0xFFFFFFFF))
2042
2043 @property
2044 def sixtofour(self):
2045 """Return the IPv4 6to4 embedded address.
2046
2047 Returns:
2048 The IPv4 6to4-embedded address if present or None if the
2049 address doesn't appear to contain a 6to4 embedded address.
2050
2051 """
2052 if (self._ip >> 112) != 0x2002:
2053 return None
2054 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
2055
Nick Coghlandc9b2552012-05-20 21:01:57 +10002056
2057class IPv6Interface(IPv6Address):
2058
2059 def __init__(self, address):
2060 if isinstance(address, (bytes, int)):
2061 IPv6Address.__init__(self, address)
2062 self.network = IPv6Network(self._ip)
2063 self._prefixlen = self._max_prefixlen
2064 return
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002065 if isinstance(address, tuple):
2066 IPv6Address.__init__(self, address[0])
2067 if len(address) > 1:
2068 self._prefixlen = int(address[1])
2069 else:
2070 self._prefixlen = self._max_prefixlen
2071 self.network = IPv6Network(address, strict=False)
2072 self.netmask = self.network.netmask
2073 self.hostmask = self.network.hostmask
2074 return
Nick Coghlandc9b2552012-05-20 21:01:57 +10002075
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002076 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002077 IPv6Address.__init__(self, addr[0])
2078 self.network = IPv6Network(address, strict=False)
2079 self.netmask = self.network.netmask
2080 self._prefixlen = self.network._prefixlen
2081 self.hostmask = self.network.hostmask
2082
Nick Coghlandc9b2552012-05-20 21:01:57 +10002083 def __str__(self):
2084 return '%s/%d' % (self._string_from_ip_int(self._ip),
2085 self.network.prefixlen)
2086
2087 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10002088 address_equal = IPv6Address.__eq__(self, other)
2089 if not address_equal or address_equal is NotImplemented:
2090 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10002091 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10002092 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10002093 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10002094 # An interface with an associated network is NOT the
2095 # same as an unassociated address. That's why the hash
2096 # takes the extra info into account.
2097 return False
2098
2099 def __lt__(self, other):
2100 address_less = IPv6Address.__lt__(self, other)
2101 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10002102 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10002103 try:
s-sanjay7bd8d3e2017-03-31 23:09:53 -07002104 return (self.network < other.network or
2105 self.network == other.network and address_less)
Nick Coghlan3008ec02012-07-08 00:45:33 +10002106 except AttributeError:
2107 # We *do* allow addresses and interfaces to be sorted. The
2108 # unassociated address is considered less than all interfaces.
2109 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10002110
2111 def __hash__(self):
2112 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
2113
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +02002114 __reduce__ = _IPAddressBase.__reduce__
2115
Nick Coghlandc9b2552012-05-20 21:01:57 +10002116 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10002117 def ip(self):
2118 return IPv6Address(self._ip)
2119
2120 @property
2121 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10002122 return '%s/%s' % (self._string_from_ip_int(self._ip),
2123 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002124
2125 @property
2126 def with_netmask(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10002127 return '%s/%s' % (self._string_from_ip_int(self._ip),
2128 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02002129
Nick Coghlandc9b2552012-05-20 21:01:57 +10002130 @property
2131 def with_hostmask(self):
2132 return '%s/%s' % (self._string_from_ip_int(self._ip),
2133 self.hostmask)
2134
Nick Coghlan730f67f2012-08-05 22:02:18 +10002135 @property
2136 def is_unspecified(self):
2137 return self._ip == 0 and self.network.is_unspecified
2138
2139 @property
2140 def is_loopback(self):
2141 return self._ip == 1 and self.network.is_loopback
2142
Nick Coghlandc9b2552012-05-20 21:01:57 +10002143
2144class IPv6Network(_BaseV6, _BaseNetwork):
2145
2146 """This class represents and manipulates 128-bit IPv6 networks.
2147
2148 Attributes: [examples for IPv6('2001:db8::1000/124')]
2149 .network_address: IPv6Address('2001:db8::1000')
2150 .hostmask: IPv6Address('::f')
2151 .broadcast_address: IPv6Address('2001:db8::100f')
2152 .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
2153 .prefixlen: 124
2154
2155 """
2156
Nick Coghlan51c30672012-05-27 00:25:58 +10002157 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10002158 _address_class = IPv6Address
2159
Nick Coghlandc9b2552012-05-20 21:01:57 +10002160 def __init__(self, address, strict=True):
2161 """Instantiate a new IPv6 Network object.
2162
2163 Args:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02002164 address: A string or integer representing the IPv6 network or the
2165 IP and prefix/netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +10002166 '2001:db8::/128'
2167 '2001:db8:0000:0000:0000:0000:0000:0000/128'
2168 '2001:db8::'
2169 are all functionally the same in IPv6. That is to say,
2170 failing to provide a subnetmask will create an object with
2171 a mask of /128.
2172
2173 Additionally, an integer can be passed, so
2174 IPv6Network('2001:db8::') ==
2175 IPv6Network(42540766411282592856903984951653826560)
2176 or, more generally
2177 IPv6Network(int(IPv6Network('2001:db8::'))) ==
2178 IPv6Network('2001:db8::')
2179
2180 strict: A boolean. If true, ensure that we have been passed
2181 A true network address, eg, 2001:db8::1000/124 and not an
2182 IP address on a network, eg, 2001:db8::1/124.
2183
2184 Raises:
2185 AddressValueError: If address isn't a valid IPv6 address.
2186 NetmaskValueError: If the netmask isn't valid for
2187 an IPv6 address.
2188 ValueError: If strict was True and a network address was not
2189 supplied.
2190
2191 """
Nick Coghlandc9b2552012-05-20 21:01:57 +10002192 _BaseNetwork.__init__(self, address)
2193
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002194 # Efficient constructor from integer or packed address
2195 if isinstance(address, (bytes, int)):
Nick Coghlandc9b2552012-05-20 21:01:57 +10002196 self.network_address = IPv6Address(address)
Antoine Pitrou45aba182014-05-15 20:18:41 +02002197 self.netmask, self._prefixlen = self._make_netmask(self._max_prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002198 return
2199
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002200 if isinstance(address, tuple):
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002201 if len(address) > 1:
Antoine Pitrou45aba182014-05-15 20:18:41 +02002202 arg = address[1]
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002203 else:
Antoine Pitrou45aba182014-05-15 20:18:41 +02002204 arg = self._max_prefixlen
2205 self.netmask, self._prefixlen = self._make_netmask(arg)
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002206 self.network_address = IPv6Address(address[0])
2207 packed = int(self.network_address)
2208 if packed & int(self.netmask) != packed:
2209 if strict:
2210 raise ValueError('%s has host bits set' % self)
2211 else:
2212 self.network_address = IPv6Address(packed &
2213 int(self.netmask))
Hynek Schlawacked36b2e2012-06-08 15:21:21 +02002214 return
Nick Coghlandc9b2552012-05-20 21:01:57 +10002215
2216 # Assume input argument to be string or any object representation
2217 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002218 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002219
2220 self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))
2221
2222 if len(addr) == 2:
Antoine Pitrou45aba182014-05-15 20:18:41 +02002223 arg = addr[1]
Nick Coghlandc9b2552012-05-20 21:01:57 +10002224 else:
Antoine Pitrou45aba182014-05-15 20:18:41 +02002225 arg = self._max_prefixlen
2226 self.netmask, self._prefixlen = self._make_netmask(arg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002227
Nick Coghlandc9b2552012-05-20 21:01:57 +10002228 if strict:
2229 if (IPv6Address(int(self.network_address) & int(self.netmask)) !=
2230 self.network_address):
Nick Coghlan912238e2012-07-07 13:34:50 +10002231 raise ValueError('%s has host bits set' % self)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002232 self.network_address = IPv6Address(int(self.network_address) &
2233 int(self.netmask))
2234
2235 if self._prefixlen == (self._max_prefixlen - 1):
2236 self.hosts = self.__iter__
2237
Peter Moody1243c7d2014-03-11 09:55:46 -07002238 def hosts(self):
2239 """Generate Iterator over usable hosts in a network.
2240
2241 This is like __iter__ except it doesn't return the
2242 Subnet-Router anycast address.
2243
2244 """
2245 network = int(self.network_address)
2246 broadcast = int(self.broadcast_address)
2247 for x in range(network + 1, broadcast + 1):
2248 yield self._address_class(x)
2249
Nick Coghlan730f67f2012-08-05 22:02:18 +10002250 @property
2251 def is_site_local(self):
2252 """Test if the address is reserved for site-local.
2253
2254 Note that the site-local address space has been deprecated by RFC 3879.
2255 Use is_private to test if this address is in the space of unique local
2256 addresses as defined by RFC 4193.
2257
2258 Returns:
2259 A boolean, True if the address is reserved per RFC 3513 2.5.6.
2260
2261 """
2262 return (self.network_address.is_site_local and
2263 self.broadcast_address.is_site_local)
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002264
2265
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002266class _IPv6Constants:
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002267
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002268 _linklocal_network = IPv6Network('fe80::/10')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002269
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002270 _multicast_network = IPv6Network('ff00::/8')
2271
2272 _private_networks = [
2273 IPv6Network('::1/128'),
2274 IPv6Network('::/128'),
2275 IPv6Network('::ffff:0:0/96'),
2276 IPv6Network('100::/64'),
2277 IPv6Network('2001::/23'),
2278 IPv6Network('2001:2::/48'),
2279 IPv6Network('2001:db8::/32'),
2280 IPv6Network('2001:10::/28'),
2281 IPv6Network('fc00::/7'),
2282 IPv6Network('fe80::/10'),
2283 ]
2284
2285 _reserved_networks = [
2286 IPv6Network('::/8'), IPv6Network('100::/8'),
2287 IPv6Network('200::/7'), IPv6Network('400::/6'),
2288 IPv6Network('800::/5'), IPv6Network('1000::/4'),
2289 IPv6Network('4000::/3'), IPv6Network('6000::/3'),
2290 IPv6Network('8000::/3'), IPv6Network('A000::/3'),
2291 IPv6Network('C000::/3'), IPv6Network('E000::/4'),
2292 IPv6Network('F000::/5'), IPv6Network('F800::/6'),
2293 IPv6Network('FE00::/9'),
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002294 ]
2295
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002296 _sitelocal_network = IPv6Network('fec0::/10')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002297
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002298
2299IPv6Address._constants = _IPv6Constants