blob: ac03c36ce08e2d4e78053fdc1e803fdce5ea6d9b [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')
Sandro Tosi876ecad2012-05-23 22:26:55 +0200138 except:
139 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')
Sandro Tosi876ecad2012-05-23 22:26:55 +0200154 except:
155 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):
Sandro Tosi876ecad2012-05-23 22:26:55 +0200167 """Find a sequence of 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
172 Returns:
173 A tuple containing the first and last IP addresses in the sequence.
174
175 """
176 first = last = addresses[0]
177 for ip in addresses[1:]:
178 if ip._ip == last._ip + 1:
179 last = ip
180 else:
181 break
182 return (first, last)
183
Sandro Tosib95c6342012-05-23 23:17:22 +0200184
Nick Coghlandc9b2552012-05-20 21:01:57 +1000185def _count_righthand_zero_bits(number, bits):
186 """Count the number of zero bits on the right hand side.
187
188 Args:
189 number: an integer.
190 bits: maximum number of bits to count.
191
192 Returns:
193 The number of zero bits on the right hand side of the number.
194
195 """
196 if number == 0:
197 return bits
198 for i in range(bits):
Nick Coghlan7319f692012-07-07 21:43:30 +1000199 if (number >> i) & 1:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000200 return i
Nick Coghlan7319f692012-07-07 21:43:30 +1000201 # All bits of interest were zero, even if there are more in the number
202 return bits
Nick Coghlandc9b2552012-05-20 21:01:57 +1000203
204
205def summarize_address_range(first, last):
206 """Summarize a network range given the first and last IP addresses.
207
208 Example:
Eli Bendersky948af232012-10-07 07:23:50 -0700209 >>> list(summarize_address_range(IPv4Address('192.0.2.0'),
210 ... IPv4Address('192.0.2.130')))
211 ... #doctest: +NORMALIZE_WHITESPACE
Nick Coghlandc9b2552012-05-20 21:01:57 +1000212 [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'),
Eli Bendersky948af232012-10-07 07:23:50 -0700213 IPv4Network('192.0.2.130/32')]
Nick Coghlandc9b2552012-05-20 21:01:57 +1000214
215 Args:
216 first: the first IPv4Address or IPv6Address in the range.
217 last: the last IPv4Address or IPv6Address in the range.
218
219 Returns:
220 An iterator of the summarized IPv(4|6) network objects.
221
222 Raise:
223 TypeError:
224 If the first and last objects are not IP addresses.
225 If the first and last objects are not the same version.
226 ValueError:
227 If the last object is not greater than the first.
Nick Coghlan51c30672012-05-27 00:25:58 +1000228 If the version of the first address is not 4 or 6.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000229
230 """
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200231 if (not (isinstance(first, _BaseAddress) and
232 isinstance(last, _BaseAddress))):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000233 raise TypeError('first and last must be IP addresses, not networks')
234 if first.version != last.version:
235 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000236 first, last))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000237 if first > last:
238 raise ValueError('last IP address must be greater than first')
239
Nick Coghlandc9b2552012-05-20 21:01:57 +1000240 if first.version == 4:
241 ip = IPv4Network
242 elif first.version == 6:
243 ip = IPv6Network
244 else:
245 raise ValueError('unknown IP version')
246
247 ip_bits = first._max_prefixlen
248 first_int = first._ip
249 last_int = last._ip
250 while first_int <= last_int:
Nick Coghlan7319f692012-07-07 21:43:30 +1000251 nbits = min(_count_righthand_zero_bits(first_int, ip_bits),
252 (last_int - first_int + 1).bit_length() - 1)
253 net = ip('%s/%d' % (first, ip_bits - nbits))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000254 yield net
Nick Coghlan7319f692012-07-07 21:43:30 +1000255 first_int += 1 << nbits
256 if first_int - 1 == ip._ALL_ONES:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000257 break
Nick Coghlan51c30672012-05-27 00:25:58 +1000258 first = first.__class__(first_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000259
Sandro Tosib95c6342012-05-23 23:17:22 +0200260
Nick Coghlandc9b2552012-05-20 21:01:57 +1000261def _collapse_addresses_recursive(addresses):
262 """Loops through the addresses, collapsing concurrent netblocks.
263
264 Example:
265
266 ip1 = IPv4Network('192.0.2.0/26')
267 ip2 = IPv4Network('192.0.2.64/26')
268 ip3 = IPv4Network('192.0.2.128/26')
269 ip4 = IPv4Network('192.0.2.192/26')
270
271 _collapse_addresses_recursive([ip1, ip2, ip3, ip4]) ->
272 [IPv4Network('192.0.2.0/24')]
273
274 This shouldn't be called directly; it is called via
275 collapse_addresses([]).
276
277 Args:
278 addresses: A list of IPv4Network's or IPv6Network's
279
280 Returns:
281 A list of IPv4Network's or IPv6Network's depending on what we were
282 passed.
283
284 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000285 while True:
286 last_addr = None
287 ret_array = []
288 optimized = False
Nick Coghlandc9b2552012-05-20 21:01:57 +1000289
Nick Coghlan7319f692012-07-07 21:43:30 +1000290 for cur_addr in addresses:
291 if not ret_array:
292 last_addr = cur_addr
293 ret_array.append(cur_addr)
294 elif (cur_addr.network_address >= last_addr.network_address and
295 cur_addr.broadcast_address <= last_addr.broadcast_address):
296 optimized = True
297 elif cur_addr == list(last_addr.supernet().subnets())[1]:
298 ret_array[-1] = last_addr = last_addr.supernet()
299 optimized = True
300 else:
301 last_addr = cur_addr
302 ret_array.append(cur_addr)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000303
Nick Coghlan7319f692012-07-07 21:43:30 +1000304 addresses = ret_array
305 if not optimized:
306 return addresses
Nick Coghlandc9b2552012-05-20 21:01:57 +1000307
308
309def collapse_addresses(addresses):
310 """Collapse a list of IP objects.
311
312 Example:
313 collapse_addresses([IPv4Network('192.0.2.0/25'),
314 IPv4Network('192.0.2.128/25')]) ->
315 [IPv4Network('192.0.2.0/24')]
316
317 Args:
318 addresses: An iterator of IPv4Network or IPv6Network objects.
319
320 Returns:
321 An iterator of the collapsed IPv(4|6)Network objects.
322
323 Raises:
324 TypeError: If passed a list of mixed version objects.
325
326 """
327 i = 0
328 addrs = []
329 ips = []
330 nets = []
331
332 # split IP addresses and networks
333 for ip in addresses:
334 if isinstance(ip, _BaseAddress):
335 if ips and ips[-1]._version != ip._version:
336 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000337 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000338 ips.append(ip)
339 elif ip._prefixlen == ip._max_prefixlen:
340 if ips and ips[-1]._version != ip._version:
341 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000342 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000343 try:
344 ips.append(ip.ip)
345 except AttributeError:
346 ips.append(ip.network_address)
347 else:
348 if nets and nets[-1]._version != ip._version:
349 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000350 ip, nets[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000351 nets.append(ip)
352
353 # sort and dedup
354 ips = sorted(set(ips))
355 nets = sorted(set(nets))
356
357 while i < len(ips):
358 (first, last) = _find_address_range(ips[i:])
359 i = ips.index(last) + 1
360 addrs.extend(summarize_address_range(first, last))
361
362 return iter(_collapse_addresses_recursive(sorted(
363 addrs + nets, key=_BaseNetwork._get_networks_key)))
364
365
366def get_mixed_type_key(obj):
367 """Return a key suitable for sorting between networks and addresses.
368
369 Address and Network objects are not sortable by default; they're
370 fundamentally different so the expression
371
372 IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
373
374 doesn't make any sense. There are some times however, where you may wish
375 to have ipaddress sort these for you anyway. If you need to do this, you
376 can use this function as the key= argument to sorted().
377
378 Args:
379 obj: either a Network or Address object.
380 Returns:
381 appropriate key.
382
383 """
384 if isinstance(obj, _BaseNetwork):
385 return obj._get_networks_key()
386 elif isinstance(obj, _BaseAddress):
387 return obj._get_address_key()
388 return NotImplemented
389
390
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200391class _IPAddressBase:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000392
393 """The mother class."""
394
395 @property
396 def exploded(self):
397 """Return the longhand version of the IP address as a string."""
398 return self._explode_shorthand_ip_string()
399
400 @property
401 def compressed(self):
402 """Return the shorthand version of the IP address as a string."""
403 return str(self)
404
Nick Coghland9722652012-06-17 16:33:00 +1000405 @property
406 def version(self):
407 msg = '%200s has no version specified' % (type(self),)
408 raise NotImplementedError(msg)
409
Nick Coghlan297b1432012-07-08 17:11:04 +1000410 def _check_int_address(self, address):
411 if address < 0:
412 msg = "%d (< 0) is not permitted as an IPv%d address"
413 raise AddressValueError(msg % (address, self._version))
414 if address > self._ALL_ONES:
415 msg = "%d (>= 2**%d) is not permitted as an IPv%d address"
416 raise AddressValueError(msg % (address, self._max_prefixlen,
417 self._version))
418
419 def _check_packed_address(self, address, expected_len):
420 address_len = len(address)
421 if address_len != expected_len:
422 msg = "%r (len %d != %d) is not permitted as an IPv%d address"
423 raise AddressValueError(msg % (address, address_len,
424 expected_len, self._version))
425
Nick Coghlan932346f2014-02-08 23:17:36 +1000426 def _ip_int_from_prefix(self, prefixlen):
427 """Turn the prefix length into a bitwise netmask
Nick Coghlandc9b2552012-05-20 21:01:57 +1000428
429 Args:
430 prefixlen: An integer, the prefix length.
431
432 Returns:
433 An integer.
434
435 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000436 return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen)
437
Nick Coghlan932346f2014-02-08 23:17:36 +1000438 def _prefix_from_ip_int(self, ip_int):
439 """Return prefix length from the bitwise netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000440
441 Args:
Berker Peksagf23530f2014-10-19 18:04:38 +0300442 ip_int: An integer, the netmask in expanded bitwise format
Nick Coghlandc9b2552012-05-20 21:01:57 +1000443
444 Returns:
445 An integer, the prefix length.
446
Nick Coghlan932346f2014-02-08 23:17:36 +1000447 Raises:
448 ValueError: If the input intermingles zeroes & ones
Nick Coghlandc9b2552012-05-20 21:01:57 +1000449 """
Nick Coghlan932346f2014-02-08 23:17:36 +1000450 trailing_zeroes = _count_righthand_zero_bits(ip_int,
451 self._max_prefixlen)
452 prefixlen = self._max_prefixlen - trailing_zeroes
453 leading_ones = ip_int >> trailing_zeroes
454 all_ones = (1 << prefixlen) - 1
455 if leading_ones != all_ones:
456 byteslen = self._max_prefixlen // 8
457 details = ip_int.to_bytes(byteslen, 'big')
458 msg = 'Netmask pattern %r mixes zeroes & ones'
459 raise ValueError(msg % details)
460 return prefixlen
Nick Coghlandc9b2552012-05-20 21:01:57 +1000461
Nick Coghlan932346f2014-02-08 23:17:36 +1000462 def _report_invalid_netmask(self, netmask_str):
463 msg = '%r is not a valid netmask' % netmask_str
464 raise NetmaskValueError(msg) from None
465
466 def _prefix_from_prefix_string(self, prefixlen_str):
467 """Return prefix length from a numeric string
Nick Coghlandc9b2552012-05-20 21:01:57 +1000468
469 Args:
Nick Coghlan932346f2014-02-08 23:17:36 +1000470 prefixlen_str: The string to be converted
Nick Coghlandc9b2552012-05-20 21:01:57 +1000471
472 Returns:
Nick Coghlan932346f2014-02-08 23:17:36 +1000473 An integer, the prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000474
Nick Coghlan932346f2014-02-08 23:17:36 +1000475 Raises:
476 NetmaskValueError: If the input is not a valid netmask
Nick Coghlandc9b2552012-05-20 21:01:57 +1000477 """
Nick Coghlan932346f2014-02-08 23:17:36 +1000478 # int allows a leading +/- as well as surrounding whitespace,
479 # so we ensure that isn't the case
480 if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
481 self._report_invalid_netmask(prefixlen_str)
482 try:
483 prefixlen = int(prefixlen_str)
484 except ValueError:
485 self._report_invalid_netmask(prefixlen_str)
486 if not (0 <= prefixlen <= self._max_prefixlen):
487 self._report_invalid_netmask(prefixlen_str)
488 return prefixlen
489
490 def _prefix_from_ip_string(self, ip_str):
491 """Turn a netmask/hostmask string into a prefix length
492
493 Args:
494 ip_str: The netmask/hostmask to be converted
495
496 Returns:
497 An integer, the prefix length.
498
499 Raises:
500 NetmaskValueError: If the input is not a valid netmask/hostmask
501 """
502 # Parse the netmask/hostmask like an IP address.
503 try:
504 ip_int = self._ip_int_from_string(ip_str)
505 except AddressValueError:
506 self._report_invalid_netmask(ip_str)
507
508 # Try matching a netmask (this would be /1*0*/ as a bitwise regexp).
509 # Note that the two ambiguous cases (all-ones and all-zeroes) are
510 # treated as netmasks.
511 try:
512 return self._prefix_from_ip_int(ip_int)
513 except ValueError:
514 pass
515
516 # Invert the bits, and try matching a /0+1+/ hostmask instead.
517 ip_int ^= self._ALL_ONES
518 try:
519 return self._prefix_from_ip_int(ip_int)
520 except ValueError:
521 self._report_invalid_netmask(ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000522
Nick Coghlan730f67f2012-08-05 22:02:18 +1000523
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200524@functools.total_ordering
Nick Coghlandc9b2552012-05-20 21:01:57 +1000525class _BaseAddress(_IPAddressBase):
526
527 """A generic IP object.
528
529 This IP class contains the version independent methods which are
530 used by single IP addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000531 """
532
533 def __init__(self, address):
534 if (not isinstance(address, bytes)
535 and '/' in str(address)):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000536 raise AddressValueError("Unexpected '/' in %r" % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000537
Nick Coghlandc9b2552012-05-20 21:01:57 +1000538 def __int__(self):
539 return self._ip
540
Nick Coghlandc9b2552012-05-20 21:01:57 +1000541 def __eq__(self, other):
542 try:
543 return (self._ip == other._ip
544 and self._version == other._version)
545 except AttributeError:
546 return NotImplemented
547
Nick Coghlandc9b2552012-05-20 21:01:57 +1000548 def __lt__(self, other):
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200549 if not isinstance(other, _BaseAddress):
550 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000551 if self._version != other._version:
552 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000553 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000554 if self._ip != other._ip:
555 return self._ip < other._ip
556 return False
557
Nick Coghlandc9b2552012-05-20 21:01:57 +1000558 # Shorthand for Integer addition and subtraction. This is not
559 # meant to ever support addition/subtraction of addresses.
560 def __add__(self, other):
561 if not isinstance(other, int):
562 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000563 return self.__class__(int(self) + other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000564
565 def __sub__(self, other):
566 if not isinstance(other, int):
567 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000568 return self.__class__(int(self) - other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000569
570 def __repr__(self):
571 return '%s(%r)' % (self.__class__.__name__, str(self))
572
573 def __str__(self):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200574 return str(self._string_from_ip_int(self._ip))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000575
576 def __hash__(self):
577 return hash(hex(int(self._ip)))
578
579 def _get_address_key(self):
580 return (self._version, self)
581
Nick Coghlandc9b2552012-05-20 21:01:57 +1000582
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200583@functools.total_ordering
Nick Coghlandc9b2552012-05-20 21:01:57 +1000584class _BaseNetwork(_IPAddressBase):
585
Nick Coghlan51c30672012-05-27 00:25:58 +1000586 """A generic IP network object.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000587
588 This IP class contains the version independent methods which are
589 used by networks.
590
591 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000592 def __init__(self, address):
593 self._cache = {}
594
Nick Coghlandc9b2552012-05-20 21:01:57 +1000595 def __repr__(self):
596 return '%s(%r)' % (self.__class__.__name__, str(self))
597
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200598 def __str__(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000599 return '%s/%d' % (self.network_address, self.prefixlen)
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200600
Nick Coghlandc9b2552012-05-20 21:01:57 +1000601 def hosts(self):
602 """Generate Iterator over usable hosts in a network.
603
Sandro Tosib95c6342012-05-23 23:17:22 +0200604 This is like __iter__ except it doesn't return the network
605 or broadcast addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000606
607 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000608 network = int(self.network_address)
609 broadcast = int(self.broadcast_address)
610 for x in range(network + 1, broadcast):
611 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000612
613 def __iter__(self):
Nick Coghlan7319f692012-07-07 21:43:30 +1000614 network = int(self.network_address)
615 broadcast = int(self.broadcast_address)
616 for x in range(network, broadcast + 1):
617 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000618
619 def __getitem__(self, n):
620 network = int(self.network_address)
621 broadcast = int(self.broadcast_address)
622 if n >= 0:
623 if network + n > broadcast:
624 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000625 return self._address_class(network + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000626 else:
627 n += 1
628 if broadcast + n < network:
629 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000630 return self._address_class(broadcast + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000631
632 def __lt__(self, other):
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200633 if not isinstance(other, _BaseNetwork):
634 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000635 if self._version != other._version:
636 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000637 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000638 if self.network_address != other.network_address:
639 return self.network_address < other.network_address
640 if self.netmask != other.netmask:
641 return self.netmask < other.netmask
642 return False
643
Nick Coghlandc9b2552012-05-20 21:01:57 +1000644 def __eq__(self, other):
Nick Coghlan9a9c28c2012-07-07 23:05:59 +1000645 try:
646 return (self._version == other._version and
647 self.network_address == other.network_address and
648 int(self.netmask) == int(other.netmask))
649 except AttributeError:
650 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000651
Nick Coghlandc9b2552012-05-20 21:01:57 +1000652 def __hash__(self):
653 return hash(int(self.network_address) ^ int(self.netmask))
654
655 def __contains__(self, other):
656 # always false if one is v4 and the other is v6.
657 if self._version != other._version:
658 return False
659 # dealing with another network.
660 if isinstance(other, _BaseNetwork):
661 return False
662 # dealing with another address
663 else:
664 # address
665 return (int(self.network_address) <= int(other._ip) <=
666 int(self.broadcast_address))
667
668 def overlaps(self, other):
669 """Tell if self is partly contained in other."""
670 return self.network_address in other or (
671 self.broadcast_address in other or (
672 other.network_address in self or (
673 other.broadcast_address in self)))
674
675 @property
676 def broadcast_address(self):
677 x = self._cache.get('broadcast_address')
678 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000679 x = self._address_class(int(self.network_address) |
680 int(self.hostmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000681 self._cache['broadcast_address'] = x
682 return x
683
684 @property
685 def hostmask(self):
686 x = self._cache.get('hostmask')
687 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000688 x = self._address_class(int(self.netmask) ^ self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000689 self._cache['hostmask'] = x
690 return x
691
692 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000693 def with_prefixlen(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000694 return '%s/%d' % (self.network_address, self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000695
696 @property
697 def with_netmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000698 return '%s/%s' % (self.network_address, self.netmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000699
700 @property
701 def with_hostmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000702 return '%s/%s' % (self.network_address, self.hostmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000703
704 @property
705 def num_addresses(self):
706 """Number of hosts in the current subnet."""
707 return int(self.broadcast_address) - int(self.network_address) + 1
708
709 @property
Nick Coghlan51c30672012-05-27 00:25:58 +1000710 def _address_class(self):
Nick Coghland9722652012-06-17 16:33:00 +1000711 # Returning bare address objects (rather than interfaces) allows for
712 # more consistent behaviour across the network address, broadcast
713 # address and individual host addresses.
714 msg = '%200s has no associated address class' % (type(self),)
715 raise NotImplementedError(msg)
Nick Coghlan51c30672012-05-27 00:25:58 +1000716
717 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000718 def prefixlen(self):
719 return self._prefixlen
720
721 def address_exclude(self, other):
722 """Remove an address from a larger block.
723
724 For example:
725
726 addr1 = ip_network('192.0.2.0/28')
727 addr2 = ip_network('192.0.2.1/32')
728 addr1.address_exclude(addr2) =
729 [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
730 IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
731
732 or IPv6:
733
734 addr1 = ip_network('2001:db8::1/32')
735 addr2 = ip_network('2001:db8::1/128')
736 addr1.address_exclude(addr2) =
737 [ip_network('2001:db8::1/128'),
738 ip_network('2001:db8::2/127'),
739 ip_network('2001:db8::4/126'),
740 ip_network('2001:db8::8/125'),
741 ...
742 ip_network('2001:db8:8000::/33')]
743
744 Args:
745 other: An IPv4Network or IPv6Network object of the same type.
746
747 Returns:
Ezio Melotti3f5db392013-01-27 06:20:14 +0200748 An iterator of the IPv(4|6)Network objects which is self
Nick Coghlandc9b2552012-05-20 21:01:57 +1000749 minus other.
750
751 Raises:
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300752 TypeError: If self and other are of differing address
Nick Coghlandc9b2552012-05-20 21:01:57 +1000753 versions, or if other is not a network object.
754 ValueError: If other is not completely contained by self.
755
756 """
757 if not self._version == other._version:
758 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000759 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000760
761 if not isinstance(other, _BaseNetwork):
Nick Coghlan912238e2012-07-07 13:34:50 +1000762 raise TypeError("%s is not a network object" % other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000763
764 if not (other.network_address >= self.network_address and
765 other.broadcast_address <= self.broadcast_address):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200766 raise ValueError('%s not contained in %s' % (other, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000767 if other == self:
768 raise StopIteration
769
Nick Coghlandc9b2552012-05-20 21:01:57 +1000770 # Make sure we're comparing the network of other.
Nick Coghlan912238e2012-07-07 13:34:50 +1000771 other = other.__class__('%s/%s' % (other.network_address,
772 other.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000773
774 s1, s2 = self.subnets()
775 while s1 != other and s2 != other:
776 if (other.network_address >= s1.network_address and
777 other.broadcast_address <= s1.broadcast_address):
778 yield s2
779 s1, s2 = s1.subnets()
780 elif (other.network_address >= s2.network_address and
781 other.broadcast_address <= s2.broadcast_address):
782 yield s1
783 s1, s2 = s2.subnets()
784 else:
785 # If we got here, there's a bug somewhere.
786 raise AssertionError('Error performing exclusion: '
787 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000788 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000789 if s1 == other:
790 yield s2
791 elif s2 == other:
792 yield s1
793 else:
794 # If we got here, there's a bug somewhere.
795 raise AssertionError('Error performing exclusion: '
796 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000797 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000798
799 def compare_networks(self, other):
800 """Compare two IP objects.
801
802 This is only concerned about the comparison of the integer
803 representation of the network addresses. This means that the
804 host bits aren't considered at all in this method. If you want
805 to compare host bits, you can easily enough do a
806 'HostA._ip < HostB._ip'
807
808 Args:
809 other: An IP object.
810
811 Returns:
812 If the IP versions of self and other are the same, returns:
813
814 -1 if self < other:
815 eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
816 IPv6Network('2001:db8::1000/124') <
817 IPv6Network('2001:db8::2000/124')
818 0 if self == other
819 eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
820 IPv6Network('2001:db8::1000/124') ==
821 IPv6Network('2001:db8::1000/124')
822 1 if self > other
823 eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
824 IPv6Network('2001:db8::2000/124') >
825 IPv6Network('2001:db8::1000/124')
826
827 Raises:
828 TypeError if the IP versions are different.
829
830 """
831 # does this need to raise a ValueError?
832 if self._version != other._version:
833 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000834 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000835 # self._version == other._version below here:
836 if self.network_address < other.network_address:
837 return -1
838 if self.network_address > other.network_address:
839 return 1
840 # self.network_address == other.network_address below here:
841 if self.netmask < other.netmask:
842 return -1
843 if self.netmask > other.netmask:
844 return 1
845 return 0
846
847 def _get_networks_key(self):
848 """Network-only key function.
849
850 Returns an object that identifies this address' network and
851 netmask. This function is a suitable "key" argument for sorted()
852 and list.sort().
853
854 """
855 return (self._version, self.network_address, self.netmask)
856
857 def subnets(self, prefixlen_diff=1, new_prefix=None):
858 """The subnets which join to make the current subnet.
859
860 In the case that self contains only one IP
861 (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
862 for IPv6), yield an iterator with just ourself.
863
864 Args:
865 prefixlen_diff: An integer, the amount the prefix length
866 should be increased by. This should not be set if
867 new_prefix is also set.
868 new_prefix: The desired new prefix length. This must be a
869 larger number (smaller prefix) than the existing prefix.
870 This should not be set if prefixlen_diff is also set.
871
872 Returns:
873 An iterator of IPv(4|6) objects.
874
875 Raises:
876 ValueError: The prefixlen_diff is too small or too large.
877 OR
878 prefixlen_diff and new_prefix are both set or new_prefix
879 is a smaller number than the current prefix (smaller
880 number means a larger network)
881
882 """
883 if self._prefixlen == self._max_prefixlen:
884 yield self
885 return
886
887 if new_prefix is not None:
888 if new_prefix < self._prefixlen:
889 raise ValueError('new prefix must be longer')
890 if prefixlen_diff != 1:
891 raise ValueError('cannot set prefixlen_diff and new_prefix')
892 prefixlen_diff = new_prefix - self._prefixlen
893
894 if prefixlen_diff < 0:
895 raise ValueError('prefix length diff must be > 0')
896 new_prefixlen = self._prefixlen + prefixlen_diff
897
Nick Coghlan932346f2014-02-08 23:17:36 +1000898 if new_prefixlen > self._max_prefixlen:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000899 raise ValueError(
900 'prefix length diff %d is invalid for netblock %s' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000901 new_prefixlen, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000902
Nick Coghlan51c30672012-05-27 00:25:58 +1000903 first = self.__class__('%s/%s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000904 (self.network_address,
905 self._prefixlen + prefixlen_diff))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000906
907 yield first
908 current = first
909 while True:
910 broadcast = current.broadcast_address
911 if broadcast == self.broadcast_address:
912 return
Nick Coghlan51c30672012-05-27 00:25:58 +1000913 new_addr = self._address_class(int(broadcast) + 1)
Nick Coghlan912238e2012-07-07 13:34:50 +1000914 current = self.__class__('%s/%s' % (new_addr,
915 new_prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000916
917 yield current
918
Nick Coghlandc9b2552012-05-20 21:01:57 +1000919 def supernet(self, prefixlen_diff=1, new_prefix=None):
920 """The supernet containing the current network.
921
922 Args:
923 prefixlen_diff: An integer, the amount the prefix length of
924 the network should be decreased by. For example, given a
925 /24 network and a prefixlen_diff of 3, a supernet with a
926 /21 netmask is returned.
927
928 Returns:
929 An IPv4 network object.
930
931 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200932 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
933 a negative prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000934 OR
935 If prefixlen_diff and new_prefix are both set or new_prefix is a
936 larger number than the current prefix (larger number means a
937 smaller network)
938
939 """
940 if self._prefixlen == 0:
941 return self
942
943 if new_prefix is not None:
944 if new_prefix > self._prefixlen:
945 raise ValueError('new prefix must be shorter')
946 if prefixlen_diff != 1:
947 raise ValueError('cannot set prefixlen_diff and new_prefix')
948 prefixlen_diff = self._prefixlen - new_prefix
949
Nick Coghlandc9b2552012-05-20 21:01:57 +1000950 if self.prefixlen - prefixlen_diff < 0:
951 raise ValueError(
952 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
953 (self.prefixlen, prefixlen_diff))
954 # TODO (pmoody): optimize this.
Nick Coghlan912238e2012-07-07 13:34:50 +1000955 t = self.__class__('%s/%d' % (self.network_address,
Nick Coghlan51c30672012-05-27 00:25:58 +1000956 self.prefixlen - prefixlen_diff),
957 strict=False)
Nick Coghlan912238e2012-07-07 13:34:50 +1000958 return t.__class__('%s/%d' % (t.network_address, t.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000959
Nick Coghlan730f67f2012-08-05 22:02:18 +1000960 @property
961 def is_multicast(self):
962 """Test if the address is reserved for multicast use.
963
964 Returns:
965 A boolean, True if the address is a multicast address.
966 See RFC 2373 2.7 for details.
967
968 """
969 return (self.network_address.is_multicast and
970 self.broadcast_address.is_multicast)
971
972 @property
973 def is_reserved(self):
974 """Test if the address is otherwise IETF reserved.
975
976 Returns:
977 A boolean, True if the address is within one of the
978 reserved IPv6 Network ranges.
979
980 """
981 return (self.network_address.is_reserved and
982 self.broadcast_address.is_reserved)
983
984 @property
985 def is_link_local(self):
986 """Test if the address is reserved for link-local.
987
988 Returns:
989 A boolean, True if the address is reserved per RFC 4291.
990
991 """
992 return (self.network_address.is_link_local and
993 self.broadcast_address.is_link_local)
994
995 @property
996 def is_private(self):
997 """Test if this address is allocated for private networks.
998
999 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001000 A boolean, True if the address is reserved per
1001 iana-ipv4-special-registry or iana-ipv6-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001002
1003 """
1004 return (self.network_address.is_private and
1005 self.broadcast_address.is_private)
1006
1007 @property
Peter Moody22c31762013-10-21 13:58:06 -07001008 def is_global(self):
Peter Moodybe9c1b12013-10-22 12:36:21 -07001009 """Test if this address is allocated for public networks.
Peter Moody22c31762013-10-21 13:58:06 -07001010
1011 Returns:
1012 A boolean, True if the address is not reserved per
1013 iana-ipv4-special-registry or iana-ipv6-special-registry.
1014
1015 """
1016 return not self.is_private
1017
1018 @property
Nick Coghlan730f67f2012-08-05 22:02:18 +10001019 def is_unspecified(self):
1020 """Test if the address is unspecified.
1021
1022 Returns:
1023 A boolean, True if this is the unspecified address as defined in
1024 RFC 2373 2.5.2.
1025
1026 """
1027 return (self.network_address.is_unspecified and
1028 self.broadcast_address.is_unspecified)
1029
1030 @property
1031 def is_loopback(self):
1032 """Test if the address is a loopback address.
1033
1034 Returns:
1035 A boolean, True if the address is a loopback address as defined in
1036 RFC 2373 2.5.3.
1037
1038 """
1039 return (self.network_address.is_loopback and
1040 self.broadcast_address.is_loopback)
1041
Nick Coghlandc9b2552012-05-20 21:01:57 +10001042
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001043class _BaseV4:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001044
1045 """Base IPv4 object.
1046
1047 The following methods are used by IPv4 objects in both single IP
1048 addresses and networks.
1049
1050 """
1051
1052 # Equivalent to 255.255.255.255 or 32 bits of 1's.
1053 _ALL_ONES = (2**IPV4LENGTH) - 1
1054 _DECIMAL_DIGITS = frozenset('0123456789')
1055
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001056 # the valid octets for host and netmasks. only useful for IPv4.
Nick Coghlan7319f692012-07-07 21:43:30 +10001057 _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0))
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001058
Nick Coghlandc9b2552012-05-20 21:01:57 +10001059 def __init__(self, address):
1060 self._version = 4
1061 self._max_prefixlen = IPV4LENGTH
1062
1063 def _explode_shorthand_ip_string(self):
1064 return str(self)
1065
1066 def _ip_int_from_string(self, ip_str):
1067 """Turn the given IP string into an integer for comparison.
1068
1069 Args:
1070 ip_str: A string, the IP ip_str.
1071
1072 Returns:
1073 The IP ip_str as an integer.
1074
1075 Raises:
1076 AddressValueError: if ip_str isn't a valid IPv4 Address.
1077
1078 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001079 if not ip_str:
1080 raise AddressValueError('Address cannot be empty')
1081
Nick Coghlandc9b2552012-05-20 21:01:57 +10001082 octets = ip_str.split('.')
1083 if len(octets) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001084 raise AddressValueError("Expected 4 octets in %r" % ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001085
Nick Coghlan7319f692012-07-07 21:43:30 +10001086 try:
1087 return int.from_bytes(map(self._parse_octet, octets), 'big')
1088 except ValueError as exc:
1089 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001090
1091 def _parse_octet(self, octet_str):
1092 """Convert a decimal octet into an integer.
1093
1094 Args:
1095 octet_str: A string, the number to parse.
1096
1097 Returns:
1098 The octet as an integer.
1099
1100 Raises:
1101 ValueError: if the octet isn't strictly a decimal from [0..255].
1102
1103 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001104 if not octet_str:
1105 raise ValueError("Empty octet not permitted")
Nick Coghlandc9b2552012-05-20 21:01:57 +10001106 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1107 if not self._DECIMAL_DIGITS.issuperset(octet_str):
Nick Coghlan07c4e332012-07-08 23:06:45 +10001108 msg = "Only decimal digits permitted in %r"
1109 raise ValueError(msg % octet_str)
1110 # We do the length check second, since the invalid character error
1111 # is likely to be more informative for the user
1112 if len(octet_str) > 3:
1113 msg = "At most 3 characters permitted in %r"
1114 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001115 # Convert to integer (we know digits are legal)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001116 octet_int = int(octet_str, 10)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001117 # Any octets that look like they *might* be written in octal,
1118 # and which don't look exactly the same in both octal and
1119 # decimal are rejected as ambiguous
1120 if octet_int > 7 and octet_str[0] == '0':
Nick Coghlan07c4e332012-07-08 23:06:45 +10001121 msg = "Ambiguous (octal/decimal) value in %r not permitted"
1122 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001123 if octet_int > 255:
Nick Coghlanb582ecc2012-07-07 22:15:22 +10001124 raise ValueError("Octet %d (> 255) not permitted" % octet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001125 return octet_int
1126
1127 def _string_from_ip_int(self, ip_int):
1128 """Turns a 32-bit integer into dotted decimal notation.
1129
1130 Args:
1131 ip_int: An integer, the IP address.
1132
1133 Returns:
1134 The IP address as a string in dotted decimal notation.
1135
1136 """
Nick Coghlan7319f692012-07-07 21:43:30 +10001137 return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001138
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001139 def _is_valid_netmask(self, netmask):
1140 """Verify that the netmask is valid.
1141
1142 Args:
1143 netmask: A string, either a prefix or dotted decimal
1144 netmask.
1145
1146 Returns:
1147 A boolean, True if the prefix represents a valid IPv4
1148 netmask.
1149
1150 """
1151 mask = netmask.split('.')
1152 if len(mask) == 4:
Nick Coghlan7319f692012-07-07 21:43:30 +10001153 try:
1154 for x in mask:
1155 if int(x) not in self._valid_mask_octets:
1156 return False
1157 except ValueError:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001158 # Found something that isn't an integer or isn't valid
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001159 return False
Nick Coghlan7319f692012-07-07 21:43:30 +10001160 for idx, y in enumerate(mask):
1161 if idx > 0 and y > mask[idx - 1]:
1162 return False
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001163 return True
1164 try:
1165 netmask = int(netmask)
1166 except ValueError:
1167 return False
1168 return 0 <= netmask <= self._max_prefixlen
1169
1170 def _is_hostmask(self, ip_str):
1171 """Test if the IP string is a hostmask (rather than a netmask).
1172
1173 Args:
1174 ip_str: A string, the potential hostmask.
1175
1176 Returns:
1177 A boolean, True if the IP string is a hostmask.
1178
1179 """
1180 bits = ip_str.split('.')
1181 try:
Nick Coghlan7319f692012-07-07 21:43:30 +10001182 parts = [x for x in map(int, bits) if x in self._valid_mask_octets]
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001183 except ValueError:
1184 return False
1185 if len(parts) != len(bits):
1186 return False
1187 if parts[0] < parts[-1]:
1188 return True
1189 return False
1190
Nick Coghlandc9b2552012-05-20 21:01:57 +10001191 @property
1192 def max_prefixlen(self):
1193 return self._max_prefixlen
1194
1195 @property
1196 def version(self):
1197 return self._version
1198
Nick Coghlandc9b2552012-05-20 21:01:57 +10001199
1200class IPv4Address(_BaseV4, _BaseAddress):
1201
1202 """Represent and manipulate single IPv4 Addresses."""
1203
1204 def __init__(self, address):
1205
1206 """
1207 Args:
1208 address: A string or integer representing the IP
1209
1210 Additionally, an integer can be passed, so
1211 IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1212 or, more generally
1213 IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1214 IPv4Address('192.0.2.1')
1215
1216 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001217 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001218
1219 """
1220 _BaseAddress.__init__(self, address)
1221 _BaseV4.__init__(self, address)
1222
1223 # Efficient constructor from integer.
1224 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001225 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001226 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001227 return
1228
1229 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001230 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001231 self._check_packed_address(address, 4)
Nick Coghlandb7920b2012-08-20 10:19:12 +10001232 self._ip = int.from_bytes(address, 'big')
Nick Coghlandc9b2552012-05-20 21:01:57 +10001233 return
1234
1235 # Assume input argument to be string or any object representation
1236 # which converts into a formatted IP string.
1237 addr_str = str(address)
1238 self._ip = self._ip_int_from_string(addr_str)
1239
1240 @property
1241 def packed(self):
1242 """The binary representation of this address."""
1243 return v4_int_to_packed(self._ip)
1244
Nick Coghlan730f67f2012-08-05 22:02:18 +10001245 @property
1246 def is_reserved(self):
1247 """Test if the address is otherwise IETF reserved.
1248
1249 Returns:
1250 A boolean, True if the address is within the
1251 reserved IPv4 Network range.
1252
1253 """
1254 reserved_network = IPv4Network('240.0.0.0/4')
1255 return self in reserved_network
1256
1257 @property
Peter Moodybe9c1b12013-10-22 12:36:21 -07001258 @functools.lru_cache()
Nick Coghlan730f67f2012-08-05 22:02:18 +10001259 def is_private(self):
1260 """Test if this address is allocated for private networks.
1261
1262 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001263 A boolean, True if the address is reserved per
1264 iana-ipv4-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001265
1266 """
Peter Moody22c31762013-10-21 13:58:06 -07001267 return (self in IPv4Network('0.0.0.0/8') or
1268 self in IPv4Network('10.0.0.0/8') or
Peter Moody22c31762013-10-21 13:58:06 -07001269 self in IPv4Network('127.0.0.0/8') or
1270 self in IPv4Network('169.254.0.0/16') or
1271 self in IPv4Network('172.16.0.0/12') or
1272 self in IPv4Network('192.0.0.0/29') or
1273 self in IPv4Network('192.0.0.170/31') or
1274 self in IPv4Network('192.0.2.0/24') or
1275 self in IPv4Network('192.168.0.0/16') or
1276 self in IPv4Network('198.18.0.0/15') or
1277 self in IPv4Network('198.51.100.0/24') or
1278 self in IPv4Network('203.0.113.0/24') or
1279 self in IPv4Network('240.0.0.0/4') or
1280 self in IPv4Network('255.255.255.255/32'))
1281
Nick Coghlan730f67f2012-08-05 22:02:18 +10001282
1283 @property
1284 def is_multicast(self):
1285 """Test if the address is reserved for multicast use.
1286
1287 Returns:
1288 A boolean, True if the address is multicast.
1289 See RFC 3171 for details.
1290
1291 """
1292 multicast_network = IPv4Network('224.0.0.0/4')
1293 return self in multicast_network
1294
1295 @property
1296 def is_unspecified(self):
1297 """Test if the address is unspecified.
1298
1299 Returns:
1300 A boolean, True if this is the unspecified address as defined in
1301 RFC 5735 3.
1302
1303 """
1304 unspecified_address = IPv4Address('0.0.0.0')
1305 return self == unspecified_address
1306
1307 @property
1308 def is_loopback(self):
1309 """Test if the address is a loopback address.
1310
1311 Returns:
1312 A boolean, True if the address is a loopback per RFC 3330.
1313
1314 """
1315 loopback_network = IPv4Network('127.0.0.0/8')
1316 return self in loopback_network
1317
1318 @property
1319 def is_link_local(self):
1320 """Test if the address is reserved for link-local.
1321
1322 Returns:
1323 A boolean, True if the address is link-local per RFC 3927.
1324
1325 """
1326 linklocal_network = IPv4Network('169.254.0.0/16')
1327 return self in linklocal_network
1328
Nick Coghlandc9b2552012-05-20 21:01:57 +10001329
1330class IPv4Interface(IPv4Address):
1331
Nick Coghlandc9b2552012-05-20 21:01:57 +10001332 def __init__(self, address):
1333 if isinstance(address, (bytes, int)):
1334 IPv4Address.__init__(self, address)
1335 self.network = IPv4Network(self._ip)
1336 self._prefixlen = self._max_prefixlen
1337 return
1338
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001339 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001340 IPv4Address.__init__(self, addr[0])
1341
1342 self.network = IPv4Network(address, strict=False)
1343 self._prefixlen = self.network._prefixlen
1344
1345 self.netmask = self.network.netmask
1346 self.hostmask = self.network.hostmask
1347
Nick Coghlandc9b2552012-05-20 21:01:57 +10001348 def __str__(self):
1349 return '%s/%d' % (self._string_from_ip_int(self._ip),
1350 self.network.prefixlen)
1351
1352 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001353 address_equal = IPv4Address.__eq__(self, other)
1354 if not address_equal or address_equal is NotImplemented:
1355 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001356 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001357 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001358 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001359 # An interface with an associated network is NOT the
1360 # same as an unassociated address. That's why the hash
1361 # takes the extra info into account.
1362 return False
1363
1364 def __lt__(self, other):
1365 address_less = IPv4Address.__lt__(self, other)
1366 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001367 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001368 try:
1369 return self.network < other.network
1370 except AttributeError:
1371 # We *do* allow addresses and interfaces to be sorted. The
1372 # unassociated address is considered less than all interfaces.
1373 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001374
1375 def __hash__(self):
1376 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1377
Nick Coghlandc9b2552012-05-20 21:01:57 +10001378 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001379 def ip(self):
1380 return IPv4Address(self._ip)
1381
1382 @property
1383 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10001384 return '%s/%s' % (self._string_from_ip_int(self._ip),
1385 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001386
1387 @property
1388 def with_netmask(self):
1389 return '%s/%s' % (self._string_from_ip_int(self._ip),
1390 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001391
Nick Coghlandc9b2552012-05-20 21:01:57 +10001392 @property
1393 def with_hostmask(self):
1394 return '%s/%s' % (self._string_from_ip_int(self._ip),
1395 self.hostmask)
1396
1397
1398class IPv4Network(_BaseV4, _BaseNetwork):
1399
1400 """This class represents and manipulates 32-bit IPv4 network + addresses..
1401
1402 Attributes: [examples for IPv4Network('192.0.2.0/27')]
1403 .network_address: IPv4Address('192.0.2.0')
1404 .hostmask: IPv4Address('0.0.0.31')
1405 .broadcast_address: IPv4Address('192.0.2.32')
1406 .netmask: IPv4Address('255.255.255.224')
1407 .prefixlen: 27
1408
1409 """
Nick Coghlan51c30672012-05-27 00:25:58 +10001410 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001411 _address_class = IPv4Address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001412
Nick Coghlandc9b2552012-05-20 21:01:57 +10001413 def __init__(self, address, strict=True):
1414
1415 """Instantiate a new IPv4 network object.
1416
1417 Args:
1418 address: A string or integer representing the IP [& network].
1419 '192.0.2.0/24'
1420 '192.0.2.0/255.255.255.0'
1421 '192.0.0.2/0.0.0.255'
1422 are all functionally the same in IPv4. Similarly,
1423 '192.0.2.1'
1424 '192.0.2.1/255.255.255.255'
1425 '192.0.2.1/32'
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001426 are also functionally equivalent. That is to say, failing to
Nick Coghlandc9b2552012-05-20 21:01:57 +10001427 provide a subnetmask will create an object with a mask of /32.
1428
1429 If the mask (portion after the / in the argument) is given in
1430 dotted quad form, it is treated as a netmask if it starts with a
1431 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1432 starts with a zero field (e.g. 0.255.255.255 == /8), with the
1433 single exception of an all-zero mask which is treated as a
1434 netmask == /0. If no mask is given, a default of /32 is used.
1435
1436 Additionally, an integer can be passed, so
1437 IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1438 or, more generally
1439 IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1440 IPv4Interface('192.0.2.1')
1441
1442 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001443 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001444 NetmaskValueError: If the netmask isn't valid for
1445 an IPv4 address.
Sandro Tosib4386d32012-06-02 17:14:22 +02001446 ValueError: If strict is True and a network address is not
Nick Coghlandc9b2552012-05-20 21:01:57 +10001447 supplied.
1448
1449 """
1450
1451 _BaseV4.__init__(self, address)
1452 _BaseNetwork.__init__(self, address)
1453
1454 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001455 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001456 self.network_address = IPv4Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001457 self._prefixlen = self._max_prefixlen
1458 self.netmask = IPv4Address(self._ALL_ONES)
1459 #fixme: address/network test here
1460 return
1461
1462 # Efficient constructor from integer.
1463 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001464 self.network_address = IPv4Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001465 self._prefixlen = self._max_prefixlen
1466 self.netmask = IPv4Address(self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001467 #fixme: address/network test here.
1468 return
1469
1470 # Assume input argument to be string or any object representation
1471 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001472 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001473 self.network_address = IPv4Address(self._ip_int_from_string(addr[0]))
1474
Nick Coghlandc9b2552012-05-20 21:01:57 +10001475 if len(addr) == 2:
Nick Coghlan932346f2014-02-08 23:17:36 +10001476 try:
1477 # Check for a netmask in prefix length form
1478 self._prefixlen = self._prefix_from_prefix_string(addr[1])
1479 except NetmaskValueError:
1480 # Check for a netmask or hostmask in dotted-quad form.
1481 # This may raise NetmaskValueError.
1482 self._prefixlen = self._prefix_from_ip_string(addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001483 else:
1484 self._prefixlen = self._max_prefixlen
Nick Coghlan932346f2014-02-08 23:17:36 +10001485 self.netmask = IPv4Address(self._ip_int_from_prefix(self._prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001486
1487 if strict:
1488 if (IPv4Address(int(self.network_address) & int(self.netmask)) !=
1489 self.network_address):
1490 raise ValueError('%s has host bits set' % self)
1491 self.network_address = IPv4Address(int(self.network_address) &
1492 int(self.netmask))
1493
1494 if self._prefixlen == (self._max_prefixlen - 1):
1495 self.hosts = self.__iter__
1496
Peter Moodye5019d52013-10-24 09:47:10 -07001497 @property
1498 @functools.lru_cache()
1499 def is_global(self):
1500 """Test if this address is allocated for public networks.
1501
1502 Returns:
1503 A boolean, True if the address is not reserved per
1504 iana-ipv4-special-registry.
1505
1506 """
1507 return (not (self.network_address in IPv4Network('100.64.0.0/10') and
1508 self.broadcast_address in IPv4Network('100.64.0.0/10')) and
1509 not self.is_private)
1510
1511
Nick Coghlandc9b2552012-05-20 21:01:57 +10001512
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001513class _BaseV6:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001514
1515 """Base IPv6 object.
1516
1517 The following methods are used by IPv6 objects in both single IP
1518 addresses and networks.
1519
1520 """
1521
1522 _ALL_ONES = (2**IPV6LENGTH) - 1
1523 _HEXTET_COUNT = 8
1524 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
1525
1526 def __init__(self, address):
1527 self._version = 6
1528 self._max_prefixlen = IPV6LENGTH
1529
1530 def _ip_int_from_string(self, ip_str):
1531 """Turn an IPv6 ip_str into an integer.
1532
1533 Args:
1534 ip_str: A string, the IPv6 ip_str.
1535
1536 Returns:
1537 An int, the IPv6 address
1538
1539 Raises:
1540 AddressValueError: if ip_str isn't a valid IPv6 Address.
1541
1542 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001543 if not ip_str:
1544 raise AddressValueError('Address cannot be empty')
1545
Nick Coghlandc9b2552012-05-20 21:01:57 +10001546 parts = ip_str.split(':')
1547
1548 # An IPv6 address needs at least 2 colons (3 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001549 _min_parts = 3
1550 if len(parts) < _min_parts:
1551 msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
1552 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001553
1554 # If the address has an IPv4-style suffix, convert it to hexadecimal.
1555 if '.' in parts[-1]:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001556 try:
1557 ipv4_int = IPv4Address(parts.pop())._ip
1558 except AddressValueError as exc:
1559 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001560 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1561 parts.append('%x' % (ipv4_int & 0xFFFF))
1562
1563 # An IPv6 address can't have more than 8 colons (9 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001564 # The extra colon comes from using the "::" notation for a single
1565 # leading or trailing zero part.
1566 _max_parts = self._HEXTET_COUNT + 1
1567 if len(parts) > _max_parts:
1568 msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
1569 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001570
1571 # Disregarding the endpoints, find '::' with nothing in between.
1572 # This indicates that a run of zeroes has been skipped.
Nick Coghlan7319f692012-07-07 21:43:30 +10001573 skip_index = None
1574 for i in range(1, len(parts) - 1):
1575 if not parts[i]:
1576 if skip_index is not None:
1577 # Can't have more than one '::'
1578 msg = "At most one '::' permitted in %r" % ip_str
1579 raise AddressValueError(msg)
1580 skip_index = i
Nick Coghlandc9b2552012-05-20 21:01:57 +10001581
1582 # parts_hi is the number of parts to copy from above/before the '::'
1583 # parts_lo is the number of parts to copy from below/after the '::'
1584 if skip_index is not None:
1585 # If we found a '::', then check if it also covers the endpoints.
1586 parts_hi = skip_index
1587 parts_lo = len(parts) - skip_index - 1
1588 if not parts[0]:
1589 parts_hi -= 1
1590 if parts_hi:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001591 msg = "Leading ':' only permitted as part of '::' in %r"
1592 raise AddressValueError(msg % ip_str) # ^: requires ^::
Nick Coghlandc9b2552012-05-20 21:01:57 +10001593 if not parts[-1]:
1594 parts_lo -= 1
1595 if parts_lo:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001596 msg = "Trailing ':' only permitted as part of '::' in %r"
1597 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001598 parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo)
1599 if parts_skipped < 1:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001600 msg = "Expected at most %d other parts with '::' in %r"
1601 raise AddressValueError(msg % (self._HEXTET_COUNT-1, ip_str))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001602 else:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001603 # Otherwise, allocate the entire address to parts_hi. The
1604 # endpoints could still be empty, but _parse_hextet() will check
1605 # for that.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001606 if len(parts) != self._HEXTET_COUNT:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001607 msg = "Exactly %d parts expected without '::' in %r"
1608 raise AddressValueError(msg % (self._HEXTET_COUNT, ip_str))
1609 if not parts[0]:
1610 msg = "Leading ':' only permitted as part of '::' in %r"
1611 raise AddressValueError(msg % ip_str) # ^: requires ^::
1612 if not parts[-1]:
1613 msg = "Trailing ':' only permitted as part of '::' in %r"
1614 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001615 parts_hi = len(parts)
1616 parts_lo = 0
1617 parts_skipped = 0
1618
1619 try:
1620 # Now, parse the hextets into a 128-bit integer.
1621 ip_int = 0
1622 for i in range(parts_hi):
1623 ip_int <<= 16
1624 ip_int |= self._parse_hextet(parts[i])
1625 ip_int <<= 16 * parts_skipped
1626 for i in range(-parts_lo, 0):
1627 ip_int <<= 16
1628 ip_int |= self._parse_hextet(parts[i])
1629 return ip_int
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001630 except ValueError as exc:
1631 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001632
1633 def _parse_hextet(self, hextet_str):
1634 """Convert an IPv6 hextet string into an integer.
1635
1636 Args:
1637 hextet_str: A string, the number to parse.
1638
1639 Returns:
1640 The hextet as an integer.
1641
1642 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001643 ValueError: if the input isn't strictly a hex number from
1644 [0..FFFF].
Nick Coghlandc9b2552012-05-20 21:01:57 +10001645
1646 """
1647 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1648 if not self._HEX_DIGITS.issuperset(hextet_str):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001649 raise ValueError("Only hex digits permitted in %r" % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001650 # We do the length check second, since the invalid character error
1651 # is likely to be more informative for the user
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001652 if len(hextet_str) > 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001653 msg = "At most 4 characters permitted in %r"
1654 raise ValueError(msg % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001655 # Length check means we can skip checking the integer value
1656 return int(hextet_str, 16)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001657
1658 def _compress_hextets(self, hextets):
1659 """Compresses a list of hextets.
1660
1661 Compresses a list of strings, replacing the longest continuous
1662 sequence of "0" in the list with "" and adding empty strings at
1663 the beginning or at the end of the string such that subsequently
1664 calling ":".join(hextets) will produce the compressed version of
1665 the IPv6 address.
1666
1667 Args:
1668 hextets: A list of strings, the hextets to compress.
1669
1670 Returns:
1671 A list of strings.
1672
1673 """
1674 best_doublecolon_start = -1
1675 best_doublecolon_len = 0
1676 doublecolon_start = -1
1677 doublecolon_len = 0
Nick Coghlandb7920b2012-08-20 10:19:12 +10001678 for index, hextet in enumerate(hextets):
1679 if hextet == '0':
Nick Coghlandc9b2552012-05-20 21:01:57 +10001680 doublecolon_len += 1
1681 if doublecolon_start == -1:
1682 # Start of a sequence of zeros.
1683 doublecolon_start = index
1684 if doublecolon_len > best_doublecolon_len:
1685 # This is the longest sequence of zeros so far.
1686 best_doublecolon_len = doublecolon_len
1687 best_doublecolon_start = doublecolon_start
1688 else:
1689 doublecolon_len = 0
1690 doublecolon_start = -1
1691
1692 if best_doublecolon_len > 1:
1693 best_doublecolon_end = (best_doublecolon_start +
1694 best_doublecolon_len)
1695 # For zeros at the end of the address.
1696 if best_doublecolon_end == len(hextets):
1697 hextets += ['']
1698 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1699 # For zeros at the beginning of the address.
1700 if best_doublecolon_start == 0:
1701 hextets = [''] + hextets
1702
1703 return hextets
1704
1705 def _string_from_ip_int(self, ip_int=None):
1706 """Turns a 128-bit integer into hexadecimal notation.
1707
1708 Args:
1709 ip_int: An integer, the IP address.
1710
1711 Returns:
1712 A string, the hexadecimal representation of the address.
1713
1714 Raises:
1715 ValueError: The address is bigger than 128 bits of all ones.
1716
1717 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001718 if ip_int is None:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001719 ip_int = int(self._ip)
1720
1721 if ip_int > self._ALL_ONES:
1722 raise ValueError('IPv6 address is too large')
1723
1724 hex_str = '%032x' % ip_int
Nick Coghlan7319f692012-07-07 21:43:30 +10001725 hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001726
1727 hextets = self._compress_hextets(hextets)
1728 return ':'.join(hextets)
1729
1730 def _explode_shorthand_ip_string(self):
1731 """Expand a shortened IPv6 address.
1732
1733 Args:
1734 ip_str: A string, the IPv6 address.
1735
1736 Returns:
1737 A string, the expanded IPv6 address.
1738
1739 """
1740 if isinstance(self, IPv6Network):
1741 ip_str = str(self.network_address)
1742 elif isinstance(self, IPv6Interface):
1743 ip_str = str(self.ip)
1744 else:
1745 ip_str = str(self)
1746
1747 ip_int = self._ip_int_from_string(ip_str)
Nick Coghlan7319f692012-07-07 21:43:30 +10001748 hex_str = '%032x' % ip_int
1749 parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001750 if isinstance(self, (_BaseNetwork, IPv6Interface)):
Nick Coghlane3ded952012-08-05 22:45:22 +10001751 return '%s/%d' % (':'.join(parts), self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001752 return ':'.join(parts)
1753
1754 @property
1755 def max_prefixlen(self):
1756 return self._max_prefixlen
1757
1758 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001759 def version(self):
1760 return self._version
1761
Nick Coghlandc9b2552012-05-20 21:01:57 +10001762
1763class IPv6Address(_BaseV6, _BaseAddress):
1764
Sandro Tosib95c6342012-05-23 23:17:22 +02001765 """Represent and manipulate single IPv6 Addresses."""
Nick Coghlandc9b2552012-05-20 21:01:57 +10001766
1767 def __init__(self, address):
1768 """Instantiate a new IPv6 address object.
1769
1770 Args:
1771 address: A string or integer representing the IP
1772
1773 Additionally, an integer can be passed, so
1774 IPv6Address('2001:db8::') ==
1775 IPv6Address(42540766411282592856903984951653826560)
1776 or, more generally
1777 IPv6Address(int(IPv6Address('2001:db8::'))) ==
1778 IPv6Address('2001:db8::')
1779
1780 Raises:
1781 AddressValueError: If address isn't a valid IPv6 address.
1782
1783 """
1784 _BaseAddress.__init__(self, address)
1785 _BaseV6.__init__(self, address)
1786
1787 # Efficient constructor from integer.
1788 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001789 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001790 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001791 return
1792
1793 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001794 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001795 self._check_packed_address(address, 16)
Nick Coghlandb7920b2012-08-20 10:19:12 +10001796 self._ip = int.from_bytes(address, 'big')
Nick Coghlandc9b2552012-05-20 21:01:57 +10001797 return
1798
1799 # Assume input argument to be string or any object representation
1800 # which converts into a formatted IP string.
1801 addr_str = str(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001802 self._ip = self._ip_int_from_string(addr_str)
1803
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001804 @property
1805 def packed(self):
1806 """The binary representation of this address."""
1807 return v6_int_to_packed(self._ip)
1808
Nick Coghlan730f67f2012-08-05 22:02:18 +10001809 @property
1810 def is_multicast(self):
1811 """Test if the address is reserved for multicast use.
1812
1813 Returns:
1814 A boolean, True if the address is a multicast address.
1815 See RFC 2373 2.7 for details.
1816
1817 """
1818 multicast_network = IPv6Network('ff00::/8')
1819 return self in multicast_network
1820
1821 @property
1822 def is_reserved(self):
1823 """Test if the address is otherwise IETF reserved.
1824
1825 Returns:
1826 A boolean, True if the address is within one of the
1827 reserved IPv6 Network ranges.
1828
1829 """
1830 reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'),
1831 IPv6Network('200::/7'), IPv6Network('400::/6'),
1832 IPv6Network('800::/5'), IPv6Network('1000::/4'),
1833 IPv6Network('4000::/3'), IPv6Network('6000::/3'),
1834 IPv6Network('8000::/3'), IPv6Network('A000::/3'),
1835 IPv6Network('C000::/3'), IPv6Network('E000::/4'),
1836 IPv6Network('F000::/5'), IPv6Network('F800::/6'),
1837 IPv6Network('FE00::/9')]
1838
1839 return any(self in x for x in reserved_networks)
1840
1841 @property
1842 def is_link_local(self):
1843 """Test if the address is reserved for link-local.
1844
1845 Returns:
1846 A boolean, True if the address is reserved per RFC 4291.
1847
1848 """
1849 linklocal_network = IPv6Network('fe80::/10')
1850 return self in linklocal_network
1851
1852 @property
1853 def is_site_local(self):
1854 """Test if the address is reserved for site-local.
1855
1856 Note that the site-local address space has been deprecated by RFC 3879.
1857 Use is_private to test if this address is in the space of unique local
1858 addresses as defined by RFC 4193.
1859
1860 Returns:
1861 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1862
1863 """
1864 sitelocal_network = IPv6Network('fec0::/10')
1865 return self in sitelocal_network
1866
1867 @property
Peter Moodybe9c1b12013-10-22 12:36:21 -07001868 @functools.lru_cache()
Nick Coghlan730f67f2012-08-05 22:02:18 +10001869 def is_private(self):
1870 """Test if this address is allocated for private networks.
1871
1872 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001873 A boolean, True if the address is reserved per
1874 iana-ipv6-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001875
1876 """
Peter Moody22c31762013-10-21 13:58:06 -07001877 return (self in IPv6Network('::1/128') or
1878 self in IPv6Network('::/128') or
1879 self in IPv6Network('::ffff:0:0/96') or
1880 self in IPv6Network('100::/64') or
1881 self in IPv6Network('2001::/23') or
1882 self in IPv6Network('2001:2::/48') or
1883 self in IPv6Network('2001:db8::/32') or
1884 self in IPv6Network('2001:10::/28') or
1885 self in IPv6Network('fc00::/7') or
1886 self in IPv6Network('fe80::/10'))
1887
1888 @property
1889 def is_global(self):
1890 """Test if this address is allocated for public networks.
1891
1892 Returns:
1893 A boolean, true if the address is not reserved per
1894 iana-ipv6-special-registry.
1895
1896 """
1897 return not self.is_private
Nick Coghlan730f67f2012-08-05 22:02:18 +10001898
1899 @property
1900 def is_unspecified(self):
1901 """Test if the address is unspecified.
1902
1903 Returns:
1904 A boolean, True if this is the unspecified address as defined in
1905 RFC 2373 2.5.2.
1906
1907 """
1908 return self._ip == 0
1909
1910 @property
1911 def is_loopback(self):
1912 """Test if the address is a loopback address.
1913
1914 Returns:
1915 A boolean, True if the address is a loopback address as defined in
1916 RFC 2373 2.5.3.
1917
1918 """
1919 return self._ip == 1
1920
1921 @property
1922 def ipv4_mapped(self):
1923 """Return the IPv4 mapped address.
1924
1925 Returns:
1926 If the IPv6 address is a v4 mapped address, return the
1927 IPv4 mapped address. Return None otherwise.
1928
1929 """
1930 if (self._ip >> 32) != 0xFFFF:
1931 return None
1932 return IPv4Address(self._ip & 0xFFFFFFFF)
1933
1934 @property
1935 def teredo(self):
1936 """Tuple of embedded teredo IPs.
1937
1938 Returns:
1939 Tuple of the (server, client) IPs or None if the address
1940 doesn't appear to be a teredo address (doesn't start with
1941 2001::/32)
1942
1943 """
1944 if (self._ip >> 96) != 0x20010000:
1945 return None
1946 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
1947 IPv4Address(~self._ip & 0xFFFFFFFF))
1948
1949 @property
1950 def sixtofour(self):
1951 """Return the IPv4 6to4 embedded address.
1952
1953 Returns:
1954 The IPv4 6to4-embedded address if present or None if the
1955 address doesn't appear to contain a 6to4 embedded address.
1956
1957 """
1958 if (self._ip >> 112) != 0x2002:
1959 return None
1960 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
1961
Nick Coghlandc9b2552012-05-20 21:01:57 +10001962
1963class IPv6Interface(IPv6Address):
1964
1965 def __init__(self, address):
1966 if isinstance(address, (bytes, int)):
1967 IPv6Address.__init__(self, address)
1968 self.network = IPv6Network(self._ip)
1969 self._prefixlen = self._max_prefixlen
1970 return
1971
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001972 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001973 IPv6Address.__init__(self, addr[0])
1974 self.network = IPv6Network(address, strict=False)
1975 self.netmask = self.network.netmask
1976 self._prefixlen = self.network._prefixlen
1977 self.hostmask = self.network.hostmask
1978
Nick Coghlandc9b2552012-05-20 21:01:57 +10001979 def __str__(self):
1980 return '%s/%d' % (self._string_from_ip_int(self._ip),
1981 self.network.prefixlen)
1982
1983 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001984 address_equal = IPv6Address.__eq__(self, other)
1985 if not address_equal or address_equal is NotImplemented:
1986 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001987 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001988 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001989 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001990 # An interface with an associated network is NOT the
1991 # same as an unassociated address. That's why the hash
1992 # takes the extra info into account.
1993 return False
1994
1995 def __lt__(self, other):
1996 address_less = IPv6Address.__lt__(self, other)
1997 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001998 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001999 try:
2000 return self.network < other.network
2001 except AttributeError:
2002 # We *do* allow addresses and interfaces to be sorted. The
2003 # unassociated address is considered less than all interfaces.
2004 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10002005
2006 def __hash__(self):
2007 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
2008
2009 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10002010 def ip(self):
2011 return IPv6Address(self._ip)
2012
2013 @property
2014 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10002015 return '%s/%s' % (self._string_from_ip_int(self._ip),
2016 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002017
2018 @property
2019 def with_netmask(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10002020 return '%s/%s' % (self._string_from_ip_int(self._ip),
2021 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02002022
Nick Coghlandc9b2552012-05-20 21:01:57 +10002023 @property
2024 def with_hostmask(self):
2025 return '%s/%s' % (self._string_from_ip_int(self._ip),
2026 self.hostmask)
2027
Nick Coghlan730f67f2012-08-05 22:02:18 +10002028 @property
2029 def is_unspecified(self):
2030 return self._ip == 0 and self.network.is_unspecified
2031
2032 @property
2033 def is_loopback(self):
2034 return self._ip == 1 and self.network.is_loopback
2035
Nick Coghlandc9b2552012-05-20 21:01:57 +10002036
2037class IPv6Network(_BaseV6, _BaseNetwork):
2038
2039 """This class represents and manipulates 128-bit IPv6 networks.
2040
2041 Attributes: [examples for IPv6('2001:db8::1000/124')]
2042 .network_address: IPv6Address('2001:db8::1000')
2043 .hostmask: IPv6Address('::f')
2044 .broadcast_address: IPv6Address('2001:db8::100f')
2045 .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
2046 .prefixlen: 124
2047
2048 """
2049
Nick Coghlan51c30672012-05-27 00:25:58 +10002050 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10002051 _address_class = IPv6Address
2052
Nick Coghlandc9b2552012-05-20 21:01:57 +10002053 def __init__(self, address, strict=True):
2054 """Instantiate a new IPv6 Network object.
2055
2056 Args:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02002057 address: A string or integer representing the IPv6 network or the
2058 IP and prefix/netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +10002059 '2001:db8::/128'
2060 '2001:db8:0000:0000:0000:0000:0000:0000/128'
2061 '2001:db8::'
2062 are all functionally the same in IPv6. That is to say,
2063 failing to provide a subnetmask will create an object with
2064 a mask of /128.
2065
2066 Additionally, an integer can be passed, so
2067 IPv6Network('2001:db8::') ==
2068 IPv6Network(42540766411282592856903984951653826560)
2069 or, more generally
2070 IPv6Network(int(IPv6Network('2001:db8::'))) ==
2071 IPv6Network('2001:db8::')
2072
2073 strict: A boolean. If true, ensure that we have been passed
2074 A true network address, eg, 2001:db8::1000/124 and not an
2075 IP address on a network, eg, 2001:db8::1/124.
2076
2077 Raises:
2078 AddressValueError: If address isn't a valid IPv6 address.
2079 NetmaskValueError: If the netmask isn't valid for
2080 an IPv6 address.
2081 ValueError: If strict was True and a network address was not
2082 supplied.
2083
2084 """
2085 _BaseV6.__init__(self, address)
2086 _BaseNetwork.__init__(self, address)
2087
2088 # Efficient constructor from integer.
2089 if isinstance(address, int):
Nick Coghlandc9b2552012-05-20 21:01:57 +10002090 self.network_address = IPv6Address(address)
2091 self._prefixlen = self._max_prefixlen
2092 self.netmask = IPv6Address(self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002093 return
2094
2095 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10002096 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10002097 self.network_address = IPv6Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002098 self._prefixlen = self._max_prefixlen
2099 self.netmask = IPv6Address(self._ALL_ONES)
Hynek Schlawacked36b2e2012-06-08 15:21:21 +02002100 return
Nick Coghlandc9b2552012-05-20 21:01:57 +10002101
2102 # Assume input argument to be string or any object representation
2103 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002104 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002105
2106 self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))
2107
2108 if len(addr) == 2:
Nick Coghlan932346f2014-02-08 23:17:36 +10002109 # This may raise NetmaskValueError
2110 self._prefixlen = self._prefix_from_prefix_string(addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10002111 else:
2112 self._prefixlen = self._max_prefixlen
2113
2114 self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen))
2115 if strict:
2116 if (IPv6Address(int(self.network_address) & int(self.netmask)) !=
2117 self.network_address):
Nick Coghlan912238e2012-07-07 13:34:50 +10002118 raise ValueError('%s has host bits set' % self)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002119 self.network_address = IPv6Address(int(self.network_address) &
2120 int(self.netmask))
2121
2122 if self._prefixlen == (self._max_prefixlen - 1):
2123 self.hosts = self.__iter__
2124
Peter Moody1243c7d2014-03-11 09:55:46 -07002125 def hosts(self):
2126 """Generate Iterator over usable hosts in a network.
2127
2128 This is like __iter__ except it doesn't return the
2129 Subnet-Router anycast address.
2130
2131 """
2132 network = int(self.network_address)
2133 broadcast = int(self.broadcast_address)
2134 for x in range(network + 1, broadcast + 1):
2135 yield self._address_class(x)
2136
Nick Coghlan730f67f2012-08-05 22:02:18 +10002137 @property
2138 def is_site_local(self):
2139 """Test if the address is reserved for site-local.
2140
2141 Note that the site-local address space has been deprecated by RFC 3879.
2142 Use is_private to test if this address is in the space of unique local
2143 addresses as defined by RFC 4193.
2144
2145 Returns:
2146 A boolean, True if the address is reserved per RFC 3513 2.5.6.
2147
2148 """
2149 return (self.network_address.is_site_local and
2150 self.broadcast_address.is_site_local)