blob: 22efb092fb48a3a71a505e3e603ce54ff4514423 [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:
209 >>> summarize_address_range(IPv4Address('192.0.2.0'),
210 IPv4Address('192.0.2.130'))
211 [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'),
212 IPv4Network('192.0.2.130/32')]
213
214 Args:
215 first: the first IPv4Address or IPv6Address in the range.
216 last: the last IPv4Address or IPv6Address in the range.
217
218 Returns:
219 An iterator of the summarized IPv(4|6) network objects.
220
221 Raise:
222 TypeError:
223 If the first and last objects are not IP addresses.
224 If the first and last objects are not the same version.
225 ValueError:
226 If the last object is not greater than the first.
Nick Coghlan51c30672012-05-27 00:25:58 +1000227 If the version of the first address is not 4 or 6.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000228
229 """
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200230 if (not (isinstance(first, _BaseAddress) and
231 isinstance(last, _BaseAddress))):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000232 raise TypeError('first and last must be IP addresses, not networks')
233 if first.version != last.version:
234 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000235 first, last))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000236 if first > last:
237 raise ValueError('last IP address must be greater than first')
238
Nick Coghlandc9b2552012-05-20 21:01:57 +1000239 if first.version == 4:
240 ip = IPv4Network
241 elif first.version == 6:
242 ip = IPv6Network
243 else:
244 raise ValueError('unknown IP version')
245
246 ip_bits = first._max_prefixlen
247 first_int = first._ip
248 last_int = last._ip
249 while first_int <= last_int:
Nick Coghlan7319f692012-07-07 21:43:30 +1000250 nbits = min(_count_righthand_zero_bits(first_int, ip_bits),
251 (last_int - first_int + 1).bit_length() - 1)
252 net = ip('%s/%d' % (first, ip_bits - nbits))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000253 yield net
Nick Coghlan7319f692012-07-07 21:43:30 +1000254 first_int += 1 << nbits
255 if first_int - 1 == ip._ALL_ONES:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000256 break
Nick Coghlan51c30672012-05-27 00:25:58 +1000257 first = first.__class__(first_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000258
Sandro Tosib95c6342012-05-23 23:17:22 +0200259
Nick Coghlandc9b2552012-05-20 21:01:57 +1000260def _collapse_addresses_recursive(addresses):
261 """Loops through the addresses, collapsing concurrent netblocks.
262
263 Example:
264
265 ip1 = IPv4Network('192.0.2.0/26')
266 ip2 = IPv4Network('192.0.2.64/26')
267 ip3 = IPv4Network('192.0.2.128/26')
268 ip4 = IPv4Network('192.0.2.192/26')
269
270 _collapse_addresses_recursive([ip1, ip2, ip3, ip4]) ->
271 [IPv4Network('192.0.2.0/24')]
272
273 This shouldn't be called directly; it is called via
274 collapse_addresses([]).
275
276 Args:
277 addresses: A list of IPv4Network's or IPv6Network's
278
279 Returns:
280 A list of IPv4Network's or IPv6Network's depending on what we were
281 passed.
282
283 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000284 while True:
285 last_addr = None
286 ret_array = []
287 optimized = False
Nick Coghlandc9b2552012-05-20 21:01:57 +1000288
Nick Coghlan7319f692012-07-07 21:43:30 +1000289 for cur_addr in addresses:
290 if not ret_array:
291 last_addr = cur_addr
292 ret_array.append(cur_addr)
293 elif (cur_addr.network_address >= last_addr.network_address and
294 cur_addr.broadcast_address <= last_addr.broadcast_address):
295 optimized = True
296 elif cur_addr == list(last_addr.supernet().subnets())[1]:
297 ret_array[-1] = last_addr = last_addr.supernet()
298 optimized = True
299 else:
300 last_addr = cur_addr
301 ret_array.append(cur_addr)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000302
Nick Coghlan7319f692012-07-07 21:43:30 +1000303 addresses = ret_array
304 if not optimized:
305 return addresses
Nick Coghlandc9b2552012-05-20 21:01:57 +1000306
307
308def collapse_addresses(addresses):
309 """Collapse a list of IP objects.
310
311 Example:
312 collapse_addresses([IPv4Network('192.0.2.0/25'),
313 IPv4Network('192.0.2.128/25')]) ->
314 [IPv4Network('192.0.2.0/24')]
315
316 Args:
317 addresses: An iterator of IPv4Network or IPv6Network objects.
318
319 Returns:
320 An iterator of the collapsed IPv(4|6)Network objects.
321
322 Raises:
323 TypeError: If passed a list of mixed version objects.
324
325 """
326 i = 0
327 addrs = []
328 ips = []
329 nets = []
330
331 # split IP addresses and networks
332 for ip in addresses:
333 if isinstance(ip, _BaseAddress):
334 if ips and ips[-1]._version != ip._version:
335 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000336 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000337 ips.append(ip)
338 elif ip._prefixlen == ip._max_prefixlen:
339 if ips and ips[-1]._version != ip._version:
340 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000341 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000342 try:
343 ips.append(ip.ip)
344 except AttributeError:
345 ips.append(ip.network_address)
346 else:
347 if nets and nets[-1]._version != ip._version:
348 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000349 ip, nets[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000350 nets.append(ip)
351
352 # sort and dedup
353 ips = sorted(set(ips))
354 nets = sorted(set(nets))
355
356 while i < len(ips):
357 (first, last) = _find_address_range(ips[i:])
358 i = ips.index(last) + 1
359 addrs.extend(summarize_address_range(first, last))
360
361 return iter(_collapse_addresses_recursive(sorted(
362 addrs + nets, key=_BaseNetwork._get_networks_key)))
363
364
365def get_mixed_type_key(obj):
366 """Return a key suitable for sorting between networks and addresses.
367
368 Address and Network objects are not sortable by default; they're
369 fundamentally different so the expression
370
371 IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
372
373 doesn't make any sense. There are some times however, where you may wish
374 to have ipaddress sort these for you anyway. If you need to do this, you
375 can use this function as the key= argument to sorted().
376
377 Args:
378 obj: either a Network or Address object.
379 Returns:
380 appropriate key.
381
382 """
383 if isinstance(obj, _BaseNetwork):
384 return obj._get_networks_key()
385 elif isinstance(obj, _BaseAddress):
386 return obj._get_address_key()
387 return NotImplemented
388
389
Nick Coghlan3008ec02012-07-08 00:45:33 +1000390class _TotalOrderingMixin:
391 # Helper that derives the other comparison operations from
392 # __lt__ and __eq__
Nick Coghlan297b1432012-07-08 17:11:04 +1000393 # We avoid functools.total_ordering because it doesn't handle
394 # NotImplemented correctly yet (http://bugs.python.org/issue10042)
Nick Coghlan3008ec02012-07-08 00:45:33 +1000395 def __eq__(self, other):
396 raise NotImplementedError
397 def __ne__(self, other):
398 equal = self.__eq__(other)
399 if equal is NotImplemented:
400 return NotImplemented
401 return not equal
402 def __lt__(self, other):
403 raise NotImplementedError
404 def __le__(self, other):
405 less = self.__lt__(other)
406 if less is NotImplemented or not less:
407 return self.__eq__(other)
408 return less
409 def __gt__(self, other):
410 less = self.__lt__(other)
411 if less is NotImplemented:
412 return NotImplemented
413 equal = self.__eq__(other)
414 if equal is NotImplemented:
415 return NotImplemented
416 return not (less or equal)
417 def __ge__(self, other):
418 less = self.__lt__(other)
419 if less is NotImplemented:
420 return NotImplemented
421 return not less
422
423class _IPAddressBase(_TotalOrderingMixin):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000424
425 """The mother class."""
426
427 @property
428 def exploded(self):
429 """Return the longhand version of the IP address as a string."""
430 return self._explode_shorthand_ip_string()
431
432 @property
433 def compressed(self):
434 """Return the shorthand version of the IP address as a string."""
435 return str(self)
436
Nick Coghland9722652012-06-17 16:33:00 +1000437 @property
438 def version(self):
439 msg = '%200s has no version specified' % (type(self),)
440 raise NotImplementedError(msg)
441
Nick Coghlan297b1432012-07-08 17:11:04 +1000442 def _check_int_address(self, address):
443 if address < 0:
444 msg = "%d (< 0) is not permitted as an IPv%d address"
445 raise AddressValueError(msg % (address, self._version))
446 if address > self._ALL_ONES:
447 msg = "%d (>= 2**%d) is not permitted as an IPv%d address"
448 raise AddressValueError(msg % (address, self._max_prefixlen,
449 self._version))
450
451 def _check_packed_address(self, address, expected_len):
452 address_len = len(address)
453 if address_len != expected_len:
454 msg = "%r (len %d != %d) is not permitted as an IPv%d address"
455 raise AddressValueError(msg % (address, address_len,
456 expected_len, self._version))
457
Nick Coghlandc9b2552012-05-20 21:01:57 +1000458 def _ip_int_from_prefix(self, prefixlen=None):
459 """Turn the prefix length netmask into a int for comparison.
460
461 Args:
462 prefixlen: An integer, the prefix length.
463
464 Returns:
465 An integer.
466
467 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +0200468 if prefixlen is None:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000469 prefixlen = self._prefixlen
470 return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen)
471
472 def _prefix_from_ip_int(self, ip_int, mask=32):
473 """Return prefix length from the decimal netmask.
474
475 Args:
476 ip_int: An integer, the IP address.
477 mask: The netmask. Defaults to 32.
478
479 Returns:
480 An integer, the prefix length.
481
482 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000483 return mask - _count_righthand_zero_bits(ip_int, mask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000484
485 def _ip_string_from_prefix(self, prefixlen=None):
486 """Turn a prefix length into a dotted decimal string.
487
488 Args:
489 prefixlen: An integer, the netmask prefix length.
490
491 Returns:
492 A string, the dotted decimal netmask string.
493
494 """
495 if not prefixlen:
496 prefixlen = self._prefixlen
497 return self._string_from_ip_int(self._ip_int_from_prefix(prefixlen))
498
Nick Coghlan730f67f2012-08-05 22:02:18 +1000499
Nick Coghlandc9b2552012-05-20 21:01:57 +1000500class _BaseAddress(_IPAddressBase):
501
502 """A generic IP object.
503
504 This IP class contains the version independent methods which are
505 used by single IP addresses.
506
507 """
508
509 def __init__(self, address):
510 if (not isinstance(address, bytes)
511 and '/' in str(address)):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000512 raise AddressValueError("Unexpected '/' in %r" % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000513
Nick Coghlandc9b2552012-05-20 21:01:57 +1000514 def __int__(self):
515 return self._ip
516
Nick Coghlandc9b2552012-05-20 21:01:57 +1000517 def __eq__(self, other):
518 try:
519 return (self._ip == other._ip
520 and self._version == other._version)
521 except AttributeError:
522 return NotImplemented
523
Nick Coghlandc9b2552012-05-20 21:01:57 +1000524 def __lt__(self, other):
525 if self._version != other._version:
526 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000527 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000528 if not isinstance(other, _BaseAddress):
529 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000530 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000531 if self._ip != other._ip:
532 return self._ip < other._ip
533 return False
534
Nick Coghlandc9b2552012-05-20 21:01:57 +1000535 # Shorthand for Integer addition and subtraction. This is not
536 # meant to ever support addition/subtraction of addresses.
537 def __add__(self, other):
538 if not isinstance(other, int):
539 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000540 return self.__class__(int(self) + other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000541
542 def __sub__(self, other):
543 if not isinstance(other, int):
544 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000545 return self.__class__(int(self) - other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000546
547 def __repr__(self):
548 return '%s(%r)' % (self.__class__.__name__, str(self))
549
550 def __str__(self):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200551 return str(self._string_from_ip_int(self._ip))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000552
553 def __hash__(self):
554 return hash(hex(int(self._ip)))
555
556 def _get_address_key(self):
557 return (self._version, self)
558
Nick Coghlandc9b2552012-05-20 21:01:57 +1000559
560class _BaseNetwork(_IPAddressBase):
561
Nick Coghlan51c30672012-05-27 00:25:58 +1000562 """A generic IP network object.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000563
564 This IP class contains the version independent methods which are
565 used by networks.
566
567 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000568 def __init__(self, address):
569 self._cache = {}
570
Nick Coghlandc9b2552012-05-20 21:01:57 +1000571 def __repr__(self):
572 return '%s(%r)' % (self.__class__.__name__, str(self))
573
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200574 def __str__(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000575 return '%s/%d' % (self.network_address, self.prefixlen)
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200576
Nick Coghlandc9b2552012-05-20 21:01:57 +1000577 def hosts(self):
578 """Generate Iterator over usable hosts in a network.
579
Sandro Tosib95c6342012-05-23 23:17:22 +0200580 This is like __iter__ except it doesn't return the network
581 or broadcast addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000582
583 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000584 network = int(self.network_address)
585 broadcast = int(self.broadcast_address)
586 for x in range(network + 1, broadcast):
587 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000588
589 def __iter__(self):
Nick Coghlan7319f692012-07-07 21:43:30 +1000590 network = int(self.network_address)
591 broadcast = int(self.broadcast_address)
592 for x in range(network, broadcast + 1):
593 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000594
595 def __getitem__(self, n):
596 network = int(self.network_address)
597 broadcast = int(self.broadcast_address)
598 if n >= 0:
599 if network + n > broadcast:
600 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000601 return self._address_class(network + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000602 else:
603 n += 1
604 if broadcast + n < network:
605 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000606 return self._address_class(broadcast + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000607
608 def __lt__(self, other):
609 if self._version != other._version:
610 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000611 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000612 if not isinstance(other, _BaseNetwork):
613 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000614 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000615 if self.network_address != other.network_address:
616 return self.network_address < other.network_address
617 if self.netmask != other.netmask:
618 return self.netmask < other.netmask
619 return False
620
Nick Coghlandc9b2552012-05-20 21:01:57 +1000621 def __eq__(self, other):
Nick Coghlan9a9c28c2012-07-07 23:05:59 +1000622 try:
623 return (self._version == other._version and
624 self.network_address == other.network_address and
625 int(self.netmask) == int(other.netmask))
626 except AttributeError:
627 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000628
Nick Coghlandc9b2552012-05-20 21:01:57 +1000629 def __hash__(self):
630 return hash(int(self.network_address) ^ int(self.netmask))
631
632 def __contains__(self, other):
633 # always false if one is v4 and the other is v6.
634 if self._version != other._version:
635 return False
636 # dealing with another network.
637 if isinstance(other, _BaseNetwork):
638 return False
639 # dealing with another address
640 else:
641 # address
642 return (int(self.network_address) <= int(other._ip) <=
643 int(self.broadcast_address))
644
645 def overlaps(self, other):
646 """Tell if self is partly contained in other."""
647 return self.network_address in other or (
648 self.broadcast_address in other or (
649 other.network_address in self or (
650 other.broadcast_address in self)))
651
652 @property
653 def broadcast_address(self):
654 x = self._cache.get('broadcast_address')
655 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000656 x = self._address_class(int(self.network_address) |
657 int(self.hostmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000658 self._cache['broadcast_address'] = x
659 return x
660
661 @property
662 def hostmask(self):
663 x = self._cache.get('hostmask')
664 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000665 x = self._address_class(int(self.netmask) ^ self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000666 self._cache['hostmask'] = x
667 return x
668
669 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000670 def with_prefixlen(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000671 return '%s/%d' % (self.network_address, self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000672
673 @property
674 def with_netmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000675 return '%s/%s' % (self.network_address, self.netmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000676
677 @property
678 def with_hostmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000679 return '%s/%s' % (self.network_address, self.hostmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000680
681 @property
682 def num_addresses(self):
683 """Number of hosts in the current subnet."""
684 return int(self.broadcast_address) - int(self.network_address) + 1
685
686 @property
Nick Coghlan51c30672012-05-27 00:25:58 +1000687 def _address_class(self):
Nick Coghland9722652012-06-17 16:33:00 +1000688 # Returning bare address objects (rather than interfaces) allows for
689 # more consistent behaviour across the network address, broadcast
690 # address and individual host addresses.
691 msg = '%200s has no associated address class' % (type(self),)
692 raise NotImplementedError(msg)
Nick Coghlan51c30672012-05-27 00:25:58 +1000693
694 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000695 def prefixlen(self):
696 return self._prefixlen
697
698 def address_exclude(self, other):
699 """Remove an address from a larger block.
700
701 For example:
702
703 addr1 = ip_network('192.0.2.0/28')
704 addr2 = ip_network('192.0.2.1/32')
705 addr1.address_exclude(addr2) =
706 [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
707 IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
708
709 or IPv6:
710
711 addr1 = ip_network('2001:db8::1/32')
712 addr2 = ip_network('2001:db8::1/128')
713 addr1.address_exclude(addr2) =
714 [ip_network('2001:db8::1/128'),
715 ip_network('2001:db8::2/127'),
716 ip_network('2001:db8::4/126'),
717 ip_network('2001:db8::8/125'),
718 ...
719 ip_network('2001:db8:8000::/33')]
720
721 Args:
722 other: An IPv4Network or IPv6Network object of the same type.
723
724 Returns:
725 An iterator of the the IPv(4|6)Network objects which is self
726 minus other.
727
728 Raises:
729 TypeError: If self and other are of difffering address
730 versions, or if other is not a network object.
731 ValueError: If other is not completely contained by self.
732
733 """
734 if not self._version == other._version:
735 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000736 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000737
738 if not isinstance(other, _BaseNetwork):
Nick Coghlan912238e2012-07-07 13:34:50 +1000739 raise TypeError("%s is not a network object" % other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000740
741 if not (other.network_address >= self.network_address and
742 other.broadcast_address <= self.broadcast_address):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200743 raise ValueError('%s not contained in %s' % (other, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000744 if other == self:
745 raise StopIteration
746
Nick Coghlandc9b2552012-05-20 21:01:57 +1000747 # Make sure we're comparing the network of other.
Nick Coghlan912238e2012-07-07 13:34:50 +1000748 other = other.__class__('%s/%s' % (other.network_address,
749 other.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000750
751 s1, s2 = self.subnets()
752 while s1 != other and s2 != other:
753 if (other.network_address >= s1.network_address and
754 other.broadcast_address <= s1.broadcast_address):
755 yield s2
756 s1, s2 = s1.subnets()
757 elif (other.network_address >= s2.network_address and
758 other.broadcast_address <= s2.broadcast_address):
759 yield s1
760 s1, s2 = s2.subnets()
761 else:
762 # If we got here, there's a bug somewhere.
763 raise AssertionError('Error performing exclusion: '
764 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000765 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000766 if s1 == other:
767 yield s2
768 elif s2 == other:
769 yield s1
770 else:
771 # If we got here, there's a bug somewhere.
772 raise AssertionError('Error performing exclusion: '
773 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000774 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000775
776 def compare_networks(self, other):
777 """Compare two IP objects.
778
779 This is only concerned about the comparison of the integer
780 representation of the network addresses. This means that the
781 host bits aren't considered at all in this method. If you want
782 to compare host bits, you can easily enough do a
783 'HostA._ip < HostB._ip'
784
785 Args:
786 other: An IP object.
787
788 Returns:
789 If the IP versions of self and other are the same, returns:
790
791 -1 if self < other:
792 eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
793 IPv6Network('2001:db8::1000/124') <
794 IPv6Network('2001:db8::2000/124')
795 0 if self == other
796 eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
797 IPv6Network('2001:db8::1000/124') ==
798 IPv6Network('2001:db8::1000/124')
799 1 if self > other
800 eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
801 IPv6Network('2001:db8::2000/124') >
802 IPv6Network('2001:db8::1000/124')
803
804 Raises:
805 TypeError if the IP versions are different.
806
807 """
808 # does this need to raise a ValueError?
809 if self._version != other._version:
810 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000811 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000812 # self._version == other._version below here:
813 if self.network_address < other.network_address:
814 return -1
815 if self.network_address > other.network_address:
816 return 1
817 # self.network_address == other.network_address below here:
818 if self.netmask < other.netmask:
819 return -1
820 if self.netmask > other.netmask:
821 return 1
822 return 0
823
824 def _get_networks_key(self):
825 """Network-only key function.
826
827 Returns an object that identifies this address' network and
828 netmask. This function is a suitable "key" argument for sorted()
829 and list.sort().
830
831 """
832 return (self._version, self.network_address, self.netmask)
833
834 def subnets(self, prefixlen_diff=1, new_prefix=None):
835 """The subnets which join to make the current subnet.
836
837 In the case that self contains only one IP
838 (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
839 for IPv6), yield an iterator with just ourself.
840
841 Args:
842 prefixlen_diff: An integer, the amount the prefix length
843 should be increased by. This should not be set if
844 new_prefix is also set.
845 new_prefix: The desired new prefix length. This must be a
846 larger number (smaller prefix) than the existing prefix.
847 This should not be set if prefixlen_diff is also set.
848
849 Returns:
850 An iterator of IPv(4|6) objects.
851
852 Raises:
853 ValueError: The prefixlen_diff is too small or too large.
854 OR
855 prefixlen_diff and new_prefix are both set or new_prefix
856 is a smaller number than the current prefix (smaller
857 number means a larger network)
858
859 """
860 if self._prefixlen == self._max_prefixlen:
861 yield self
862 return
863
864 if new_prefix is not None:
865 if new_prefix < self._prefixlen:
866 raise ValueError('new prefix must be longer')
867 if prefixlen_diff != 1:
868 raise ValueError('cannot set prefixlen_diff and new_prefix')
869 prefixlen_diff = new_prefix - self._prefixlen
870
871 if prefixlen_diff < 0:
872 raise ValueError('prefix length diff must be > 0')
873 new_prefixlen = self._prefixlen + prefixlen_diff
874
875 if not self._is_valid_netmask(str(new_prefixlen)):
876 raise ValueError(
877 'prefix length diff %d is invalid for netblock %s' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000878 new_prefixlen, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000879
Nick Coghlan51c30672012-05-27 00:25:58 +1000880 first = self.__class__('%s/%s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000881 (self.network_address,
882 self._prefixlen + prefixlen_diff))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000883
884 yield first
885 current = first
886 while True:
887 broadcast = current.broadcast_address
888 if broadcast == self.broadcast_address:
889 return
Nick Coghlan51c30672012-05-27 00:25:58 +1000890 new_addr = self._address_class(int(broadcast) + 1)
Nick Coghlan912238e2012-07-07 13:34:50 +1000891 current = self.__class__('%s/%s' % (new_addr,
892 new_prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000893
894 yield current
895
Nick Coghlandc9b2552012-05-20 21:01:57 +1000896 def supernet(self, prefixlen_diff=1, new_prefix=None):
897 """The supernet containing the current network.
898
899 Args:
900 prefixlen_diff: An integer, the amount the prefix length of
901 the network should be decreased by. For example, given a
902 /24 network and a prefixlen_diff of 3, a supernet with a
903 /21 netmask is returned.
904
905 Returns:
906 An IPv4 network object.
907
908 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200909 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
910 a negative prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000911 OR
912 If prefixlen_diff and new_prefix are both set or new_prefix is a
913 larger number than the current prefix (larger number means a
914 smaller network)
915
916 """
917 if self._prefixlen == 0:
918 return self
919
920 if new_prefix is not None:
921 if new_prefix > self._prefixlen:
922 raise ValueError('new prefix must be shorter')
923 if prefixlen_diff != 1:
924 raise ValueError('cannot set prefixlen_diff and new_prefix')
925 prefixlen_diff = self._prefixlen - new_prefix
926
Nick Coghlandc9b2552012-05-20 21:01:57 +1000927 if self.prefixlen - prefixlen_diff < 0:
928 raise ValueError(
929 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
930 (self.prefixlen, prefixlen_diff))
931 # TODO (pmoody): optimize this.
Nick Coghlan912238e2012-07-07 13:34:50 +1000932 t = self.__class__('%s/%d' % (self.network_address,
Nick Coghlan51c30672012-05-27 00:25:58 +1000933 self.prefixlen - prefixlen_diff),
934 strict=False)
Nick Coghlan912238e2012-07-07 13:34:50 +1000935 return t.__class__('%s/%d' % (t.network_address, t.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000936
Nick Coghlan730f67f2012-08-05 22:02:18 +1000937 @property
938 def is_multicast(self):
939 """Test if the address is reserved for multicast use.
940
941 Returns:
942 A boolean, True if the address is a multicast address.
943 See RFC 2373 2.7 for details.
944
945 """
946 return (self.network_address.is_multicast and
947 self.broadcast_address.is_multicast)
948
949 @property
950 def is_reserved(self):
951 """Test if the address is otherwise IETF reserved.
952
953 Returns:
954 A boolean, True if the address is within one of the
955 reserved IPv6 Network ranges.
956
957 """
958 return (self.network_address.is_reserved and
959 self.broadcast_address.is_reserved)
960
961 @property
962 def is_link_local(self):
963 """Test if the address is reserved for link-local.
964
965 Returns:
966 A boolean, True if the address is reserved per RFC 4291.
967
968 """
969 return (self.network_address.is_link_local and
970 self.broadcast_address.is_link_local)
971
972 @property
973 def is_private(self):
974 """Test if this address is allocated for private networks.
975
976 Returns:
977 A boolean, True if the address is reserved per RFC 4193.
978
979 """
980 return (self.network_address.is_private and
981 self.broadcast_address.is_private)
982
983 @property
984 def is_unspecified(self):
985 """Test if the address is unspecified.
986
987 Returns:
988 A boolean, True if this is the unspecified address as defined in
989 RFC 2373 2.5.2.
990
991 """
992 return (self.network_address.is_unspecified and
993 self.broadcast_address.is_unspecified)
994
995 @property
996 def is_loopback(self):
997 """Test if the address is a loopback address.
998
999 Returns:
1000 A boolean, True if the address is a loopback address as defined in
1001 RFC 2373 2.5.3.
1002
1003 """
1004 return (self.network_address.is_loopback and
1005 self.broadcast_address.is_loopback)
1006
Nick Coghlandc9b2552012-05-20 21:01:57 +10001007
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001008class _BaseV4:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001009
1010 """Base IPv4 object.
1011
1012 The following methods are used by IPv4 objects in both single IP
1013 addresses and networks.
1014
1015 """
1016
1017 # Equivalent to 255.255.255.255 or 32 bits of 1's.
1018 _ALL_ONES = (2**IPV4LENGTH) - 1
1019 _DECIMAL_DIGITS = frozenset('0123456789')
1020
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001021 # the valid octets for host and netmasks. only useful for IPv4.
Nick Coghlan7319f692012-07-07 21:43:30 +10001022 _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0))
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001023
Nick Coghlandc9b2552012-05-20 21:01:57 +10001024 def __init__(self, address):
1025 self._version = 4
1026 self._max_prefixlen = IPV4LENGTH
1027
1028 def _explode_shorthand_ip_string(self):
1029 return str(self)
1030
1031 def _ip_int_from_string(self, ip_str):
1032 """Turn the given IP string into an integer for comparison.
1033
1034 Args:
1035 ip_str: A string, the IP ip_str.
1036
1037 Returns:
1038 The IP ip_str as an integer.
1039
1040 Raises:
1041 AddressValueError: if ip_str isn't a valid IPv4 Address.
1042
1043 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001044 if not ip_str:
1045 raise AddressValueError('Address cannot be empty')
1046
Nick Coghlandc9b2552012-05-20 21:01:57 +10001047 octets = ip_str.split('.')
1048 if len(octets) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001049 raise AddressValueError("Expected 4 octets in %r" % ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001050
Nick Coghlan7319f692012-07-07 21:43:30 +10001051 try:
1052 return int.from_bytes(map(self._parse_octet, octets), 'big')
1053 except ValueError as exc:
1054 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001055
1056 def _parse_octet(self, octet_str):
1057 """Convert a decimal octet into an integer.
1058
1059 Args:
1060 octet_str: A string, the number to parse.
1061
1062 Returns:
1063 The octet as an integer.
1064
1065 Raises:
1066 ValueError: if the octet isn't strictly a decimal from [0..255].
1067
1068 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001069 if not octet_str:
1070 raise ValueError("Empty octet not permitted")
Nick Coghlandc9b2552012-05-20 21:01:57 +10001071 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1072 if not self._DECIMAL_DIGITS.issuperset(octet_str):
Nick Coghlan07c4e332012-07-08 23:06:45 +10001073 msg = "Only decimal digits permitted in %r"
1074 raise ValueError(msg % octet_str)
1075 # We do the length check second, since the invalid character error
1076 # is likely to be more informative for the user
1077 if len(octet_str) > 3:
1078 msg = "At most 3 characters permitted in %r"
1079 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001080 # Convert to integer (we know digits are legal)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001081 octet_int = int(octet_str, 10)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001082 # Any octets that look like they *might* be written in octal,
1083 # and which don't look exactly the same in both octal and
1084 # decimal are rejected as ambiguous
1085 if octet_int > 7 and octet_str[0] == '0':
Nick Coghlan07c4e332012-07-08 23:06:45 +10001086 msg = "Ambiguous (octal/decimal) value in %r not permitted"
1087 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001088 if octet_int > 255:
Nick Coghlanb582ecc2012-07-07 22:15:22 +10001089 raise ValueError("Octet %d (> 255) not permitted" % octet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001090 return octet_int
1091
1092 def _string_from_ip_int(self, ip_int):
1093 """Turns a 32-bit integer into dotted decimal notation.
1094
1095 Args:
1096 ip_int: An integer, the IP address.
1097
1098 Returns:
1099 The IP address as a string in dotted decimal notation.
1100
1101 """
Nick Coghlan7319f692012-07-07 21:43:30 +10001102 return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001103
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001104 def _is_valid_netmask(self, netmask):
1105 """Verify that the netmask is valid.
1106
1107 Args:
1108 netmask: A string, either a prefix or dotted decimal
1109 netmask.
1110
1111 Returns:
1112 A boolean, True if the prefix represents a valid IPv4
1113 netmask.
1114
1115 """
1116 mask = netmask.split('.')
1117 if len(mask) == 4:
Nick Coghlan7319f692012-07-07 21:43:30 +10001118 try:
1119 for x in mask:
1120 if int(x) not in self._valid_mask_octets:
1121 return False
1122 except ValueError:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001123 # Found something that isn't an integer or isn't valid
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001124 return False
Nick Coghlan7319f692012-07-07 21:43:30 +10001125 for idx, y in enumerate(mask):
1126 if idx > 0 and y > mask[idx - 1]:
1127 return False
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001128 return True
1129 try:
1130 netmask = int(netmask)
1131 except ValueError:
1132 return False
1133 return 0 <= netmask <= self._max_prefixlen
1134
1135 def _is_hostmask(self, ip_str):
1136 """Test if the IP string is a hostmask (rather than a netmask).
1137
1138 Args:
1139 ip_str: A string, the potential hostmask.
1140
1141 Returns:
1142 A boolean, True if the IP string is a hostmask.
1143
1144 """
1145 bits = ip_str.split('.')
1146 try:
Nick Coghlan7319f692012-07-07 21:43:30 +10001147 parts = [x for x in map(int, bits) if x in self._valid_mask_octets]
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001148 except ValueError:
1149 return False
1150 if len(parts) != len(bits):
1151 return False
1152 if parts[0] < parts[-1]:
1153 return True
1154 return False
1155
Nick Coghlandc9b2552012-05-20 21:01:57 +10001156 @property
1157 def max_prefixlen(self):
1158 return self._max_prefixlen
1159
1160 @property
1161 def version(self):
1162 return self._version
1163
Nick Coghlandc9b2552012-05-20 21:01:57 +10001164
1165class IPv4Address(_BaseV4, _BaseAddress):
1166
1167 """Represent and manipulate single IPv4 Addresses."""
1168
1169 def __init__(self, address):
1170
1171 """
1172 Args:
1173 address: A string or integer representing the IP
1174
1175 Additionally, an integer can be passed, so
1176 IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1177 or, more generally
1178 IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1179 IPv4Address('192.0.2.1')
1180
1181 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001182 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001183
1184 """
1185 _BaseAddress.__init__(self, address)
1186 _BaseV4.__init__(self, address)
1187
1188 # Efficient constructor from integer.
1189 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001190 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001191 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001192 return
1193
1194 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001195 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001196 self._check_packed_address(address, 4)
Nick Coghlandb7920b2012-08-20 10:19:12 +10001197 self._ip = int.from_bytes(address, 'big')
Nick Coghlandc9b2552012-05-20 21:01:57 +10001198 return
1199
1200 # Assume input argument to be string or any object representation
1201 # which converts into a formatted IP string.
1202 addr_str = str(address)
1203 self._ip = self._ip_int_from_string(addr_str)
1204
1205 @property
1206 def packed(self):
1207 """The binary representation of this address."""
1208 return v4_int_to_packed(self._ip)
1209
Nick Coghlan730f67f2012-08-05 22:02:18 +10001210 @property
1211 def is_reserved(self):
1212 """Test if the address is otherwise IETF reserved.
1213
1214 Returns:
1215 A boolean, True if the address is within the
1216 reserved IPv4 Network range.
1217
1218 """
1219 reserved_network = IPv4Network('240.0.0.0/4')
1220 return self in reserved_network
1221
1222 @property
1223 def is_private(self):
1224 """Test if this address is allocated for private networks.
1225
1226 Returns:
1227 A boolean, True if the address is reserved per RFC 1918.
1228
1229 """
1230 private_10 = IPv4Network('10.0.0.0/8')
1231 private_172 = IPv4Network('172.16.0.0/12')
1232 private_192 = IPv4Network('192.168.0.0/16')
1233 return (self in private_10 or
1234 self in private_172 or
1235 self in private_192)
1236
1237 @property
1238 def is_multicast(self):
1239 """Test if the address is reserved for multicast use.
1240
1241 Returns:
1242 A boolean, True if the address is multicast.
1243 See RFC 3171 for details.
1244
1245 """
1246 multicast_network = IPv4Network('224.0.0.0/4')
1247 return self in multicast_network
1248
1249 @property
1250 def is_unspecified(self):
1251 """Test if the address is unspecified.
1252
1253 Returns:
1254 A boolean, True if this is the unspecified address as defined in
1255 RFC 5735 3.
1256
1257 """
1258 unspecified_address = IPv4Address('0.0.0.0')
1259 return self == unspecified_address
1260
1261 @property
1262 def is_loopback(self):
1263 """Test if the address is a loopback address.
1264
1265 Returns:
1266 A boolean, True if the address is a loopback per RFC 3330.
1267
1268 """
1269 loopback_network = IPv4Network('127.0.0.0/8')
1270 return self in loopback_network
1271
1272 @property
1273 def is_link_local(self):
1274 """Test if the address is reserved for link-local.
1275
1276 Returns:
1277 A boolean, True if the address is link-local per RFC 3927.
1278
1279 """
1280 linklocal_network = IPv4Network('169.254.0.0/16')
1281 return self in linklocal_network
1282
Nick Coghlandc9b2552012-05-20 21:01:57 +10001283
1284class IPv4Interface(IPv4Address):
1285
Nick Coghlandc9b2552012-05-20 21:01:57 +10001286 def __init__(self, address):
1287 if isinstance(address, (bytes, int)):
1288 IPv4Address.__init__(self, address)
1289 self.network = IPv4Network(self._ip)
1290 self._prefixlen = self._max_prefixlen
1291 return
1292
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001293 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001294 IPv4Address.__init__(self, addr[0])
1295
1296 self.network = IPv4Network(address, strict=False)
1297 self._prefixlen = self.network._prefixlen
1298
1299 self.netmask = self.network.netmask
1300 self.hostmask = self.network.hostmask
1301
Nick Coghlandc9b2552012-05-20 21:01:57 +10001302 def __str__(self):
1303 return '%s/%d' % (self._string_from_ip_int(self._ip),
1304 self.network.prefixlen)
1305
1306 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001307 address_equal = IPv4Address.__eq__(self, other)
1308 if not address_equal or address_equal is NotImplemented:
1309 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001310 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001311 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001312 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001313 # An interface with an associated network is NOT the
1314 # same as an unassociated address. That's why the hash
1315 # takes the extra info into account.
1316 return False
1317
1318 def __lt__(self, other):
1319 address_less = IPv4Address.__lt__(self, other)
1320 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001321 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001322 try:
1323 return self.network < other.network
1324 except AttributeError:
1325 # We *do* allow addresses and interfaces to be sorted. The
1326 # unassociated address is considered less than all interfaces.
1327 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001328
1329 def __hash__(self):
1330 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1331
Nick Coghlandc9b2552012-05-20 21:01:57 +10001332 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001333 def ip(self):
1334 return IPv4Address(self._ip)
1335
1336 @property
1337 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10001338 return '%s/%s' % (self._string_from_ip_int(self._ip),
1339 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001340
1341 @property
1342 def with_netmask(self):
1343 return '%s/%s' % (self._string_from_ip_int(self._ip),
1344 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001345
Nick Coghlandc9b2552012-05-20 21:01:57 +10001346 @property
1347 def with_hostmask(self):
1348 return '%s/%s' % (self._string_from_ip_int(self._ip),
1349 self.hostmask)
1350
1351
1352class IPv4Network(_BaseV4, _BaseNetwork):
1353
1354 """This class represents and manipulates 32-bit IPv4 network + addresses..
1355
1356 Attributes: [examples for IPv4Network('192.0.2.0/27')]
1357 .network_address: IPv4Address('192.0.2.0')
1358 .hostmask: IPv4Address('0.0.0.31')
1359 .broadcast_address: IPv4Address('192.0.2.32')
1360 .netmask: IPv4Address('255.255.255.224')
1361 .prefixlen: 27
1362
1363 """
Nick Coghlan51c30672012-05-27 00:25:58 +10001364 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001365 _address_class = IPv4Address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001366
Nick Coghlandc9b2552012-05-20 21:01:57 +10001367 def __init__(self, address, strict=True):
1368
1369 """Instantiate a new IPv4 network object.
1370
1371 Args:
1372 address: A string or integer representing the IP [& network].
1373 '192.0.2.0/24'
1374 '192.0.2.0/255.255.255.0'
1375 '192.0.0.2/0.0.0.255'
1376 are all functionally the same in IPv4. Similarly,
1377 '192.0.2.1'
1378 '192.0.2.1/255.255.255.255'
1379 '192.0.2.1/32'
1380 are also functionaly equivalent. That is to say, failing to
1381 provide a subnetmask will create an object with a mask of /32.
1382
1383 If the mask (portion after the / in the argument) is given in
1384 dotted quad form, it is treated as a netmask if it starts with a
1385 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1386 starts with a zero field (e.g. 0.255.255.255 == /8), with the
1387 single exception of an all-zero mask which is treated as a
1388 netmask == /0. If no mask is given, a default of /32 is used.
1389
1390 Additionally, an integer can be passed, so
1391 IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1392 or, more generally
1393 IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1394 IPv4Interface('192.0.2.1')
1395
1396 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001397 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001398 NetmaskValueError: If the netmask isn't valid for
1399 an IPv4 address.
Sandro Tosib4386d32012-06-02 17:14:22 +02001400 ValueError: If strict is True and a network address is not
Nick Coghlandc9b2552012-05-20 21:01:57 +10001401 supplied.
1402
1403 """
1404
1405 _BaseV4.__init__(self, address)
1406 _BaseNetwork.__init__(self, address)
1407
1408 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001409 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001410 self.network_address = IPv4Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001411 self._prefixlen = self._max_prefixlen
1412 self.netmask = IPv4Address(self._ALL_ONES)
1413 #fixme: address/network test here
1414 return
1415
1416 # Efficient constructor from integer.
1417 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001418 self.network_address = IPv4Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001419 self._prefixlen = self._max_prefixlen
1420 self.netmask = IPv4Address(self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001421 #fixme: address/network test here.
1422 return
1423
1424 # Assume input argument to be string or any object representation
1425 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001426 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001427 self.network_address = IPv4Address(self._ip_int_from_string(addr[0]))
1428
Nick Coghlandc9b2552012-05-20 21:01:57 +10001429 if len(addr) == 2:
1430 mask = addr[1].split('.')
1431
1432 if len(mask) == 4:
1433 # We have dotted decimal netmask.
1434 if self._is_valid_netmask(addr[1]):
1435 self.netmask = IPv4Address(self._ip_int_from_string(
1436 addr[1]))
1437 elif self._is_hostmask(addr[1]):
1438 self.netmask = IPv4Address(
1439 self._ip_int_from_string(addr[1]) ^ self._ALL_ONES)
1440 else:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001441 raise NetmaskValueError('%r is not a valid netmask'
Nick Coghlandc9b2552012-05-20 21:01:57 +10001442 % addr[1])
1443
1444 self._prefixlen = self._prefix_from_ip_int(int(self.netmask))
1445 else:
1446 # We have a netmask in prefix length form.
1447 if not self._is_valid_netmask(addr[1]):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001448 raise NetmaskValueError('%r is not a valid netmask'
1449 % addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001450 self._prefixlen = int(addr[1])
1451 self.netmask = IPv4Address(self._ip_int_from_prefix(
1452 self._prefixlen))
1453 else:
1454 self._prefixlen = self._max_prefixlen
1455 self.netmask = IPv4Address(self._ip_int_from_prefix(
1456 self._prefixlen))
1457
1458 if strict:
1459 if (IPv4Address(int(self.network_address) & int(self.netmask)) !=
1460 self.network_address):
1461 raise ValueError('%s has host bits set' % self)
1462 self.network_address = IPv4Address(int(self.network_address) &
1463 int(self.netmask))
1464
1465 if self._prefixlen == (self._max_prefixlen - 1):
1466 self.hosts = self.__iter__
1467
Nick Coghlandc9b2552012-05-20 21:01:57 +10001468
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001469class _BaseV6:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001470
1471 """Base IPv6 object.
1472
1473 The following methods are used by IPv6 objects in both single IP
1474 addresses and networks.
1475
1476 """
1477
1478 _ALL_ONES = (2**IPV6LENGTH) - 1
1479 _HEXTET_COUNT = 8
1480 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
1481
1482 def __init__(self, address):
1483 self._version = 6
1484 self._max_prefixlen = IPV6LENGTH
1485
1486 def _ip_int_from_string(self, ip_str):
1487 """Turn an IPv6 ip_str into an integer.
1488
1489 Args:
1490 ip_str: A string, the IPv6 ip_str.
1491
1492 Returns:
1493 An int, the IPv6 address
1494
1495 Raises:
1496 AddressValueError: if ip_str isn't a valid IPv6 Address.
1497
1498 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001499 if not ip_str:
1500 raise AddressValueError('Address cannot be empty')
1501
Nick Coghlandc9b2552012-05-20 21:01:57 +10001502 parts = ip_str.split(':')
1503
1504 # An IPv6 address needs at least 2 colons (3 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001505 _min_parts = 3
1506 if len(parts) < _min_parts:
1507 msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
1508 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001509
1510 # If the address has an IPv4-style suffix, convert it to hexadecimal.
1511 if '.' in parts[-1]:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001512 try:
1513 ipv4_int = IPv4Address(parts.pop())._ip
1514 except AddressValueError as exc:
1515 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001516 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1517 parts.append('%x' % (ipv4_int & 0xFFFF))
1518
1519 # An IPv6 address can't have more than 8 colons (9 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001520 # The extra colon comes from using the "::" notation for a single
1521 # leading or trailing zero part.
1522 _max_parts = self._HEXTET_COUNT + 1
1523 if len(parts) > _max_parts:
1524 msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
1525 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001526
1527 # Disregarding the endpoints, find '::' with nothing in between.
1528 # This indicates that a run of zeroes has been skipped.
Nick Coghlan7319f692012-07-07 21:43:30 +10001529 skip_index = None
1530 for i in range(1, len(parts) - 1):
1531 if not parts[i]:
1532 if skip_index is not None:
1533 # Can't have more than one '::'
1534 msg = "At most one '::' permitted in %r" % ip_str
1535 raise AddressValueError(msg)
1536 skip_index = i
Nick Coghlandc9b2552012-05-20 21:01:57 +10001537
1538 # parts_hi is the number of parts to copy from above/before the '::'
1539 # parts_lo is the number of parts to copy from below/after the '::'
1540 if skip_index is not None:
1541 # If we found a '::', then check if it also covers the endpoints.
1542 parts_hi = skip_index
1543 parts_lo = len(parts) - skip_index - 1
1544 if not parts[0]:
1545 parts_hi -= 1
1546 if parts_hi:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001547 msg = "Leading ':' only permitted as part of '::' in %r"
1548 raise AddressValueError(msg % ip_str) # ^: requires ^::
Nick Coghlandc9b2552012-05-20 21:01:57 +10001549 if not parts[-1]:
1550 parts_lo -= 1
1551 if parts_lo:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001552 msg = "Trailing ':' only permitted as part of '::' in %r"
1553 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001554 parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo)
1555 if parts_skipped < 1:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001556 msg = "Expected at most %d other parts with '::' in %r"
1557 raise AddressValueError(msg % (self._HEXTET_COUNT-1, ip_str))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001558 else:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001559 # Otherwise, allocate the entire address to parts_hi. The
1560 # endpoints could still be empty, but _parse_hextet() will check
1561 # for that.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001562 if len(parts) != self._HEXTET_COUNT:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001563 msg = "Exactly %d parts expected without '::' in %r"
1564 raise AddressValueError(msg % (self._HEXTET_COUNT, ip_str))
1565 if not parts[0]:
1566 msg = "Leading ':' only permitted as part of '::' in %r"
1567 raise AddressValueError(msg % ip_str) # ^: requires ^::
1568 if not parts[-1]:
1569 msg = "Trailing ':' only permitted as part of '::' in %r"
1570 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001571 parts_hi = len(parts)
1572 parts_lo = 0
1573 parts_skipped = 0
1574
1575 try:
1576 # Now, parse the hextets into a 128-bit integer.
1577 ip_int = 0
1578 for i in range(parts_hi):
1579 ip_int <<= 16
1580 ip_int |= self._parse_hextet(parts[i])
1581 ip_int <<= 16 * parts_skipped
1582 for i in range(-parts_lo, 0):
1583 ip_int <<= 16
1584 ip_int |= self._parse_hextet(parts[i])
1585 return ip_int
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001586 except ValueError as exc:
1587 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001588
1589 def _parse_hextet(self, hextet_str):
1590 """Convert an IPv6 hextet string into an integer.
1591
1592 Args:
1593 hextet_str: A string, the number to parse.
1594
1595 Returns:
1596 The hextet as an integer.
1597
1598 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001599 ValueError: if the input isn't strictly a hex number from
1600 [0..FFFF].
Nick Coghlandc9b2552012-05-20 21:01:57 +10001601
1602 """
1603 # Whitelist the characters, since int() allows a lot of bizarre stuff.
1604 if not self._HEX_DIGITS.issuperset(hextet_str):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001605 raise ValueError("Only hex digits permitted in %r" % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001606 # We do the length check second, since the invalid character error
1607 # is likely to be more informative for the user
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001608 if len(hextet_str) > 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001609 msg = "At most 4 characters permitted in %r"
1610 raise ValueError(msg % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001611 # Length check means we can skip checking the integer value
1612 return int(hextet_str, 16)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001613
1614 def _compress_hextets(self, hextets):
1615 """Compresses a list of hextets.
1616
1617 Compresses a list of strings, replacing the longest continuous
1618 sequence of "0" in the list with "" and adding empty strings at
1619 the beginning or at the end of the string such that subsequently
1620 calling ":".join(hextets) will produce the compressed version of
1621 the IPv6 address.
1622
1623 Args:
1624 hextets: A list of strings, the hextets to compress.
1625
1626 Returns:
1627 A list of strings.
1628
1629 """
1630 best_doublecolon_start = -1
1631 best_doublecolon_len = 0
1632 doublecolon_start = -1
1633 doublecolon_len = 0
Nick Coghlandb7920b2012-08-20 10:19:12 +10001634 for index, hextet in enumerate(hextets):
1635 if hextet == '0':
Nick Coghlandc9b2552012-05-20 21:01:57 +10001636 doublecolon_len += 1
1637 if doublecolon_start == -1:
1638 # Start of a sequence of zeros.
1639 doublecolon_start = index
1640 if doublecolon_len > best_doublecolon_len:
1641 # This is the longest sequence of zeros so far.
1642 best_doublecolon_len = doublecolon_len
1643 best_doublecolon_start = doublecolon_start
1644 else:
1645 doublecolon_len = 0
1646 doublecolon_start = -1
1647
1648 if best_doublecolon_len > 1:
1649 best_doublecolon_end = (best_doublecolon_start +
1650 best_doublecolon_len)
1651 # For zeros at the end of the address.
1652 if best_doublecolon_end == len(hextets):
1653 hextets += ['']
1654 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1655 # For zeros at the beginning of the address.
1656 if best_doublecolon_start == 0:
1657 hextets = [''] + hextets
1658
1659 return hextets
1660
1661 def _string_from_ip_int(self, ip_int=None):
1662 """Turns a 128-bit integer into hexadecimal notation.
1663
1664 Args:
1665 ip_int: An integer, the IP address.
1666
1667 Returns:
1668 A string, the hexadecimal representation of the address.
1669
1670 Raises:
1671 ValueError: The address is bigger than 128 bits of all ones.
1672
1673 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001674 if ip_int is None:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001675 ip_int = int(self._ip)
1676
1677 if ip_int > self._ALL_ONES:
1678 raise ValueError('IPv6 address is too large')
1679
1680 hex_str = '%032x' % ip_int
Nick Coghlan7319f692012-07-07 21:43:30 +10001681 hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001682
1683 hextets = self._compress_hextets(hextets)
1684 return ':'.join(hextets)
1685
1686 def _explode_shorthand_ip_string(self):
1687 """Expand a shortened IPv6 address.
1688
1689 Args:
1690 ip_str: A string, the IPv6 address.
1691
1692 Returns:
1693 A string, the expanded IPv6 address.
1694
1695 """
1696 if isinstance(self, IPv6Network):
1697 ip_str = str(self.network_address)
1698 elif isinstance(self, IPv6Interface):
1699 ip_str = str(self.ip)
1700 else:
1701 ip_str = str(self)
1702
1703 ip_int = self._ip_int_from_string(ip_str)
Nick Coghlan7319f692012-07-07 21:43:30 +10001704 hex_str = '%032x' % ip_int
1705 parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001706 if isinstance(self, (_BaseNetwork, IPv6Interface)):
Nick Coghlane3ded952012-08-05 22:45:22 +10001707 return '%s/%d' % (':'.join(parts), self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001708 return ':'.join(parts)
1709
1710 @property
1711 def max_prefixlen(self):
1712 return self._max_prefixlen
1713
1714 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001715 def version(self):
1716 return self._version
1717
Nick Coghlandc9b2552012-05-20 21:01:57 +10001718
1719class IPv6Address(_BaseV6, _BaseAddress):
1720
Sandro Tosib95c6342012-05-23 23:17:22 +02001721 """Represent and manipulate single IPv6 Addresses."""
Nick Coghlandc9b2552012-05-20 21:01:57 +10001722
1723 def __init__(self, address):
1724 """Instantiate a new IPv6 address object.
1725
1726 Args:
1727 address: A string or integer representing the IP
1728
1729 Additionally, an integer can be passed, so
1730 IPv6Address('2001:db8::') ==
1731 IPv6Address(42540766411282592856903984951653826560)
1732 or, more generally
1733 IPv6Address(int(IPv6Address('2001:db8::'))) ==
1734 IPv6Address('2001:db8::')
1735
1736 Raises:
1737 AddressValueError: If address isn't a valid IPv6 address.
1738
1739 """
1740 _BaseAddress.__init__(self, address)
1741 _BaseV6.__init__(self, address)
1742
1743 # Efficient constructor from integer.
1744 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001745 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001746 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001747 return
1748
1749 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001750 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001751 self._check_packed_address(address, 16)
Nick Coghlandb7920b2012-08-20 10:19:12 +10001752 self._ip = int.from_bytes(address, 'big')
Nick Coghlandc9b2552012-05-20 21:01:57 +10001753 return
1754
1755 # Assume input argument to be string or any object representation
1756 # which converts into a formatted IP string.
1757 addr_str = str(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001758 self._ip = self._ip_int_from_string(addr_str)
1759
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001760 @property
1761 def packed(self):
1762 """The binary representation of this address."""
1763 return v6_int_to_packed(self._ip)
1764
Nick Coghlan730f67f2012-08-05 22:02:18 +10001765 @property
1766 def is_multicast(self):
1767 """Test if the address is reserved for multicast use.
1768
1769 Returns:
1770 A boolean, True if the address is a multicast address.
1771 See RFC 2373 2.7 for details.
1772
1773 """
1774 multicast_network = IPv6Network('ff00::/8')
1775 return self in multicast_network
1776
1777 @property
1778 def is_reserved(self):
1779 """Test if the address is otherwise IETF reserved.
1780
1781 Returns:
1782 A boolean, True if the address is within one of the
1783 reserved IPv6 Network ranges.
1784
1785 """
1786 reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'),
1787 IPv6Network('200::/7'), IPv6Network('400::/6'),
1788 IPv6Network('800::/5'), IPv6Network('1000::/4'),
1789 IPv6Network('4000::/3'), IPv6Network('6000::/3'),
1790 IPv6Network('8000::/3'), IPv6Network('A000::/3'),
1791 IPv6Network('C000::/3'), IPv6Network('E000::/4'),
1792 IPv6Network('F000::/5'), IPv6Network('F800::/6'),
1793 IPv6Network('FE00::/9')]
1794
1795 return any(self in x for x in reserved_networks)
1796
1797 @property
1798 def is_link_local(self):
1799 """Test if the address is reserved for link-local.
1800
1801 Returns:
1802 A boolean, True if the address is reserved per RFC 4291.
1803
1804 """
1805 linklocal_network = IPv6Network('fe80::/10')
1806 return self in linklocal_network
1807
1808 @property
1809 def is_site_local(self):
1810 """Test if the address is reserved for site-local.
1811
1812 Note that the site-local address space has been deprecated by RFC 3879.
1813 Use is_private to test if this address is in the space of unique local
1814 addresses as defined by RFC 4193.
1815
1816 Returns:
1817 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1818
1819 """
1820 sitelocal_network = IPv6Network('fec0::/10')
1821 return self in sitelocal_network
1822
1823 @property
1824 def is_private(self):
1825 """Test if this address is allocated for private networks.
1826
1827 Returns:
1828 A boolean, True if the address is reserved per RFC 4193.
1829
1830 """
1831 private_network = IPv6Network('fc00::/7')
1832 return self in private_network
1833
1834 @property
1835 def is_unspecified(self):
1836 """Test if the address is unspecified.
1837
1838 Returns:
1839 A boolean, True if this is the unspecified address as defined in
1840 RFC 2373 2.5.2.
1841
1842 """
1843 return self._ip == 0
1844
1845 @property
1846 def is_loopback(self):
1847 """Test if the address is a loopback address.
1848
1849 Returns:
1850 A boolean, True if the address is a loopback address as defined in
1851 RFC 2373 2.5.3.
1852
1853 """
1854 return self._ip == 1
1855
1856 @property
1857 def ipv4_mapped(self):
1858 """Return the IPv4 mapped address.
1859
1860 Returns:
1861 If the IPv6 address is a v4 mapped address, return the
1862 IPv4 mapped address. Return None otherwise.
1863
1864 """
1865 if (self._ip >> 32) != 0xFFFF:
1866 return None
1867 return IPv4Address(self._ip & 0xFFFFFFFF)
1868
1869 @property
1870 def teredo(self):
1871 """Tuple of embedded teredo IPs.
1872
1873 Returns:
1874 Tuple of the (server, client) IPs or None if the address
1875 doesn't appear to be a teredo address (doesn't start with
1876 2001::/32)
1877
1878 """
1879 if (self._ip >> 96) != 0x20010000:
1880 return None
1881 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
1882 IPv4Address(~self._ip & 0xFFFFFFFF))
1883
1884 @property
1885 def sixtofour(self):
1886 """Return the IPv4 6to4 embedded address.
1887
1888 Returns:
1889 The IPv4 6to4-embedded address if present or None if the
1890 address doesn't appear to contain a 6to4 embedded address.
1891
1892 """
1893 if (self._ip >> 112) != 0x2002:
1894 return None
1895 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
1896
Nick Coghlandc9b2552012-05-20 21:01:57 +10001897
1898class IPv6Interface(IPv6Address):
1899
1900 def __init__(self, address):
1901 if isinstance(address, (bytes, int)):
1902 IPv6Address.__init__(self, address)
1903 self.network = IPv6Network(self._ip)
1904 self._prefixlen = self._max_prefixlen
1905 return
1906
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001907 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001908 IPv6Address.__init__(self, addr[0])
1909 self.network = IPv6Network(address, strict=False)
1910 self.netmask = self.network.netmask
1911 self._prefixlen = self.network._prefixlen
1912 self.hostmask = self.network.hostmask
1913
Nick Coghlandc9b2552012-05-20 21:01:57 +10001914 def __str__(self):
1915 return '%s/%d' % (self._string_from_ip_int(self._ip),
1916 self.network.prefixlen)
1917
1918 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001919 address_equal = IPv6Address.__eq__(self, other)
1920 if not address_equal or address_equal is NotImplemented:
1921 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001922 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001923 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001924 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001925 # An interface with an associated network is NOT the
1926 # same as an unassociated address. That's why the hash
1927 # takes the extra info into account.
1928 return False
1929
1930 def __lt__(self, other):
1931 address_less = IPv6Address.__lt__(self, other)
1932 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001933 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001934 try:
1935 return self.network < other.network
1936 except AttributeError:
1937 # We *do* allow addresses and interfaces to be sorted. The
1938 # unassociated address is considered less than all interfaces.
1939 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001940
1941 def __hash__(self):
1942 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1943
1944 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001945 def ip(self):
1946 return IPv6Address(self._ip)
1947
1948 @property
1949 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10001950 return '%s/%s' % (self._string_from_ip_int(self._ip),
1951 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001952
1953 @property
1954 def with_netmask(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10001955 return '%s/%s' % (self._string_from_ip_int(self._ip),
1956 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001957
Nick Coghlandc9b2552012-05-20 21:01:57 +10001958 @property
1959 def with_hostmask(self):
1960 return '%s/%s' % (self._string_from_ip_int(self._ip),
1961 self.hostmask)
1962
Nick Coghlan730f67f2012-08-05 22:02:18 +10001963 @property
1964 def is_unspecified(self):
1965 return self._ip == 0 and self.network.is_unspecified
1966
1967 @property
1968 def is_loopback(self):
1969 return self._ip == 1 and self.network.is_loopback
1970
Nick Coghlandc9b2552012-05-20 21:01:57 +10001971
1972class IPv6Network(_BaseV6, _BaseNetwork):
1973
1974 """This class represents and manipulates 128-bit IPv6 networks.
1975
1976 Attributes: [examples for IPv6('2001:db8::1000/124')]
1977 .network_address: IPv6Address('2001:db8::1000')
1978 .hostmask: IPv6Address('::f')
1979 .broadcast_address: IPv6Address('2001:db8::100f')
1980 .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
1981 .prefixlen: 124
1982
1983 """
1984
Nick Coghlan51c30672012-05-27 00:25:58 +10001985 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001986 _address_class = IPv6Address
1987
Nick Coghlandc9b2552012-05-20 21:01:57 +10001988 def __init__(self, address, strict=True):
1989 """Instantiate a new IPv6 Network object.
1990
1991 Args:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001992 address: A string or integer representing the IPv6 network or the
1993 IP and prefix/netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001994 '2001:db8::/128'
1995 '2001:db8:0000:0000:0000:0000:0000:0000/128'
1996 '2001:db8::'
1997 are all functionally the same in IPv6. That is to say,
1998 failing to provide a subnetmask will create an object with
1999 a mask of /128.
2000
2001 Additionally, an integer can be passed, so
2002 IPv6Network('2001:db8::') ==
2003 IPv6Network(42540766411282592856903984951653826560)
2004 or, more generally
2005 IPv6Network(int(IPv6Network('2001:db8::'))) ==
2006 IPv6Network('2001:db8::')
2007
2008 strict: A boolean. If true, ensure that we have been passed
2009 A true network address, eg, 2001:db8::1000/124 and not an
2010 IP address on a network, eg, 2001:db8::1/124.
2011
2012 Raises:
2013 AddressValueError: If address isn't a valid IPv6 address.
2014 NetmaskValueError: If the netmask isn't valid for
2015 an IPv6 address.
2016 ValueError: If strict was True and a network address was not
2017 supplied.
2018
2019 """
2020 _BaseV6.__init__(self, address)
2021 _BaseNetwork.__init__(self, address)
2022
2023 # Efficient constructor from integer.
2024 if isinstance(address, int):
Nick Coghlandc9b2552012-05-20 21:01:57 +10002025 self.network_address = IPv6Address(address)
2026 self._prefixlen = self._max_prefixlen
2027 self.netmask = IPv6Address(self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002028 return
2029
2030 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10002031 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10002032 self.network_address = IPv6Address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002033 self._prefixlen = self._max_prefixlen
2034 self.netmask = IPv6Address(self._ALL_ONES)
Hynek Schlawacked36b2e2012-06-08 15:21:21 +02002035 return
Nick Coghlandc9b2552012-05-20 21:01:57 +10002036
2037 # Assume input argument to be string or any object representation
2038 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002039 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002040
2041 self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))
2042
2043 if len(addr) == 2:
2044 if self._is_valid_netmask(addr[1]):
2045 self._prefixlen = int(addr[1])
2046 else:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002047 raise NetmaskValueError('%r is not a valid netmask'
2048 % addr[1])
Nick Coghlandc9b2552012-05-20 21:01:57 +10002049 else:
2050 self._prefixlen = self._max_prefixlen
2051
2052 self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen))
2053 if strict:
2054 if (IPv6Address(int(self.network_address) & int(self.netmask)) !=
2055 self.network_address):
Nick Coghlan912238e2012-07-07 13:34:50 +10002056 raise ValueError('%s has host bits set' % self)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002057 self.network_address = IPv6Address(int(self.network_address) &
2058 int(self.netmask))
2059
2060 if self._prefixlen == (self._max_prefixlen - 1):
2061 self.hosts = self.__iter__
2062
Nick Coghlandc9b2552012-05-20 21:01:57 +10002063 def _is_valid_netmask(self, prefixlen):
2064 """Verify that the netmask/prefixlen is valid.
2065
2066 Args:
2067 prefixlen: A string, the netmask in prefix length format.
2068
2069 Returns:
2070 A boolean, True if the prefix represents a valid IPv6
2071 netmask.
2072
2073 """
2074 try:
2075 prefixlen = int(prefixlen)
2076 except ValueError:
2077 return False
2078 return 0 <= prefixlen <= self._max_prefixlen
Nick Coghlan730f67f2012-08-05 22:02:18 +10002079
2080 @property
2081 def is_site_local(self):
2082 """Test if the address is reserved for site-local.
2083
2084 Note that the site-local address space has been deprecated by RFC 3879.
2085 Use is_private to test if this address is in the space of unique local
2086 addresses as defined by RFC 4193.
2087
2088 Returns:
2089 A boolean, True if the address is reserved per RFC 3513 2.5.6.
2090
2091 """
2092 return (self.network_address.is_site_local and
2093 self.broadcast_address.is_site_local)