blob: ecf3f4491cf482b2a95472712fffccc4afa79da3 [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
Nick Coghlan3008ec02012-07-08 00:45:33 +1000391class _TotalOrderingMixin:
392 # Helper that derives the other comparison operations from
393 # __lt__ and __eq__
Nick Coghlan297b1432012-07-08 17:11:04 +1000394 # We avoid functools.total_ordering because it doesn't handle
395 # NotImplemented correctly yet (http://bugs.python.org/issue10042)
Nick Coghlan3008ec02012-07-08 00:45:33 +1000396 def __eq__(self, other):
397 raise NotImplementedError
398 def __ne__(self, other):
399 equal = self.__eq__(other)
400 if equal is NotImplemented:
401 return NotImplemented
402 return not equal
403 def __lt__(self, other):
404 raise NotImplementedError
405 def __le__(self, other):
406 less = self.__lt__(other)
407 if less is NotImplemented or not less:
408 return self.__eq__(other)
409 return less
410 def __gt__(self, other):
411 less = self.__lt__(other)
412 if less is NotImplemented:
413 return NotImplemented
414 equal = self.__eq__(other)
415 if equal is NotImplemented:
416 return NotImplemented
417 return not (less or equal)
418 def __ge__(self, other):
419 less = self.__lt__(other)
420 if less is NotImplemented:
421 return NotImplemented
422 return not less
423
424class _IPAddressBase(_TotalOrderingMixin):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000425
426 """The mother class."""
427
428 @property
429 def exploded(self):
430 """Return the longhand version of the IP address as a string."""
431 return self._explode_shorthand_ip_string()
432
433 @property
434 def compressed(self):
435 """Return the shorthand version of the IP address as a string."""
436 return str(self)
437
Nick Coghland9722652012-06-17 16:33:00 +1000438 @property
439 def version(self):
440 msg = '%200s has no version specified' % (type(self),)
441 raise NotImplementedError(msg)
442
Nick Coghlan297b1432012-07-08 17:11:04 +1000443 def _check_int_address(self, address):
444 if address < 0:
445 msg = "%d (< 0) is not permitted as an IPv%d address"
446 raise AddressValueError(msg % (address, self._version))
447 if address > self._ALL_ONES:
448 msg = "%d (>= 2**%d) is not permitted as an IPv%d address"
449 raise AddressValueError(msg % (address, self._max_prefixlen,
450 self._version))
451
452 def _check_packed_address(self, address, expected_len):
453 address_len = len(address)
454 if address_len != expected_len:
455 msg = "%r (len %d != %d) is not permitted as an IPv%d address"
456 raise AddressValueError(msg % (address, address_len,
457 expected_len, self._version))
458
Nick Coghlan932346f2014-02-08 23:17:36 +1000459 def _ip_int_from_prefix(self, prefixlen):
460 """Turn the prefix length into a bitwise netmask
Nick Coghlandc9b2552012-05-20 21:01:57 +1000461
462 Args:
463 prefixlen: An integer, the prefix length.
464
465 Returns:
466 An integer.
467
468 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000469 return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen)
470
Nick Coghlan932346f2014-02-08 23:17:36 +1000471 def _prefix_from_ip_int(self, ip_int):
472 """Return prefix length from the bitwise netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000473
474 Args:
Nick Coghlan932346f2014-02-08 23:17:36 +1000475 ip_int: An integer, the netmask in axpanded bitwise format
Nick Coghlandc9b2552012-05-20 21:01:57 +1000476
477 Returns:
478 An integer, the prefix length.
479
Nick Coghlan932346f2014-02-08 23:17:36 +1000480 Raises:
481 ValueError: If the input intermingles zeroes & ones
Nick Coghlandc9b2552012-05-20 21:01:57 +1000482 """
Nick Coghlan932346f2014-02-08 23:17:36 +1000483 trailing_zeroes = _count_righthand_zero_bits(ip_int,
484 self._max_prefixlen)
485 prefixlen = self._max_prefixlen - trailing_zeroes
486 leading_ones = ip_int >> trailing_zeroes
487 all_ones = (1 << prefixlen) - 1
488 if leading_ones != all_ones:
489 byteslen = self._max_prefixlen // 8
490 details = ip_int.to_bytes(byteslen, 'big')
491 msg = 'Netmask pattern %r mixes zeroes & ones'
492 raise ValueError(msg % details)
493 return prefixlen
Nick Coghlandc9b2552012-05-20 21:01:57 +1000494
Nick Coghlan932346f2014-02-08 23:17:36 +1000495 def _report_invalid_netmask(self, netmask_str):
496 msg = '%r is not a valid netmask' % netmask_str
497 raise NetmaskValueError(msg) from None
498
499 def _prefix_from_prefix_string(self, prefixlen_str):
500 """Return prefix length from a numeric string
Nick Coghlandc9b2552012-05-20 21:01:57 +1000501
502 Args:
Nick Coghlan932346f2014-02-08 23:17:36 +1000503 prefixlen_str: The string to be converted
Nick Coghlandc9b2552012-05-20 21:01:57 +1000504
505 Returns:
Nick Coghlan932346f2014-02-08 23:17:36 +1000506 An integer, the prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000507
Nick Coghlan932346f2014-02-08 23:17:36 +1000508 Raises:
509 NetmaskValueError: If the input is not a valid netmask
Nick Coghlandc9b2552012-05-20 21:01:57 +1000510 """
Nick Coghlan932346f2014-02-08 23:17:36 +1000511 # int allows a leading +/- as well as surrounding whitespace,
512 # so we ensure that isn't the case
513 if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
514 self._report_invalid_netmask(prefixlen_str)
515 try:
516 prefixlen = int(prefixlen_str)
517 except ValueError:
518 self._report_invalid_netmask(prefixlen_str)
519 if not (0 <= prefixlen <= self._max_prefixlen):
520 self._report_invalid_netmask(prefixlen_str)
521 return prefixlen
522
523 def _prefix_from_ip_string(self, ip_str):
524 """Turn a netmask/hostmask string into a prefix length
525
526 Args:
527 ip_str: The netmask/hostmask to be converted
528
529 Returns:
530 An integer, the prefix length.
531
532 Raises:
533 NetmaskValueError: If the input is not a valid netmask/hostmask
534 """
535 # Parse the netmask/hostmask like an IP address.
536 try:
537 ip_int = self._ip_int_from_string(ip_str)
538 except AddressValueError:
539 self._report_invalid_netmask(ip_str)
540
541 # Try matching a netmask (this would be /1*0*/ as a bitwise regexp).
542 # Note that the two ambiguous cases (all-ones and all-zeroes) are
543 # treated as netmasks.
544 try:
545 return self._prefix_from_ip_int(ip_int)
546 except ValueError:
547 pass
548
549 # Invert the bits, and try matching a /0+1+/ hostmask instead.
550 ip_int ^= self._ALL_ONES
551 try:
552 return self._prefix_from_ip_int(ip_int)
553 except ValueError:
554 self._report_invalid_netmask(ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000555
Nick Coghlan730f67f2012-08-05 22:02:18 +1000556
Nick Coghlandc9b2552012-05-20 21:01:57 +1000557class _BaseAddress(_IPAddressBase):
558
559 """A generic IP object.
560
561 This IP class contains the version independent methods which are
562 used by single IP addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000563 """
564
565 def __init__(self, address):
566 if (not isinstance(address, bytes)
567 and '/' in str(address)):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000568 raise AddressValueError("Unexpected '/' in %r" % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000569
Nick Coghlandc9b2552012-05-20 21:01:57 +1000570 def __int__(self):
571 return self._ip
572
Nick Coghlandc9b2552012-05-20 21:01:57 +1000573 def __eq__(self, other):
574 try:
575 return (self._ip == other._ip
576 and self._version == other._version)
577 except AttributeError:
578 return NotImplemented
579
Nick Coghlandc9b2552012-05-20 21:01:57 +1000580 def __lt__(self, other):
581 if self._version != other._version:
582 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000583 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000584 if not isinstance(other, _BaseAddress):
585 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000586 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000587 if self._ip != other._ip:
588 return self._ip < other._ip
589 return False
590
Nick Coghlandc9b2552012-05-20 21:01:57 +1000591 # Shorthand for Integer addition and subtraction. This is not
592 # meant to ever support addition/subtraction of addresses.
593 def __add__(self, other):
594 if not isinstance(other, int):
595 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000596 return self.__class__(int(self) + other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000597
598 def __sub__(self, other):
599 if not isinstance(other, int):
600 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000601 return self.__class__(int(self) - other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000602
603 def __repr__(self):
604 return '%s(%r)' % (self.__class__.__name__, str(self))
605
606 def __str__(self):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200607 return str(self._string_from_ip_int(self._ip))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000608
609 def __hash__(self):
610 return hash(hex(int(self._ip)))
611
612 def _get_address_key(self):
613 return (self._version, self)
614
Nick Coghlandc9b2552012-05-20 21:01:57 +1000615
616class _BaseNetwork(_IPAddressBase):
617
Nick Coghlan51c30672012-05-27 00:25:58 +1000618 """A generic IP network object.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000619
620 This IP class contains the version independent methods which are
621 used by networks.
622
623 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000624 def __init__(self, address):
625 self._cache = {}
626
Nick Coghlandc9b2552012-05-20 21:01:57 +1000627 def __repr__(self):
628 return '%s(%r)' % (self.__class__.__name__, str(self))
629
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200630 def __str__(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000631 return '%s/%d' % (self.network_address, self.prefixlen)
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200632
Nick Coghlandc9b2552012-05-20 21:01:57 +1000633 def hosts(self):
634 """Generate Iterator over usable hosts in a network.
635
Sandro Tosib95c6342012-05-23 23:17:22 +0200636 This is like __iter__ except it doesn't return the network
637 or broadcast addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000638
639 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000640 network = int(self.network_address)
641 broadcast = int(self.broadcast_address)
642 for x in range(network + 1, broadcast):
643 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000644
645 def __iter__(self):
Nick Coghlan7319f692012-07-07 21:43:30 +1000646 network = int(self.network_address)
647 broadcast = int(self.broadcast_address)
648 for x in range(network, broadcast + 1):
649 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000650
651 def __getitem__(self, n):
652 network = int(self.network_address)
653 broadcast = int(self.broadcast_address)
654 if n >= 0:
655 if network + n > broadcast:
656 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000657 return self._address_class(network + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000658 else:
659 n += 1
660 if broadcast + n < network:
661 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000662 return self._address_class(broadcast + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000663
664 def __lt__(self, other):
665 if self._version != other._version:
666 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000667 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000668 if not isinstance(other, _BaseNetwork):
669 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000670 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000671 if self.network_address != other.network_address:
672 return self.network_address < other.network_address
673 if self.netmask != other.netmask:
674 return self.netmask < other.netmask
675 return False
676
Nick Coghlandc9b2552012-05-20 21:01:57 +1000677 def __eq__(self, other):
Nick Coghlan9a9c28c2012-07-07 23:05:59 +1000678 try:
679 return (self._version == other._version and
680 self.network_address == other.network_address and
681 int(self.netmask) == int(other.netmask))
682 except AttributeError:
683 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000684
Nick Coghlandc9b2552012-05-20 21:01:57 +1000685 def __hash__(self):
686 return hash(int(self.network_address) ^ int(self.netmask))
687
688 def __contains__(self, other):
689 # always false if one is v4 and the other is v6.
690 if self._version != other._version:
691 return False
692 # dealing with another network.
693 if isinstance(other, _BaseNetwork):
694 return False
695 # dealing with another address
696 else:
697 # address
698 return (int(self.network_address) <= int(other._ip) <=
699 int(self.broadcast_address))
700
701 def overlaps(self, other):
702 """Tell if self is partly contained in other."""
703 return self.network_address in other or (
704 self.broadcast_address in other or (
705 other.network_address in self or (
706 other.broadcast_address in self)))
707
708 @property
709 def broadcast_address(self):
710 x = self._cache.get('broadcast_address')
711 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000712 x = self._address_class(int(self.network_address) |
713 int(self.hostmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000714 self._cache['broadcast_address'] = x
715 return x
716
717 @property
718 def hostmask(self):
719 x = self._cache.get('hostmask')
720 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000721 x = self._address_class(int(self.netmask) ^ self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000722 self._cache['hostmask'] = x
723 return x
724
725 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000726 def with_prefixlen(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000727 return '%s/%d' % (self.network_address, self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000728
729 @property
730 def with_netmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000731 return '%s/%s' % (self.network_address, self.netmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000732
733 @property
734 def with_hostmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000735 return '%s/%s' % (self.network_address, self.hostmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000736
737 @property
738 def num_addresses(self):
739 """Number of hosts in the current subnet."""
740 return int(self.broadcast_address) - int(self.network_address) + 1
741
742 @property
Nick Coghlan51c30672012-05-27 00:25:58 +1000743 def _address_class(self):
Nick Coghland9722652012-06-17 16:33:00 +1000744 # Returning bare address objects (rather than interfaces) allows for
745 # more consistent behaviour across the network address, broadcast
746 # address and individual host addresses.
747 msg = '%200s has no associated address class' % (type(self),)
748 raise NotImplementedError(msg)
Nick Coghlan51c30672012-05-27 00:25:58 +1000749
750 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000751 def prefixlen(self):
752 return self._prefixlen
753
754 def address_exclude(self, other):
755 """Remove an address from a larger block.
756
757 For example:
758
759 addr1 = ip_network('192.0.2.0/28')
760 addr2 = ip_network('192.0.2.1/32')
761 addr1.address_exclude(addr2) =
762 [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
763 IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
764
765 or IPv6:
766
767 addr1 = ip_network('2001:db8::1/32')
768 addr2 = ip_network('2001:db8::1/128')
769 addr1.address_exclude(addr2) =
770 [ip_network('2001:db8::1/128'),
771 ip_network('2001:db8::2/127'),
772 ip_network('2001:db8::4/126'),
773 ip_network('2001:db8::8/125'),
774 ...
775 ip_network('2001:db8:8000::/33')]
776
777 Args:
778 other: An IPv4Network or IPv6Network object of the same type.
779
780 Returns:
Ezio Melotti3f5db392013-01-27 06:20:14 +0200781 An iterator of the IPv(4|6)Network objects which is self
Nick Coghlandc9b2552012-05-20 21:01:57 +1000782 minus other.
783
784 Raises:
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300785 TypeError: If self and other are of differing address
Nick Coghlandc9b2552012-05-20 21:01:57 +1000786 versions, or if other is not a network object.
787 ValueError: If other is not completely contained by self.
788
789 """
790 if not self._version == other._version:
791 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000792 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000793
794 if not isinstance(other, _BaseNetwork):
Nick Coghlan912238e2012-07-07 13:34:50 +1000795 raise TypeError("%s is not a network object" % other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000796
797 if not (other.network_address >= self.network_address and
798 other.broadcast_address <= self.broadcast_address):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200799 raise ValueError('%s not contained in %s' % (other, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000800 if other == self:
801 raise StopIteration
802
Nick Coghlandc9b2552012-05-20 21:01:57 +1000803 # Make sure we're comparing the network of other.
Nick Coghlan912238e2012-07-07 13:34:50 +1000804 other = other.__class__('%s/%s' % (other.network_address,
805 other.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000806
807 s1, s2 = self.subnets()
808 while s1 != other and s2 != other:
809 if (other.network_address >= s1.network_address and
810 other.broadcast_address <= s1.broadcast_address):
811 yield s2
812 s1, s2 = s1.subnets()
813 elif (other.network_address >= s2.network_address and
814 other.broadcast_address <= s2.broadcast_address):
815 yield s1
816 s1, s2 = s2.subnets()
817 else:
818 # If we got here, there's a bug somewhere.
819 raise AssertionError('Error performing exclusion: '
820 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000821 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000822 if s1 == other:
823 yield s2
824 elif s2 == other:
825 yield s1
826 else:
827 # If we got here, there's a bug somewhere.
828 raise AssertionError('Error performing exclusion: '
829 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000830 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000831
832 def compare_networks(self, other):
833 """Compare two IP objects.
834
835 This is only concerned about the comparison of the integer
836 representation of the network addresses. This means that the
837 host bits aren't considered at all in this method. If you want
838 to compare host bits, you can easily enough do a
839 'HostA._ip < HostB._ip'
840
841 Args:
842 other: An IP object.
843
844 Returns:
845 If the IP versions of self and other are the same, returns:
846
847 -1 if self < other:
848 eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
849 IPv6Network('2001:db8::1000/124') <
850 IPv6Network('2001:db8::2000/124')
851 0 if self == other
852 eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
853 IPv6Network('2001:db8::1000/124') ==
854 IPv6Network('2001:db8::1000/124')
855 1 if self > other
856 eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
857 IPv6Network('2001:db8::2000/124') >
858 IPv6Network('2001:db8::1000/124')
859
860 Raises:
861 TypeError if the IP versions are different.
862
863 """
864 # does this need to raise a ValueError?
865 if self._version != other._version:
866 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000867 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000868 # self._version == other._version below here:
869 if self.network_address < other.network_address:
870 return -1
871 if self.network_address > other.network_address:
872 return 1
873 # self.network_address == other.network_address below here:
874 if self.netmask < other.netmask:
875 return -1
876 if self.netmask > other.netmask:
877 return 1
878 return 0
879
880 def _get_networks_key(self):
881 """Network-only key function.
882
883 Returns an object that identifies this address' network and
884 netmask. This function is a suitable "key" argument for sorted()
885 and list.sort().
886
887 """
888 return (self._version, self.network_address, self.netmask)
889
890 def subnets(self, prefixlen_diff=1, new_prefix=None):
891 """The subnets which join to make the current subnet.
892
893 In the case that self contains only one IP
894 (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
895 for IPv6), yield an iterator with just ourself.
896
897 Args:
898 prefixlen_diff: An integer, the amount the prefix length
899 should be increased by. This should not be set if
900 new_prefix is also set.
901 new_prefix: The desired new prefix length. This must be a
902 larger number (smaller prefix) than the existing prefix.
903 This should not be set if prefixlen_diff is also set.
904
905 Returns:
906 An iterator of IPv(4|6) objects.
907
908 Raises:
909 ValueError: The prefixlen_diff is too small or too large.
910 OR
911 prefixlen_diff and new_prefix are both set or new_prefix
912 is a smaller number than the current prefix (smaller
913 number means a larger network)
914
915 """
916 if self._prefixlen == self._max_prefixlen:
917 yield self
918 return
919
920 if new_prefix is not None:
921 if new_prefix < self._prefixlen:
922 raise ValueError('new prefix must be longer')
923 if prefixlen_diff != 1:
924 raise ValueError('cannot set prefixlen_diff and new_prefix')
925 prefixlen_diff = new_prefix - self._prefixlen
926
927 if prefixlen_diff < 0:
928 raise ValueError('prefix length diff must be > 0')
929 new_prefixlen = self._prefixlen + prefixlen_diff
930
Nick Coghlan932346f2014-02-08 23:17:36 +1000931 if new_prefixlen > self._max_prefixlen:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000932 raise ValueError(
933 'prefix length diff %d is invalid for netblock %s' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000934 new_prefixlen, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000935
Nick Coghlan51c30672012-05-27 00:25:58 +1000936 first = self.__class__('%s/%s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000937 (self.network_address,
938 self._prefixlen + prefixlen_diff))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000939
940 yield first
941 current = first
942 while True:
943 broadcast = current.broadcast_address
944 if broadcast == self.broadcast_address:
945 return
Nick Coghlan51c30672012-05-27 00:25:58 +1000946 new_addr = self._address_class(int(broadcast) + 1)
Nick Coghlan912238e2012-07-07 13:34:50 +1000947 current = self.__class__('%s/%s' % (new_addr,
948 new_prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000949
950 yield current
951
Nick Coghlandc9b2552012-05-20 21:01:57 +1000952 def supernet(self, prefixlen_diff=1, new_prefix=None):
953 """The supernet containing the current network.
954
955 Args:
956 prefixlen_diff: An integer, the amount the prefix length of
957 the network should be decreased by. For example, given a
958 /24 network and a prefixlen_diff of 3, a supernet with a
959 /21 netmask is returned.
960
961 Returns:
962 An IPv4 network object.
963
964 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200965 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
966 a negative prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000967 OR
968 If prefixlen_diff and new_prefix are both set or new_prefix is a
969 larger number than the current prefix (larger number means a
970 smaller network)
971
972 """
973 if self._prefixlen == 0:
974 return self
975
976 if new_prefix is not None:
977 if new_prefix > self._prefixlen:
978 raise ValueError('new prefix must be shorter')
979 if prefixlen_diff != 1:
980 raise ValueError('cannot set prefixlen_diff and new_prefix')
981 prefixlen_diff = self._prefixlen - new_prefix
982
Nick Coghlandc9b2552012-05-20 21:01:57 +1000983 if self.prefixlen - prefixlen_diff < 0:
984 raise ValueError(
985 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
986 (self.prefixlen, prefixlen_diff))
987 # TODO (pmoody): optimize this.
Nick Coghlan912238e2012-07-07 13:34:50 +1000988 t = self.__class__('%s/%d' % (self.network_address,
Nick Coghlan51c30672012-05-27 00:25:58 +1000989 self.prefixlen - prefixlen_diff),
990 strict=False)
Nick Coghlan912238e2012-07-07 13:34:50 +1000991 return t.__class__('%s/%d' % (t.network_address, t.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000992
Nick Coghlan730f67f2012-08-05 22:02:18 +1000993 @property
994 def is_multicast(self):
995 """Test if the address is reserved for multicast use.
996
997 Returns:
998 A boolean, True if the address is a multicast address.
999 See RFC 2373 2.7 for details.
1000
1001 """
1002 return (self.network_address.is_multicast and
1003 self.broadcast_address.is_multicast)
1004
1005 @property
1006 def is_reserved(self):
1007 """Test if the address is otherwise IETF reserved.
1008
1009 Returns:
1010 A boolean, True if the address is within one of the
1011 reserved IPv6 Network ranges.
1012
1013 """
1014 return (self.network_address.is_reserved and
1015 self.broadcast_address.is_reserved)
1016
1017 @property
1018 def is_link_local(self):
1019 """Test if the address is reserved for link-local.
1020
1021 Returns:
1022 A boolean, True if the address is reserved per RFC 4291.
1023
1024 """
1025 return (self.network_address.is_link_local and
1026 self.broadcast_address.is_link_local)
1027
1028 @property
1029 def is_private(self):
1030 """Test if this address is allocated for private networks.
1031
1032 Returns:
1033 A boolean, True if the address is reserved per RFC 4193.
1034
1035 """
1036 return (self.network_address.is_private and
1037 self.broadcast_address.is_private)
1038
1039 @property
1040 def is_unspecified(self):
1041 """Test if the address is unspecified.
1042
1043 Returns:
1044 A boolean, True if this is the unspecified address as defined in
1045 RFC 2373 2.5.2.
1046
1047 """
1048 return (self.network_address.is_unspecified and
1049 self.broadcast_address.is_unspecified)
1050
1051 @property
1052 def is_loopback(self):
1053 """Test if the address is a loopback address.
1054
1055 Returns:
1056 A boolean, True if the address is a loopback address as defined in
1057 RFC 2373 2.5.3.
1058
1059 """
1060 return (self.network_address.is_loopback and
1061 self.broadcast_address.is_loopback)
1062
Nick Coghlandc9b2552012-05-20 21:01:57 +10001063
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001064class _BaseV4:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001065
1066 """Base IPv4 object.
1067
1068 The following methods are used by IPv4 objects in both single IP
1069 addresses and networks.
1070
1071 """
1072
1073 # Equivalent to 255.255.255.255 or 32 bits of 1's.
1074 _ALL_ONES = (2**IPV4LENGTH) - 1
1075 _DECIMAL_DIGITS = frozenset('0123456789')
1076
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001077 # the valid octets for host and netmasks. only useful for IPv4.
Nick Coghlan7319f692012-07-07 21:43:30 +10001078 _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0))
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001079
Nick Coghlandc9b2552012-05-20 21:01:57 +10001080 def __init__(self, address):
1081 self._version = 4
1082 self._max_prefixlen = IPV4LENGTH
1083
1084 def _explode_shorthand_ip_string(self):
1085 return str(self)
1086
1087 def _ip_int_from_string(self, ip_str):
1088 """Turn the given IP string into an integer for comparison.
1089
1090 Args:
1091 ip_str: A string, the IP ip_str.
1092
1093 Returns:
1094 The IP ip_str as an integer.
1095
1096 Raises:
1097 AddressValueError: if ip_str isn't a valid IPv4 Address.
1098
1099 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001100 if not ip_str:
1101 raise AddressValueError('Address cannot be empty')
1102
Nick Coghlandc9b2552012-05-20 21:01:57 +10001103 octets = ip_str.split('.')
1104 if len(octets) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001105 raise AddressValueError("Expected 4 octets in %r" % ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001106
Nick Coghlan7319f692012-07-07 21:43:30 +10001107 try:
1108 return int.from_bytes(map(self._parse_octet, octets), 'big')
1109 except ValueError as exc:
1110 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001111
1112 def _parse_octet(self, octet_str):
1113 """Convert a decimal octet into an integer.
1114
1115 Args:
1116 octet_str: A string, the number to parse.
1117
1118 Returns:
1119 The octet as an integer.
1120
1121 Raises:
1122 ValueError: if the octet isn't strictly a decimal from [0..255].
1123
1124 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001125 if not octet_str:
1126 raise ValueError("Empty octet not permitted")
Nick Coghlandc9b2552012-05-20 21:01:57 +10001127 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1128 if not self._DECIMAL_DIGITS.issuperset(octet_str):
Nick Coghlan07c4e332012-07-08 23:06:45 +10001129 msg = "Only decimal digits permitted in %r"
1130 raise ValueError(msg % octet_str)
1131 # We do the length check second, since the invalid character error
1132 # is likely to be more informative for the user
1133 if len(octet_str) > 3:
1134 msg = "At most 3 characters permitted in %r"
1135 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001136 # Convert to integer (we know digits are legal)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001137 octet_int = int(octet_str, 10)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001138 # Any octets that look like they *might* be written in octal,
1139 # and which don't look exactly the same in both octal and
1140 # decimal are rejected as ambiguous
1141 if octet_int > 7 and octet_str[0] == '0':
Nick Coghlan07c4e332012-07-08 23:06:45 +10001142 msg = "Ambiguous (octal/decimal) value in %r not permitted"
1143 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001144 if octet_int > 255:
Nick Coghlanb582ecc2012-07-07 22:15:22 +10001145 raise ValueError("Octet %d (> 255) not permitted" % octet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001146 return octet_int
1147
1148 def _string_from_ip_int(self, ip_int):
1149 """Turns a 32-bit integer into dotted decimal notation.
1150
1151 Args:
1152 ip_int: An integer, the IP address.
1153
1154 Returns:
1155 The IP address as a string in dotted decimal notation.
1156
1157 """
Nick Coghlan7319f692012-07-07 21:43:30 +10001158 return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001159
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001160 def _is_valid_netmask(self, netmask):
1161 """Verify that the netmask is valid.
1162
1163 Args:
1164 netmask: A string, either a prefix or dotted decimal
1165 netmask.
1166
1167 Returns:
1168 A boolean, True if the prefix represents a valid IPv4
1169 netmask.
1170
1171 """
1172 mask = netmask.split('.')
1173 if len(mask) == 4:
Nick Coghlan7319f692012-07-07 21:43:30 +10001174 try:
1175 for x in mask:
1176 if int(x) not in self._valid_mask_octets:
1177 return False
1178 except ValueError:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001179 # Found something that isn't an integer or isn't valid
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001180 return False
Nick Coghlan7319f692012-07-07 21:43:30 +10001181 for idx, y in enumerate(mask):
1182 if idx > 0 and y > mask[idx - 1]:
1183 return False
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001184 return True
1185 try:
1186 netmask = int(netmask)
1187 except ValueError:
1188 return False
1189 return 0 <= netmask <= self._max_prefixlen
1190
1191 def _is_hostmask(self, ip_str):
1192 """Test if the IP string is a hostmask (rather than a netmask).
1193
1194 Args:
1195 ip_str: A string, the potential hostmask.
1196
1197 Returns:
1198 A boolean, True if the IP string is a hostmask.
1199
1200 """
1201 bits = ip_str.split('.')
1202 try:
Nick Coghlan7319f692012-07-07 21:43:30 +10001203 parts = [x for x in map(int, bits) if x in self._valid_mask_octets]
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001204 except ValueError:
1205 return False
1206 if len(parts) != len(bits):
1207 return False
1208 if parts[0] < parts[-1]:
1209 return True
1210 return False
1211
Nick Coghlandc9b2552012-05-20 21:01:57 +10001212 @property
1213 def max_prefixlen(self):
1214 return self._max_prefixlen
1215
1216 @property
1217 def version(self):
1218 return self._version
1219
Nick Coghlandc9b2552012-05-20 21:01:57 +10001220
1221class IPv4Address(_BaseV4, _BaseAddress):
1222
1223 """Represent and manipulate single IPv4 Addresses."""
1224
1225 def __init__(self, address):
1226
1227 """
1228 Args:
1229 address: A string or integer representing the IP
1230
1231 Additionally, an integer can be passed, so
1232 IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1233 or, more generally
1234 IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1235 IPv4Address('192.0.2.1')
1236
1237 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001238 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001239
1240 """
1241 _BaseAddress.__init__(self, address)
1242 _BaseV4.__init__(self, address)
1243
1244 # Efficient constructor from integer.
1245 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001246 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001247 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001248 return
1249
1250 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001251 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001252 self._check_packed_address(address, 4)
Nick Coghlandb7920b2012-08-20 10:19:12 +10001253 self._ip = int.from_bytes(address, 'big')
Nick Coghlandc9b2552012-05-20 21:01:57 +10001254 return
1255
1256 # Assume input argument to be string or any object representation
1257 # which converts into a formatted IP string.
1258 addr_str = str(address)
1259 self._ip = self._ip_int_from_string(addr_str)
1260
1261 @property
1262 def packed(self):
1263 """The binary representation of this address."""
1264 return v4_int_to_packed(self._ip)
1265
Nick Coghlan730f67f2012-08-05 22:02:18 +10001266 @property
1267 def is_reserved(self):
1268 """Test if the address is otherwise IETF reserved.
1269
1270 Returns:
1271 A boolean, True if the address is within the
1272 reserved IPv4 Network range.
1273
1274 """
1275 reserved_network = IPv4Network('240.0.0.0/4')
1276 return self in reserved_network
1277
1278 @property
1279 def is_private(self):
1280 """Test if this address is allocated for private networks.
1281
1282 Returns:
1283 A boolean, True if the address is reserved per RFC 1918.
1284
1285 """
1286 private_10 = IPv4Network('10.0.0.0/8')
1287 private_172 = IPv4Network('172.16.0.0/12')
1288 private_192 = IPv4Network('192.168.0.0/16')
1289 return (self in private_10 or
1290 self in private_172 or
1291 self in private_192)
1292
1293 @property
1294 def is_multicast(self):
1295 """Test if the address is reserved for multicast use.
1296
1297 Returns:
1298 A boolean, True if the address is multicast.
1299 See RFC 3171 for details.
1300
1301 """
1302 multicast_network = IPv4Network('224.0.0.0/4')
1303 return self in multicast_network
1304
1305 @property
1306 def is_unspecified(self):
1307 """Test if the address is unspecified.
1308
1309 Returns:
1310 A boolean, True if this is the unspecified address as defined in
1311 RFC 5735 3.
1312
1313 """
1314 unspecified_address = IPv4Address('0.0.0.0')
1315 return self == unspecified_address
1316
1317 @property
1318 def is_loopback(self):
1319 """Test if the address is a loopback address.
1320
1321 Returns:
1322 A boolean, True if the address is a loopback per RFC 3330.
1323
1324 """
1325 loopback_network = IPv4Network('127.0.0.0/8')
1326 return self in loopback_network
1327
1328 @property
1329 def is_link_local(self):
1330 """Test if the address is reserved for link-local.
1331
1332 Returns:
1333 A boolean, True if the address is link-local per RFC 3927.
1334
1335 """
1336 linklocal_network = IPv4Network('169.254.0.0/16')
1337 return self in linklocal_network
1338
Nick Coghlandc9b2552012-05-20 21:01:57 +10001339
1340class IPv4Interface(IPv4Address):
1341
Nick Coghlandc9b2552012-05-20 21:01:57 +10001342 def __init__(self, address):
1343 if isinstance(address, (bytes, int)):
1344 IPv4Address.__init__(self, address)
1345 self.network = IPv4Network(self._ip)
1346 self._prefixlen = self._max_prefixlen
1347 return
1348
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001349 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001350 IPv4Address.__init__(self, addr[0])
1351
1352 self.network = IPv4Network(address, strict=False)
1353 self._prefixlen = self.network._prefixlen
1354
1355 self.netmask = self.network.netmask
1356 self.hostmask = self.network.hostmask
1357
Nick Coghlandc9b2552012-05-20 21:01:57 +10001358 def __str__(self):
1359 return '%s/%d' % (self._string_from_ip_int(self._ip),
1360 self.network.prefixlen)
1361
1362 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001363 address_equal = IPv4Address.__eq__(self, other)
1364 if not address_equal or address_equal is NotImplemented:
1365 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001366 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001367 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001368 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001369 # An interface with an associated network is NOT the
1370 # same as an unassociated address. That's why the hash
1371 # takes the extra info into account.
1372 return False
1373
1374 def __lt__(self, other):
1375 address_less = IPv4Address.__lt__(self, other)
1376 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001377 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001378 try:
1379 return self.network < other.network
1380 except AttributeError:
1381 # We *do* allow addresses and interfaces to be sorted. The
1382 # unassociated address is considered less than all interfaces.
1383 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001384
1385 def __hash__(self):
1386 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1387
Nick Coghlandc9b2552012-05-20 21:01:57 +10001388 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001389 def ip(self):
1390 return IPv4Address(self._ip)
1391
1392 @property
1393 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10001394 return '%s/%s' % (self._string_from_ip_int(self._ip),
1395 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001396
1397 @property
1398 def with_netmask(self):
1399 return '%s/%s' % (self._string_from_ip_int(self._ip),
1400 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001401
Nick Coghlandc9b2552012-05-20 21:01:57 +10001402 @property
1403 def with_hostmask(self):
1404 return '%s/%s' % (self._string_from_ip_int(self._ip),
1405 self.hostmask)
1406
1407
1408class IPv4Network(_BaseV4, _BaseNetwork):
1409
1410 """This class represents and manipulates 32-bit IPv4 network + addresses..
1411
1412 Attributes: [examples for IPv4Network('192.0.2.0/27')]
1413 .network_address: IPv4Address('192.0.2.0')
1414 .hostmask: IPv4Address('0.0.0.31')
1415 .broadcast_address: IPv4Address('192.0.2.32')
1416 .netmask: IPv4Address('255.255.255.224')
1417 .prefixlen: 27
1418
1419 """
Nick Coghlan51c30672012-05-27 00:25:58 +10001420 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001421 _address_class = IPv4Address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001422
Nick Coghlandc9b2552012-05-20 21:01:57 +10001423 def __init__(self, address, strict=True):
1424
1425 """Instantiate a new IPv4 network object.
1426
1427 Args:
1428 address: A string or integer representing the IP [& network].
1429 '192.0.2.0/24'
1430 '192.0.2.0/255.255.255.0'
1431 '192.0.0.2/0.0.0.255'
1432 are all functionally the same in IPv4. Similarly,
1433 '192.0.2.1'
1434 '192.0.2.1/255.255.255.255'
1435 '192.0.2.1/32'
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001436 are also functionally equivalent. That is to say, failing to
Nick Coghlandc9b2552012-05-20 21:01:57 +10001437 provide a subnetmask will create an object with a mask of /32.
1438
1439 If the mask (portion after the / in the argument) is given in
1440 dotted quad form, it is treated as a netmask if it starts with a
1441 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1442 starts with a zero field (e.g. 0.255.255.255 == /8), with the
1443 single exception of an all-zero mask which is treated as a
1444 netmask == /0. If no mask is given, a default of /32 is used.
1445
1446 Additionally, an integer can be passed, so
1447 IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1448 or, more generally
1449 IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1450 IPv4Interface('192.0.2.1')
1451
1452 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001453 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001454 NetmaskValueError: If the netmask isn't valid for
1455 an IPv4 address.
Sandro Tosib4386d32012-06-02 17:14:22 +02001456 ValueError: If strict is True and a network address is not
Nick Coghlandc9b2552012-05-20 21:01:57 +10001457 supplied.
1458
1459 """
1460
1461 _BaseV4.__init__(self, address)
1462 _BaseNetwork.__init__(self, address)
1463
1464 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001465 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001466 self.network_address = IPv4Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001467 self._prefixlen = self._max_prefixlen
1468 self.netmask = IPv4Address(self._ALL_ONES)
1469 #fixme: address/network test here
1470 return
1471
1472 # Efficient constructor from integer.
1473 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001474 self.network_address = IPv4Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001475 self._prefixlen = self._max_prefixlen
1476 self.netmask = IPv4Address(self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001477 #fixme: address/network test here.
1478 return
1479
1480 # Assume input argument to be string or any object representation
1481 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001482 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001483 self.network_address = IPv4Address(self._ip_int_from_string(addr[0]))
1484
Nick Coghlandc9b2552012-05-20 21:01:57 +10001485 if len(addr) == 2:
Nick Coghlan932346f2014-02-08 23:17:36 +10001486 try:
1487 # Check for a netmask in prefix length form
1488 self._prefixlen = self._prefix_from_prefix_string(addr[1])
1489 except NetmaskValueError:
1490 # Check for a netmask or hostmask in dotted-quad form.
1491 # This may raise NetmaskValueError.
1492 self._prefixlen = self._prefix_from_ip_string(addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001493 else:
1494 self._prefixlen = self._max_prefixlen
Nick Coghlan932346f2014-02-08 23:17:36 +10001495 self.netmask = IPv4Address(self._ip_int_from_prefix(self._prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001496
1497 if strict:
1498 if (IPv4Address(int(self.network_address) & int(self.netmask)) !=
1499 self.network_address):
1500 raise ValueError('%s has host bits set' % self)
1501 self.network_address = IPv4Address(int(self.network_address) &
1502 int(self.netmask))
1503
1504 if self._prefixlen == (self._max_prefixlen - 1):
1505 self.hosts = self.__iter__
1506
Nick Coghlandc9b2552012-05-20 21:01:57 +10001507
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001508class _BaseV6:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001509
1510 """Base IPv6 object.
1511
1512 The following methods are used by IPv6 objects in both single IP
1513 addresses and networks.
1514
1515 """
1516
1517 _ALL_ONES = (2**IPV6LENGTH) - 1
1518 _HEXTET_COUNT = 8
1519 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
1520
1521 def __init__(self, address):
1522 self._version = 6
1523 self._max_prefixlen = IPV6LENGTH
1524
1525 def _ip_int_from_string(self, ip_str):
1526 """Turn an IPv6 ip_str into an integer.
1527
1528 Args:
1529 ip_str: A string, the IPv6 ip_str.
1530
1531 Returns:
1532 An int, the IPv6 address
1533
1534 Raises:
1535 AddressValueError: if ip_str isn't a valid IPv6 Address.
1536
1537 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001538 if not ip_str:
1539 raise AddressValueError('Address cannot be empty')
1540
Nick Coghlandc9b2552012-05-20 21:01:57 +10001541 parts = ip_str.split(':')
1542
1543 # An IPv6 address needs at least 2 colons (3 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001544 _min_parts = 3
1545 if len(parts) < _min_parts:
1546 msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
1547 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001548
1549 # If the address has an IPv4-style suffix, convert it to hexadecimal.
1550 if '.' in parts[-1]:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001551 try:
1552 ipv4_int = IPv4Address(parts.pop())._ip
1553 except AddressValueError as exc:
1554 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001555 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1556 parts.append('%x' % (ipv4_int & 0xFFFF))
1557
1558 # An IPv6 address can't have more than 8 colons (9 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001559 # The extra colon comes from using the "::" notation for a single
1560 # leading or trailing zero part.
1561 _max_parts = self._HEXTET_COUNT + 1
1562 if len(parts) > _max_parts:
1563 msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
1564 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001565
1566 # Disregarding the endpoints, find '::' with nothing in between.
1567 # This indicates that a run of zeroes has been skipped.
Nick Coghlan7319f692012-07-07 21:43:30 +10001568 skip_index = None
1569 for i in range(1, len(parts) - 1):
1570 if not parts[i]:
1571 if skip_index is not None:
1572 # Can't have more than one '::'
1573 msg = "At most one '::' permitted in %r" % ip_str
1574 raise AddressValueError(msg)
1575 skip_index = i
Nick Coghlandc9b2552012-05-20 21:01:57 +10001576
1577 # parts_hi is the number of parts to copy from above/before the '::'
1578 # parts_lo is the number of parts to copy from below/after the '::'
1579 if skip_index is not None:
1580 # If we found a '::', then check if it also covers the endpoints.
1581 parts_hi = skip_index
1582 parts_lo = len(parts) - skip_index - 1
1583 if not parts[0]:
1584 parts_hi -= 1
1585 if parts_hi:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001586 msg = "Leading ':' only permitted as part of '::' in %r"
1587 raise AddressValueError(msg % ip_str) # ^: requires ^::
Nick Coghlandc9b2552012-05-20 21:01:57 +10001588 if not parts[-1]:
1589 parts_lo -= 1
1590 if parts_lo:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001591 msg = "Trailing ':' only permitted as part of '::' in %r"
1592 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001593 parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo)
1594 if parts_skipped < 1:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001595 msg = "Expected at most %d other parts with '::' in %r"
1596 raise AddressValueError(msg % (self._HEXTET_COUNT-1, ip_str))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001597 else:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001598 # Otherwise, allocate the entire address to parts_hi. The
1599 # endpoints could still be empty, but _parse_hextet() will check
1600 # for that.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001601 if len(parts) != self._HEXTET_COUNT:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001602 msg = "Exactly %d parts expected without '::' in %r"
1603 raise AddressValueError(msg % (self._HEXTET_COUNT, ip_str))
1604 if not parts[0]:
1605 msg = "Leading ':' only permitted as part of '::' in %r"
1606 raise AddressValueError(msg % ip_str) # ^: requires ^::
1607 if not parts[-1]:
1608 msg = "Trailing ':' only permitted as part of '::' in %r"
1609 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001610 parts_hi = len(parts)
1611 parts_lo = 0
1612 parts_skipped = 0
1613
1614 try:
1615 # Now, parse the hextets into a 128-bit integer.
1616 ip_int = 0
1617 for i in range(parts_hi):
1618 ip_int <<= 16
1619 ip_int |= self._parse_hextet(parts[i])
1620 ip_int <<= 16 * parts_skipped
1621 for i in range(-parts_lo, 0):
1622 ip_int <<= 16
1623 ip_int |= self._parse_hextet(parts[i])
1624 return ip_int
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001625 except ValueError as exc:
1626 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001627
1628 def _parse_hextet(self, hextet_str):
1629 """Convert an IPv6 hextet string into an integer.
1630
1631 Args:
1632 hextet_str: A string, the number to parse.
1633
1634 Returns:
1635 The hextet as an integer.
1636
1637 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001638 ValueError: if the input isn't strictly a hex number from
1639 [0..FFFF].
Nick Coghlandc9b2552012-05-20 21:01:57 +10001640
1641 """
1642 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1643 if not self._HEX_DIGITS.issuperset(hextet_str):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001644 raise ValueError("Only hex digits permitted in %r" % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001645 # We do the length check second, since the invalid character error
1646 # is likely to be more informative for the user
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001647 if len(hextet_str) > 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001648 msg = "At most 4 characters permitted in %r"
1649 raise ValueError(msg % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001650 # Length check means we can skip checking the integer value
1651 return int(hextet_str, 16)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001652
1653 def _compress_hextets(self, hextets):
1654 """Compresses a list of hextets.
1655
1656 Compresses a list of strings, replacing the longest continuous
1657 sequence of "0" in the list with "" and adding empty strings at
1658 the beginning or at the end of the string such that subsequently
1659 calling ":".join(hextets) will produce the compressed version of
1660 the IPv6 address.
1661
1662 Args:
1663 hextets: A list of strings, the hextets to compress.
1664
1665 Returns:
1666 A list of strings.
1667
1668 """
1669 best_doublecolon_start = -1
1670 best_doublecolon_len = 0
1671 doublecolon_start = -1
1672 doublecolon_len = 0
Nick Coghlandb7920b2012-08-20 10:19:12 +10001673 for index, hextet in enumerate(hextets):
1674 if hextet == '0':
Nick Coghlandc9b2552012-05-20 21:01:57 +10001675 doublecolon_len += 1
1676 if doublecolon_start == -1:
1677 # Start of a sequence of zeros.
1678 doublecolon_start = index
1679 if doublecolon_len > best_doublecolon_len:
1680 # This is the longest sequence of zeros so far.
1681 best_doublecolon_len = doublecolon_len
1682 best_doublecolon_start = doublecolon_start
1683 else:
1684 doublecolon_len = 0
1685 doublecolon_start = -1
1686
1687 if best_doublecolon_len > 1:
1688 best_doublecolon_end = (best_doublecolon_start +
1689 best_doublecolon_len)
1690 # For zeros at the end of the address.
1691 if best_doublecolon_end == len(hextets):
1692 hextets += ['']
1693 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1694 # For zeros at the beginning of the address.
1695 if best_doublecolon_start == 0:
1696 hextets = [''] + hextets
1697
1698 return hextets
1699
1700 def _string_from_ip_int(self, ip_int=None):
1701 """Turns a 128-bit integer into hexadecimal notation.
1702
1703 Args:
1704 ip_int: An integer, the IP address.
1705
1706 Returns:
1707 A string, the hexadecimal representation of the address.
1708
1709 Raises:
1710 ValueError: The address is bigger than 128 bits of all ones.
1711
1712 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001713 if ip_int is None:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001714 ip_int = int(self._ip)
1715
1716 if ip_int > self._ALL_ONES:
1717 raise ValueError('IPv6 address is too large')
1718
1719 hex_str = '%032x' % ip_int
Nick Coghlan7319f692012-07-07 21:43:30 +10001720 hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001721
1722 hextets = self._compress_hextets(hextets)
1723 return ':'.join(hextets)
1724
1725 def _explode_shorthand_ip_string(self):
1726 """Expand a shortened IPv6 address.
1727
1728 Args:
1729 ip_str: A string, the IPv6 address.
1730
1731 Returns:
1732 A string, the expanded IPv6 address.
1733
1734 """
1735 if isinstance(self, IPv6Network):
1736 ip_str = str(self.network_address)
1737 elif isinstance(self, IPv6Interface):
1738 ip_str = str(self.ip)
1739 else:
1740 ip_str = str(self)
1741
1742 ip_int = self._ip_int_from_string(ip_str)
Nick Coghlan7319f692012-07-07 21:43:30 +10001743 hex_str = '%032x' % ip_int
1744 parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001745 if isinstance(self, (_BaseNetwork, IPv6Interface)):
Nick Coghlane3ded952012-08-05 22:45:22 +10001746 return '%s/%d' % (':'.join(parts), self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001747 return ':'.join(parts)
1748
1749 @property
1750 def max_prefixlen(self):
1751 return self._max_prefixlen
1752
1753 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001754 def version(self):
1755 return self._version
1756
Nick Coghlandc9b2552012-05-20 21:01:57 +10001757
1758class IPv6Address(_BaseV6, _BaseAddress):
1759
Sandro Tosib95c6342012-05-23 23:17:22 +02001760 """Represent and manipulate single IPv6 Addresses."""
Nick Coghlandc9b2552012-05-20 21:01:57 +10001761
1762 def __init__(self, address):
1763 """Instantiate a new IPv6 address object.
1764
1765 Args:
1766 address: A string or integer representing the IP
1767
1768 Additionally, an integer can be passed, so
1769 IPv6Address('2001:db8::') ==
1770 IPv6Address(42540766411282592856903984951653826560)
1771 or, more generally
1772 IPv6Address(int(IPv6Address('2001:db8::'))) ==
1773 IPv6Address('2001:db8::')
1774
1775 Raises:
1776 AddressValueError: If address isn't a valid IPv6 address.
1777
1778 """
1779 _BaseAddress.__init__(self, address)
1780 _BaseV6.__init__(self, address)
1781
1782 # Efficient constructor from integer.
1783 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001784 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001785 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001786 return
1787
1788 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001789 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001790 self._check_packed_address(address, 16)
Nick Coghlandb7920b2012-08-20 10:19:12 +10001791 self._ip = int.from_bytes(address, 'big')
Nick Coghlandc9b2552012-05-20 21:01:57 +10001792 return
1793
1794 # Assume input argument to be string or any object representation
1795 # which converts into a formatted IP string.
1796 addr_str = str(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001797 self._ip = self._ip_int_from_string(addr_str)
1798
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001799 @property
1800 def packed(self):
1801 """The binary representation of this address."""
1802 return v6_int_to_packed(self._ip)
1803
Nick Coghlan730f67f2012-08-05 22:02:18 +10001804 @property
1805 def is_multicast(self):
1806 """Test if the address is reserved for multicast use.
1807
1808 Returns:
1809 A boolean, True if the address is a multicast address.
1810 See RFC 2373 2.7 for details.
1811
1812 """
1813 multicast_network = IPv6Network('ff00::/8')
1814 return self in multicast_network
1815
1816 @property
1817 def is_reserved(self):
1818 """Test if the address is otherwise IETF reserved.
1819
1820 Returns:
1821 A boolean, True if the address is within one of the
1822 reserved IPv6 Network ranges.
1823
1824 """
1825 reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'),
1826 IPv6Network('200::/7'), IPv6Network('400::/6'),
1827 IPv6Network('800::/5'), IPv6Network('1000::/4'),
1828 IPv6Network('4000::/3'), IPv6Network('6000::/3'),
1829 IPv6Network('8000::/3'), IPv6Network('A000::/3'),
1830 IPv6Network('C000::/3'), IPv6Network('E000::/4'),
1831 IPv6Network('F000::/5'), IPv6Network('F800::/6'),
1832 IPv6Network('FE00::/9')]
1833
1834 return any(self in x for x in reserved_networks)
1835
1836 @property
1837 def is_link_local(self):
1838 """Test if the address is reserved for link-local.
1839
1840 Returns:
1841 A boolean, True if the address is reserved per RFC 4291.
1842
1843 """
1844 linklocal_network = IPv6Network('fe80::/10')
1845 return self in linklocal_network
1846
1847 @property
1848 def is_site_local(self):
1849 """Test if the address is reserved for site-local.
1850
1851 Note that the site-local address space has been deprecated by RFC 3879.
1852 Use is_private to test if this address is in the space of unique local
1853 addresses as defined by RFC 4193.
1854
1855 Returns:
1856 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1857
1858 """
1859 sitelocal_network = IPv6Network('fec0::/10')
1860 return self in sitelocal_network
1861
1862 @property
1863 def is_private(self):
1864 """Test if this address is allocated for private networks.
1865
1866 Returns:
1867 A boolean, True if the address is reserved per RFC 4193.
1868
1869 """
1870 private_network = IPv6Network('fc00::/7')
1871 return self in private_network
1872
1873 @property
1874 def is_unspecified(self):
1875 """Test if the address is unspecified.
1876
1877 Returns:
1878 A boolean, True if this is the unspecified address as defined in
1879 RFC 2373 2.5.2.
1880
1881 """
1882 return self._ip == 0
1883
1884 @property
1885 def is_loopback(self):
1886 """Test if the address is a loopback address.
1887
1888 Returns:
1889 A boolean, True if the address is a loopback address as defined in
1890 RFC 2373 2.5.3.
1891
1892 """
1893 return self._ip == 1
1894
1895 @property
1896 def ipv4_mapped(self):
1897 """Return the IPv4 mapped address.
1898
1899 Returns:
1900 If the IPv6 address is a v4 mapped address, return the
1901 IPv4 mapped address. Return None otherwise.
1902
1903 """
1904 if (self._ip >> 32) != 0xFFFF:
1905 return None
1906 return IPv4Address(self._ip & 0xFFFFFFFF)
1907
1908 @property
1909 def teredo(self):
1910 """Tuple of embedded teredo IPs.
1911
1912 Returns:
1913 Tuple of the (server, client) IPs or None if the address
1914 doesn't appear to be a teredo address (doesn't start with
1915 2001::/32)
1916
1917 """
1918 if (self._ip >> 96) != 0x20010000:
1919 return None
1920 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
1921 IPv4Address(~self._ip & 0xFFFFFFFF))
1922
1923 @property
1924 def sixtofour(self):
1925 """Return the IPv4 6to4 embedded address.
1926
1927 Returns:
1928 The IPv4 6to4-embedded address if present or None if the
1929 address doesn't appear to contain a 6to4 embedded address.
1930
1931 """
1932 if (self._ip >> 112) != 0x2002:
1933 return None
1934 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
1935
Nick Coghlandc9b2552012-05-20 21:01:57 +10001936
1937class IPv6Interface(IPv6Address):
1938
1939 def __init__(self, address):
1940 if isinstance(address, (bytes, int)):
1941 IPv6Address.__init__(self, address)
1942 self.network = IPv6Network(self._ip)
1943 self._prefixlen = self._max_prefixlen
1944 return
1945
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001946 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001947 IPv6Address.__init__(self, addr[0])
1948 self.network = IPv6Network(address, strict=False)
1949 self.netmask = self.network.netmask
1950 self._prefixlen = self.network._prefixlen
1951 self.hostmask = self.network.hostmask
1952
Nick Coghlandc9b2552012-05-20 21:01:57 +10001953 def __str__(self):
1954 return '%s/%d' % (self._string_from_ip_int(self._ip),
1955 self.network.prefixlen)
1956
1957 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001958 address_equal = IPv6Address.__eq__(self, other)
1959 if not address_equal or address_equal is NotImplemented:
1960 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001961 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001962 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001963 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001964 # An interface with an associated network is NOT the
1965 # same as an unassociated address. That's why the hash
1966 # takes the extra info into account.
1967 return False
1968
1969 def __lt__(self, other):
1970 address_less = IPv6Address.__lt__(self, other)
1971 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001972 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001973 try:
1974 return self.network < other.network
1975 except AttributeError:
1976 # We *do* allow addresses and interfaces to be sorted. The
1977 # unassociated address is considered less than all interfaces.
1978 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001979
1980 def __hash__(self):
1981 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1982
1983 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001984 def ip(self):
1985 return IPv6Address(self._ip)
1986
1987 @property
1988 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10001989 return '%s/%s' % (self._string_from_ip_int(self._ip),
1990 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001991
1992 @property
1993 def with_netmask(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10001994 return '%s/%s' % (self._string_from_ip_int(self._ip),
1995 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001996
Nick Coghlandc9b2552012-05-20 21:01:57 +10001997 @property
1998 def with_hostmask(self):
1999 return '%s/%s' % (self._string_from_ip_int(self._ip),
2000 self.hostmask)
2001
Nick Coghlan730f67f2012-08-05 22:02:18 +10002002 @property
2003 def is_unspecified(self):
2004 return self._ip == 0 and self.network.is_unspecified
2005
2006 @property
2007 def is_loopback(self):
2008 return self._ip == 1 and self.network.is_loopback
2009
Nick Coghlandc9b2552012-05-20 21:01:57 +10002010
2011class IPv6Network(_BaseV6, _BaseNetwork):
2012
2013 """This class represents and manipulates 128-bit IPv6 networks.
2014
2015 Attributes: [examples for IPv6('2001:db8::1000/124')]
2016 .network_address: IPv6Address('2001:db8::1000')
2017 .hostmask: IPv6Address('::f')
2018 .broadcast_address: IPv6Address('2001:db8::100f')
2019 .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
2020 .prefixlen: 124
2021
2022 """
2023
Nick Coghlan51c30672012-05-27 00:25:58 +10002024 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10002025 _address_class = IPv6Address
2026
Nick Coghlandc9b2552012-05-20 21:01:57 +10002027 def __init__(self, address, strict=True):
2028 """Instantiate a new IPv6 Network object.
2029
2030 Args:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02002031 address: A string or integer representing the IPv6 network or the
2032 IP and prefix/netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +10002033 '2001:db8::/128'
2034 '2001:db8:0000:0000:0000:0000:0000:0000/128'
2035 '2001:db8::'
2036 are all functionally the same in IPv6. That is to say,
2037 failing to provide a subnetmask will create an object with
2038 a mask of /128.
2039
2040 Additionally, an integer can be passed, so
2041 IPv6Network('2001:db8::') ==
2042 IPv6Network(42540766411282592856903984951653826560)
2043 or, more generally
2044 IPv6Network(int(IPv6Network('2001:db8::'))) ==
2045 IPv6Network('2001:db8::')
2046
2047 strict: A boolean. If true, ensure that we have been passed
2048 A true network address, eg, 2001:db8::1000/124 and not an
2049 IP address on a network, eg, 2001:db8::1/124.
2050
2051 Raises:
2052 AddressValueError: If address isn't a valid IPv6 address.
2053 NetmaskValueError: If the netmask isn't valid for
2054 an IPv6 address.
2055 ValueError: If strict was True and a network address was not
2056 supplied.
2057
2058 """
2059 _BaseV6.__init__(self, address)
2060 _BaseNetwork.__init__(self, address)
2061
2062 # Efficient constructor from integer.
2063 if isinstance(address, int):
Nick Coghlandc9b2552012-05-20 21:01:57 +10002064 self.network_address = IPv6Address(address)
2065 self._prefixlen = self._max_prefixlen
2066 self.netmask = IPv6Address(self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002067 return
2068
2069 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10002070 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10002071 self.network_address = IPv6Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002072 self._prefixlen = self._max_prefixlen
2073 self.netmask = IPv6Address(self._ALL_ONES)
Hynek Schlawacked36b2e2012-06-08 15:21:21 +02002074 return
Nick Coghlandc9b2552012-05-20 21:01:57 +10002075
2076 # Assume input argument to be string or any object representation
2077 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002078 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002079
2080 self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))
2081
2082 if len(addr) == 2:
Nick Coghlan932346f2014-02-08 23:17:36 +10002083 # This may raise NetmaskValueError
2084 self._prefixlen = self._prefix_from_prefix_string(addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10002085 else:
2086 self._prefixlen = self._max_prefixlen
2087
2088 self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen))
2089 if strict:
2090 if (IPv6Address(int(self.network_address) & int(self.netmask)) !=
2091 self.network_address):
Nick Coghlan912238e2012-07-07 13:34:50 +10002092 raise ValueError('%s has host bits set' % self)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002093 self.network_address = IPv6Address(int(self.network_address) &
2094 int(self.netmask))
2095
2096 if self._prefixlen == (self._max_prefixlen - 1):
2097 self.hosts = self.__iter__
2098
Nick Coghlan730f67f2012-08-05 22:02:18 +10002099 @property
2100 def is_site_local(self):
2101 """Test if the address is reserved for site-local.
2102
2103 Note that the site-local address space has been deprecated by RFC 3879.
2104 Use is_private to test if this address is in the space of unique local
2105 addresses as defined by RFC 4193.
2106
2107 Returns:
2108 A boolean, True if the address is reserved per RFC 3513 2.5.6.
2109
2110 """
2111 return (self.network_address.is_site_local and
2112 self.broadcast_address.is_site_local)