blob: 4f02d520f128de8890c7766c8c002f98090f85bc [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
Antoine Pitrou824db302014-05-15 20:21:48 +0200198 return min(bits, (~number & (number-1)).bit_length())
Nick Coghlandc9b2552012-05-20 21:01:57 +1000199
200
201def summarize_address_range(first, last):
202 """Summarize a network range given the first and last IP addresses.
203
204 Example:
Eli Bendersky948af232012-10-07 07:23:50 -0700205 >>> list(summarize_address_range(IPv4Address('192.0.2.0'),
206 ... IPv4Address('192.0.2.130')))
207 ... #doctest: +NORMALIZE_WHITESPACE
Nick Coghlandc9b2552012-05-20 21:01:57 +1000208 [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'),
Eli Bendersky948af232012-10-07 07:23:50 -0700209 IPv4Network('192.0.2.130/32')]
Nick Coghlandc9b2552012-05-20 21:01:57 +1000210
211 Args:
212 first: the first IPv4Address or IPv6Address in the range.
213 last: the last IPv4Address or IPv6Address in the range.
214
215 Returns:
216 An iterator of the summarized IPv(4|6) network objects.
217
218 Raise:
219 TypeError:
220 If the first and last objects are not IP addresses.
221 If the first and last objects are not the same version.
222 ValueError:
223 If the last object is not greater than the first.
Nick Coghlan51c30672012-05-27 00:25:58 +1000224 If the version of the first address is not 4 or 6.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000225
226 """
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200227 if (not (isinstance(first, _BaseAddress) and
228 isinstance(last, _BaseAddress))):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000229 raise TypeError('first and last must be IP addresses, not networks')
230 if first.version != last.version:
231 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000232 first, last))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000233 if first > last:
234 raise ValueError('last IP address must be greater than first')
235
Nick Coghlandc9b2552012-05-20 21:01:57 +1000236 if first.version == 4:
237 ip = IPv4Network
238 elif first.version == 6:
239 ip = IPv6Network
240 else:
241 raise ValueError('unknown IP version')
242
243 ip_bits = first._max_prefixlen
244 first_int = first._ip
245 last_int = last._ip
246 while first_int <= last_int:
Nick Coghlan7319f692012-07-07 21:43:30 +1000247 nbits = min(_count_righthand_zero_bits(first_int, ip_bits),
248 (last_int - first_int + 1).bit_length() - 1)
Antoine Pitrou824db302014-05-15 20:21:48 +0200249 net = ip((first_int, ip_bits - nbits))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000250 yield net
Nick Coghlan7319f692012-07-07 21:43:30 +1000251 first_int += 1 << nbits
252 if first_int - 1 == ip._ALL_ONES:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000253 break
Nick Coghlandc9b2552012-05-20 21:01:57 +1000254
Sandro Tosib95c6342012-05-23 23:17:22 +0200255
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200256def _collapse_addresses_internal(addresses):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000257 """Loops through the addresses, collapsing concurrent netblocks.
258
259 Example:
260
261 ip1 = IPv4Network('192.0.2.0/26')
262 ip2 = IPv4Network('192.0.2.64/26')
263 ip3 = IPv4Network('192.0.2.128/26')
264 ip4 = IPv4Network('192.0.2.192/26')
265
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200266 _collapse_addresses_internal([ip1, ip2, ip3, ip4]) ->
Nick Coghlandc9b2552012-05-20 21:01:57 +1000267 [IPv4Network('192.0.2.0/24')]
268
269 This shouldn't be called directly; it is called via
270 collapse_addresses([]).
271
272 Args:
273 addresses: A list of IPv4Network's or IPv6Network's
274
275 Returns:
276 A list of IPv4Network's or IPv6Network's depending on what we were
277 passed.
278
279 """
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200280 # First merge
281 to_merge = list(addresses)
282 subnets = {}
283 while to_merge:
284 net = to_merge.pop()
285 supernet = net.supernet()
286 existing = subnets.get(supernet)
287 if existing is None:
288 subnets[supernet] = net
289 elif existing != net:
290 # Merge consecutive subnets
291 del subnets[supernet]
292 to_merge.append(supernet)
293 # Then iterate over resulting networks, skipping subsumed subnets
294 last = None
295 for net in sorted(subnets.values()):
296 if last is not None:
297 # Since they are sorted, last.network_address <= net.network_address
298 # is a given.
299 if last.broadcast_address >= net.broadcast_address:
300 continue
301 yield net
302 last = net
Nick Coghlandc9b2552012-05-20 21:01:57 +1000303
304
305def collapse_addresses(addresses):
306 """Collapse a list of IP objects.
307
308 Example:
309 collapse_addresses([IPv4Network('192.0.2.0/25'),
310 IPv4Network('192.0.2.128/25')]) ->
311 [IPv4Network('192.0.2.0/24')]
312
313 Args:
314 addresses: An iterator of IPv4Network or IPv6Network objects.
315
316 Returns:
317 An iterator of the collapsed IPv(4|6)Network objects.
318
319 Raises:
320 TypeError: If passed a list of mixed version objects.
321
322 """
323 i = 0
324 addrs = []
325 ips = []
326 nets = []
327
328 # split IP addresses and networks
329 for ip in addresses:
330 if isinstance(ip, _BaseAddress):
331 if ips and ips[-1]._version != ip._version:
332 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000333 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000334 ips.append(ip)
335 elif ip._prefixlen == ip._max_prefixlen:
336 if ips and ips[-1]._version != ip._version:
337 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000338 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000339 try:
340 ips.append(ip.ip)
341 except AttributeError:
342 ips.append(ip.network_address)
343 else:
344 if nets and nets[-1]._version != ip._version:
345 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000346 ip, nets[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000347 nets.append(ip)
348
349 # sort and dedup
350 ips = sorted(set(ips))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000351
352 while i < len(ips):
353 (first, last) = _find_address_range(ips[i:])
354 i = ips.index(last) + 1
355 addrs.extend(summarize_address_range(first, last))
356
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200357 return _collapse_addresses_internal(addrs + nets)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000358
359
360def get_mixed_type_key(obj):
361 """Return a key suitable for sorting between networks and addresses.
362
363 Address and Network objects are not sortable by default; they're
364 fundamentally different so the expression
365
366 IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
367
368 doesn't make any sense. There are some times however, where you may wish
369 to have ipaddress sort these for you anyway. If you need to do this, you
370 can use this function as the key= argument to sorted().
371
372 Args:
373 obj: either a Network or Address object.
374 Returns:
375 appropriate key.
376
377 """
378 if isinstance(obj, _BaseNetwork):
379 return obj._get_networks_key()
380 elif isinstance(obj, _BaseAddress):
381 return obj._get_address_key()
382 return NotImplemented
383
384
Nick Coghlan3008ec02012-07-08 00:45:33 +1000385class _TotalOrderingMixin:
386 # Helper that derives the other comparison operations from
387 # __lt__ and __eq__
Nick Coghlan297b1432012-07-08 17:11:04 +1000388 # We avoid functools.total_ordering because it doesn't handle
389 # NotImplemented correctly yet (http://bugs.python.org/issue10042)
Nick Coghlan3008ec02012-07-08 00:45:33 +1000390 def __eq__(self, other):
391 raise NotImplementedError
392 def __ne__(self, other):
393 equal = self.__eq__(other)
394 if equal is NotImplemented:
395 return NotImplemented
396 return not equal
397 def __lt__(self, other):
398 raise NotImplementedError
399 def __le__(self, other):
400 less = self.__lt__(other)
401 if less is NotImplemented or not less:
402 return self.__eq__(other)
403 return less
404 def __gt__(self, other):
405 less = self.__lt__(other)
406 if less is NotImplemented:
407 return NotImplemented
408 equal = self.__eq__(other)
409 if equal is NotImplemented:
410 return NotImplemented
411 return not (less or equal)
412 def __ge__(self, other):
413 less = self.__lt__(other)
414 if less is NotImplemented:
415 return NotImplemented
416 return not less
417
418class _IPAddressBase(_TotalOrderingMixin):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000419
420 """The mother class."""
421
422 @property
423 def exploded(self):
424 """Return the longhand version of the IP address as a string."""
425 return self._explode_shorthand_ip_string()
426
427 @property
428 def compressed(self):
429 """Return the shorthand version of the IP address as a string."""
430 return str(self)
431
Nick Coghland9722652012-06-17 16:33:00 +1000432 @property
Eric V. Smithebdaaf42014-04-14 12:58:07 -0400433 def reverse_pointer(self):
434 """The name of the reverse DNS pointer for the IP address, e.g.:
435 >>> ipaddress.ip_address("127.0.0.1").reverse_pointer
436 '1.0.0.127.in-addr.arpa'
437 >>> ipaddress.ip_address("2001:db8::1").reverse_pointer
438 '1.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.0.8.b.d.0.1.0.0.2.ip6.arpa'
439
440 """
441 return self._reverse_pointer()
442
443 @property
Nick Coghland9722652012-06-17 16:33:00 +1000444 def version(self):
445 msg = '%200s has no version specified' % (type(self),)
446 raise NotImplementedError(msg)
447
Nick Coghlan297b1432012-07-08 17:11:04 +1000448 def _check_int_address(self, address):
449 if address < 0:
450 msg = "%d (< 0) is not permitted as an IPv%d address"
451 raise AddressValueError(msg % (address, self._version))
452 if address > self._ALL_ONES:
453 msg = "%d (>= 2**%d) is not permitted as an IPv%d address"
454 raise AddressValueError(msg % (address, self._max_prefixlen,
455 self._version))
456
457 def _check_packed_address(self, address, expected_len):
458 address_len = len(address)
459 if address_len != expected_len:
460 msg = "%r (len %d != %d) is not permitted as an IPv%d address"
461 raise AddressValueError(msg % (address, address_len,
462 expected_len, self._version))
463
Antoine Pitrou45aba182014-05-15 20:18:41 +0200464 @classmethod
465 def _ip_int_from_prefix(cls, prefixlen):
Nick Coghlan932346f2014-02-08 23:17:36 +1000466 """Turn the prefix length into a bitwise netmask
Nick Coghlandc9b2552012-05-20 21:01:57 +1000467
468 Args:
469 prefixlen: An integer, the prefix length.
470
471 Returns:
472 An integer.
473
474 """
Antoine Pitrou45aba182014-05-15 20:18:41 +0200475 return cls._ALL_ONES ^ (cls._ALL_ONES >> prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000476
Antoine Pitrou45aba182014-05-15 20:18:41 +0200477 @classmethod
478 def _prefix_from_ip_int(cls, ip_int):
Nick Coghlan932346f2014-02-08 23:17:36 +1000479 """Return prefix length from the bitwise netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000480
481 Args:
Nick Coghlan932346f2014-02-08 23:17:36 +1000482 ip_int: An integer, the netmask in axpanded bitwise format
Nick Coghlandc9b2552012-05-20 21:01:57 +1000483
484 Returns:
485 An integer, the prefix length.
486
Nick Coghlan932346f2014-02-08 23:17:36 +1000487 Raises:
488 ValueError: If the input intermingles zeroes & ones
Nick Coghlandc9b2552012-05-20 21:01:57 +1000489 """
Nick Coghlan932346f2014-02-08 23:17:36 +1000490 trailing_zeroes = _count_righthand_zero_bits(ip_int,
Antoine Pitrou45aba182014-05-15 20:18:41 +0200491 cls._max_prefixlen)
492 prefixlen = cls._max_prefixlen - trailing_zeroes
Nick Coghlan932346f2014-02-08 23:17:36 +1000493 leading_ones = ip_int >> trailing_zeroes
494 all_ones = (1 << prefixlen) - 1
495 if leading_ones != all_ones:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200496 byteslen = cls._max_prefixlen // 8
Nick Coghlan932346f2014-02-08 23:17:36 +1000497 details = ip_int.to_bytes(byteslen, 'big')
498 msg = 'Netmask pattern %r mixes zeroes & ones'
499 raise ValueError(msg % details)
500 return prefixlen
Nick Coghlandc9b2552012-05-20 21:01:57 +1000501
Antoine Pitrou45aba182014-05-15 20:18:41 +0200502 @classmethod
503 def _report_invalid_netmask(cls, netmask_str):
Nick Coghlan932346f2014-02-08 23:17:36 +1000504 msg = '%r is not a valid netmask' % netmask_str
505 raise NetmaskValueError(msg) from None
506
Antoine Pitrou45aba182014-05-15 20:18:41 +0200507 @classmethod
508 def _prefix_from_prefix_string(cls, prefixlen_str):
Nick Coghlan932346f2014-02-08 23:17:36 +1000509 """Return prefix length from a numeric string
Nick Coghlandc9b2552012-05-20 21:01:57 +1000510
511 Args:
Nick Coghlan932346f2014-02-08 23:17:36 +1000512 prefixlen_str: The string to be converted
Nick Coghlandc9b2552012-05-20 21:01:57 +1000513
514 Returns:
Nick Coghlan932346f2014-02-08 23:17:36 +1000515 An integer, the prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000516
Nick Coghlan932346f2014-02-08 23:17:36 +1000517 Raises:
518 NetmaskValueError: If the input is not a valid netmask
Nick Coghlandc9b2552012-05-20 21:01:57 +1000519 """
Nick Coghlan932346f2014-02-08 23:17:36 +1000520 # int allows a leading +/- as well as surrounding whitespace,
521 # so we ensure that isn't the case
522 if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
Antoine Pitrou45aba182014-05-15 20:18:41 +0200523 cls._report_invalid_netmask(prefixlen_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000524 try:
525 prefixlen = int(prefixlen_str)
526 except ValueError:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200527 cls._report_invalid_netmask(prefixlen_str)
528 if not (0 <= prefixlen <= cls._max_prefixlen):
529 cls._report_invalid_netmask(prefixlen_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000530 return prefixlen
531
Antoine Pitrou45aba182014-05-15 20:18:41 +0200532 @classmethod
533 def _prefix_from_ip_string(cls, ip_str):
Nick Coghlan932346f2014-02-08 23:17:36 +1000534 """Turn a netmask/hostmask string into a prefix length
535
536 Args:
537 ip_str: The netmask/hostmask to be converted
538
539 Returns:
540 An integer, the prefix length.
541
542 Raises:
543 NetmaskValueError: If the input is not a valid netmask/hostmask
544 """
545 # Parse the netmask/hostmask like an IP address.
546 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200547 ip_int = cls._ip_int_from_string(ip_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000548 except AddressValueError:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200549 cls._report_invalid_netmask(ip_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000550
551 # Try matching a netmask (this would be /1*0*/ as a bitwise regexp).
552 # Note that the two ambiguous cases (all-ones and all-zeroes) are
553 # treated as netmasks.
554 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200555 return cls._prefix_from_ip_int(ip_int)
Nick Coghlan932346f2014-02-08 23:17:36 +1000556 except ValueError:
557 pass
558
559 # Invert the bits, and try matching a /0+1+/ hostmask instead.
Antoine Pitrou45aba182014-05-15 20:18:41 +0200560 ip_int ^= cls._ALL_ONES
Nick Coghlan932346f2014-02-08 23:17:36 +1000561 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200562 return cls._prefix_from_ip_int(ip_int)
Nick Coghlan932346f2014-02-08 23:17:36 +1000563 except ValueError:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200564 cls._report_invalid_netmask(ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000565
Nick Coghlan730f67f2012-08-05 22:02:18 +1000566
Nick Coghlandc9b2552012-05-20 21:01:57 +1000567class _BaseAddress(_IPAddressBase):
568
569 """A generic IP object.
570
571 This IP class contains the version independent methods which are
572 used by single IP addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000573 """
574
575 def __init__(self, address):
576 if (not isinstance(address, bytes)
577 and '/' in str(address)):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +1000578 raise AddressValueError("Unexpected '/' in %r" % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000579
Nick Coghlandc9b2552012-05-20 21:01:57 +1000580 def __int__(self):
581 return self._ip
582
Nick Coghlandc9b2552012-05-20 21:01:57 +1000583 def __eq__(self, other):
584 try:
585 return (self._ip == other._ip
586 and self._version == other._version)
587 except AttributeError:
588 return NotImplemented
589
Nick Coghlandc9b2552012-05-20 21:01:57 +1000590 def __lt__(self, other):
591 if self._version != other._version:
592 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000593 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000594 if not isinstance(other, _BaseAddress):
595 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000596 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000597 if self._ip != other._ip:
598 return self._ip < other._ip
599 return False
600
Nick Coghlandc9b2552012-05-20 21:01:57 +1000601 # Shorthand for Integer addition and subtraction. This is not
602 # meant to ever support addition/subtraction of addresses.
603 def __add__(self, other):
604 if not isinstance(other, int):
605 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000606 return self.__class__(int(self) + other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000607
608 def __sub__(self, other):
609 if not isinstance(other, int):
610 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000611 return self.__class__(int(self) - other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000612
613 def __repr__(self):
614 return '%s(%r)' % (self.__class__.__name__, str(self))
615
616 def __str__(self):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200617 return str(self._string_from_ip_int(self._ip))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000618
619 def __hash__(self):
620 return hash(hex(int(self._ip)))
621
622 def _get_address_key(self):
623 return (self._version, self)
624
Nick Coghlandc9b2552012-05-20 21:01:57 +1000625
626class _BaseNetwork(_IPAddressBase):
627
Nick Coghlan51c30672012-05-27 00:25:58 +1000628 """A generic IP network object.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000629
630 This IP class contains the version independent methods which are
631 used by networks.
632
633 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000634 def __init__(self, address):
635 self._cache = {}
636
Nick Coghlandc9b2552012-05-20 21:01:57 +1000637 def __repr__(self):
638 return '%s(%r)' % (self.__class__.__name__, str(self))
639
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200640 def __str__(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000641 return '%s/%d' % (self.network_address, self.prefixlen)
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200642
Nick Coghlandc9b2552012-05-20 21:01:57 +1000643 def hosts(self):
644 """Generate Iterator over usable hosts in a network.
645
Sandro Tosib95c6342012-05-23 23:17:22 +0200646 This is like __iter__ except it doesn't return the network
647 or broadcast addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000648
649 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000650 network = int(self.network_address)
651 broadcast = int(self.broadcast_address)
652 for x in range(network + 1, broadcast):
653 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000654
655 def __iter__(self):
Nick Coghlan7319f692012-07-07 21:43:30 +1000656 network = int(self.network_address)
657 broadcast = int(self.broadcast_address)
658 for x in range(network, broadcast + 1):
659 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000660
661 def __getitem__(self, n):
662 network = int(self.network_address)
663 broadcast = int(self.broadcast_address)
664 if n >= 0:
665 if network + n > broadcast:
666 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000667 return self._address_class(network + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000668 else:
669 n += 1
670 if broadcast + n < network:
671 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000672 return self._address_class(broadcast + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000673
674 def __lt__(self, other):
675 if self._version != other._version:
676 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000677 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000678 if not isinstance(other, _BaseNetwork):
679 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000680 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000681 if self.network_address != other.network_address:
682 return self.network_address < other.network_address
683 if self.netmask != other.netmask:
684 return self.netmask < other.netmask
685 return False
686
Nick Coghlandc9b2552012-05-20 21:01:57 +1000687 def __eq__(self, other):
Nick Coghlan9a9c28c2012-07-07 23:05:59 +1000688 try:
689 return (self._version == other._version and
690 self.network_address == other.network_address and
691 int(self.netmask) == int(other.netmask))
692 except AttributeError:
693 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000694
Nick Coghlandc9b2552012-05-20 21:01:57 +1000695 def __hash__(self):
696 return hash(int(self.network_address) ^ int(self.netmask))
697
698 def __contains__(self, other):
699 # always false if one is v4 and the other is v6.
700 if self._version != other._version:
701 return False
702 # dealing with another network.
703 if isinstance(other, _BaseNetwork):
704 return False
705 # dealing with another address
706 else:
707 # address
708 return (int(self.network_address) <= int(other._ip) <=
709 int(self.broadcast_address))
710
711 def overlaps(self, other):
712 """Tell if self is partly contained in other."""
713 return self.network_address in other or (
714 self.broadcast_address in other or (
715 other.network_address in self or (
716 other.broadcast_address in self)))
717
718 @property
719 def broadcast_address(self):
720 x = self._cache.get('broadcast_address')
721 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000722 x = self._address_class(int(self.network_address) |
723 int(self.hostmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000724 self._cache['broadcast_address'] = x
725 return x
726
727 @property
728 def hostmask(self):
729 x = self._cache.get('hostmask')
730 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000731 x = self._address_class(int(self.netmask) ^ self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000732 self._cache['hostmask'] = x
733 return x
734
735 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000736 def with_prefixlen(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000737 return '%s/%d' % (self.network_address, self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000738
739 @property
740 def with_netmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000741 return '%s/%s' % (self.network_address, self.netmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000742
743 @property
744 def with_hostmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000745 return '%s/%s' % (self.network_address, self.hostmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000746
747 @property
748 def num_addresses(self):
749 """Number of hosts in the current subnet."""
750 return int(self.broadcast_address) - int(self.network_address) + 1
751
752 @property
Nick Coghlan51c30672012-05-27 00:25:58 +1000753 def _address_class(self):
Nick Coghland9722652012-06-17 16:33:00 +1000754 # Returning bare address objects (rather than interfaces) allows for
755 # more consistent behaviour across the network address, broadcast
756 # address and individual host addresses.
757 msg = '%200s has no associated address class' % (type(self),)
758 raise NotImplementedError(msg)
Nick Coghlan51c30672012-05-27 00:25:58 +1000759
760 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000761 def prefixlen(self):
762 return self._prefixlen
763
764 def address_exclude(self, other):
765 """Remove an address from a larger block.
766
767 For example:
768
769 addr1 = ip_network('192.0.2.0/28')
770 addr2 = ip_network('192.0.2.1/32')
771 addr1.address_exclude(addr2) =
772 [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
773 IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
774
775 or IPv6:
776
777 addr1 = ip_network('2001:db8::1/32')
778 addr2 = ip_network('2001:db8::1/128')
779 addr1.address_exclude(addr2) =
780 [ip_network('2001:db8::1/128'),
781 ip_network('2001:db8::2/127'),
782 ip_network('2001:db8::4/126'),
783 ip_network('2001:db8::8/125'),
784 ...
785 ip_network('2001:db8:8000::/33')]
786
787 Args:
788 other: An IPv4Network or IPv6Network object of the same type.
789
790 Returns:
Ezio Melotti3f5db392013-01-27 06:20:14 +0200791 An iterator of the IPv(4|6)Network objects which is self
Nick Coghlandc9b2552012-05-20 21:01:57 +1000792 minus other.
793
794 Raises:
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300795 TypeError: If self and other are of differing address
Nick Coghlandc9b2552012-05-20 21:01:57 +1000796 versions, or if other is not a network object.
797 ValueError: If other is not completely contained by self.
798
799 """
800 if not self._version == other._version:
801 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000802 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000803
804 if not isinstance(other, _BaseNetwork):
Nick Coghlan912238e2012-07-07 13:34:50 +1000805 raise TypeError("%s is not a network object" % other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000806
807 if not (other.network_address >= self.network_address and
808 other.broadcast_address <= self.broadcast_address):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200809 raise ValueError('%s not contained in %s' % (other, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000810 if other == self:
811 raise StopIteration
812
Nick Coghlandc9b2552012-05-20 21:01:57 +1000813 # Make sure we're comparing the network of other.
Nick Coghlan912238e2012-07-07 13:34:50 +1000814 other = other.__class__('%s/%s' % (other.network_address,
815 other.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000816
817 s1, s2 = self.subnets()
818 while s1 != other and s2 != other:
819 if (other.network_address >= s1.network_address and
820 other.broadcast_address <= s1.broadcast_address):
821 yield s2
822 s1, s2 = s1.subnets()
823 elif (other.network_address >= s2.network_address and
824 other.broadcast_address <= s2.broadcast_address):
825 yield s1
826 s1, s2 = s2.subnets()
827 else:
828 # If we got here, there's a bug somewhere.
829 raise AssertionError('Error performing exclusion: '
830 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000831 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000832 if s1 == other:
833 yield s2
834 elif s2 == other:
835 yield s1
836 else:
837 # If we got here, there's a bug somewhere.
838 raise AssertionError('Error performing exclusion: '
839 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000840 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000841
842 def compare_networks(self, other):
843 """Compare two IP objects.
844
845 This is only concerned about the comparison of the integer
846 representation of the network addresses. This means that the
847 host bits aren't considered at all in this method. If you want
848 to compare host bits, you can easily enough do a
849 'HostA._ip < HostB._ip'
850
851 Args:
852 other: An IP object.
853
854 Returns:
855 If the IP versions of self and other are the same, returns:
856
857 -1 if self < other:
858 eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
859 IPv6Network('2001:db8::1000/124') <
860 IPv6Network('2001:db8::2000/124')
861 0 if self == other
862 eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
863 IPv6Network('2001:db8::1000/124') ==
864 IPv6Network('2001:db8::1000/124')
865 1 if self > other
866 eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
867 IPv6Network('2001:db8::2000/124') >
868 IPv6Network('2001:db8::1000/124')
869
870 Raises:
871 TypeError if the IP versions are different.
872
873 """
874 # does this need to raise a ValueError?
875 if self._version != other._version:
876 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000877 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000878 # self._version == other._version below here:
879 if self.network_address < other.network_address:
880 return -1
881 if self.network_address > other.network_address:
882 return 1
883 # self.network_address == other.network_address below here:
884 if self.netmask < other.netmask:
885 return -1
886 if self.netmask > other.netmask:
887 return 1
888 return 0
889
890 def _get_networks_key(self):
891 """Network-only key function.
892
893 Returns an object that identifies this address' network and
894 netmask. This function is a suitable "key" argument for sorted()
895 and list.sort().
896
897 """
898 return (self._version, self.network_address, self.netmask)
899
900 def subnets(self, prefixlen_diff=1, new_prefix=None):
901 """The subnets which join to make the current subnet.
902
903 In the case that self contains only one IP
904 (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
905 for IPv6), yield an iterator with just ourself.
906
907 Args:
908 prefixlen_diff: An integer, the amount the prefix length
909 should be increased by. This should not be set if
910 new_prefix is also set.
911 new_prefix: The desired new prefix length. This must be a
912 larger number (smaller prefix) than the existing prefix.
913 This should not be set if prefixlen_diff is also set.
914
915 Returns:
916 An iterator of IPv(4|6) objects.
917
918 Raises:
919 ValueError: The prefixlen_diff is too small or too large.
920 OR
921 prefixlen_diff and new_prefix are both set or new_prefix
922 is a smaller number than the current prefix (smaller
923 number means a larger network)
924
925 """
926 if self._prefixlen == self._max_prefixlen:
927 yield self
928 return
929
930 if new_prefix is not None:
931 if new_prefix < self._prefixlen:
932 raise ValueError('new prefix must be longer')
933 if prefixlen_diff != 1:
934 raise ValueError('cannot set prefixlen_diff and new_prefix')
935 prefixlen_diff = new_prefix - self._prefixlen
936
937 if prefixlen_diff < 0:
938 raise ValueError('prefix length diff must be > 0')
939 new_prefixlen = self._prefixlen + prefixlen_diff
940
Nick Coghlan932346f2014-02-08 23:17:36 +1000941 if new_prefixlen > self._max_prefixlen:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000942 raise ValueError(
943 'prefix length diff %d is invalid for netblock %s' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000944 new_prefixlen, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000945
Antoine Pitrou824db302014-05-15 20:21:48 +0200946 start = int(self.network_address)
947 end = int(self.broadcast_address)
948 step = (int(self.hostmask) + 1) >> prefixlen_diff
949 for new_addr in range(start, end, step):
950 current = self.__class__((new_addr, new_prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000951 yield current
952
Nick Coghlandc9b2552012-05-20 21:01:57 +1000953 def supernet(self, prefixlen_diff=1, new_prefix=None):
954 """The supernet containing the current network.
955
956 Args:
957 prefixlen_diff: An integer, the amount the prefix length of
958 the network should be decreased by. For example, given a
959 /24 network and a prefixlen_diff of 3, a supernet with a
960 /21 netmask is returned.
961
962 Returns:
963 An IPv4 network object.
964
965 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200966 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
967 a negative prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000968 OR
969 If prefixlen_diff and new_prefix are both set or new_prefix is a
970 larger number than the current prefix (larger number means a
971 smaller network)
972
973 """
974 if self._prefixlen == 0:
975 return self
976
977 if new_prefix is not None:
978 if new_prefix > self._prefixlen:
979 raise ValueError('new prefix must be shorter')
980 if prefixlen_diff != 1:
981 raise ValueError('cannot set prefixlen_diff and new_prefix')
982 prefixlen_diff = self._prefixlen - new_prefix
983
Antoine Pitrou5fb195f2014-05-12 20:36:46 +0200984 new_prefixlen = self.prefixlen - prefixlen_diff
985 if new_prefixlen < 0:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000986 raise ValueError(
987 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
988 (self.prefixlen, prefixlen_diff))
Antoine Pitrou5fb195f2014-05-12 20:36:46 +0200989 return self.__class__((
990 int(self.network_address) & (int(self.netmask) << prefixlen_diff),
991 new_prefixlen
992 ))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000993
Nick Coghlan730f67f2012-08-05 22:02:18 +1000994 @property
995 def is_multicast(self):
996 """Test if the address is reserved for multicast use.
997
998 Returns:
999 A boolean, True if the address is a multicast address.
1000 See RFC 2373 2.7 for details.
1001
1002 """
1003 return (self.network_address.is_multicast and
1004 self.broadcast_address.is_multicast)
1005
1006 @property
1007 def is_reserved(self):
1008 """Test if the address is otherwise IETF reserved.
1009
1010 Returns:
1011 A boolean, True if the address is within one of the
1012 reserved IPv6 Network ranges.
1013
1014 """
1015 return (self.network_address.is_reserved and
1016 self.broadcast_address.is_reserved)
1017
1018 @property
1019 def is_link_local(self):
1020 """Test if the address is reserved for link-local.
1021
1022 Returns:
1023 A boolean, True if the address is reserved per RFC 4291.
1024
1025 """
1026 return (self.network_address.is_link_local and
1027 self.broadcast_address.is_link_local)
1028
1029 @property
1030 def is_private(self):
1031 """Test if this address is allocated for private networks.
1032
1033 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001034 A boolean, True if the address is reserved per
1035 iana-ipv4-special-registry or iana-ipv6-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001036
1037 """
1038 return (self.network_address.is_private and
1039 self.broadcast_address.is_private)
1040
1041 @property
Peter Moody22c31762013-10-21 13:58:06 -07001042 def is_global(self):
Peter Moodybe9c1b12013-10-22 12:36:21 -07001043 """Test if this address is allocated for public networks.
Peter Moody22c31762013-10-21 13:58:06 -07001044
1045 Returns:
1046 A boolean, True if the address is not reserved per
1047 iana-ipv4-special-registry or iana-ipv6-special-registry.
1048
1049 """
1050 return not self.is_private
1051
1052 @property
Nick Coghlan730f67f2012-08-05 22:02:18 +10001053 def is_unspecified(self):
1054 """Test if the address is unspecified.
1055
1056 Returns:
1057 A boolean, True if this is the unspecified address as defined in
1058 RFC 2373 2.5.2.
1059
1060 """
1061 return (self.network_address.is_unspecified and
1062 self.broadcast_address.is_unspecified)
1063
1064 @property
1065 def is_loopback(self):
1066 """Test if the address is a loopback address.
1067
1068 Returns:
1069 A boolean, True if the address is a loopback address as defined in
1070 RFC 2373 2.5.3.
1071
1072 """
1073 return (self.network_address.is_loopback and
1074 self.broadcast_address.is_loopback)
1075
Nick Coghlandc9b2552012-05-20 21:01:57 +10001076
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001077class _BaseV4:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001078
1079 """Base IPv4 object.
1080
1081 The following methods are used by IPv4 objects in both single IP
1082 addresses and networks.
1083
1084 """
1085
1086 # Equivalent to 255.255.255.255 or 32 bits of 1's.
1087 _ALL_ONES = (2**IPV4LENGTH) - 1
1088 _DECIMAL_DIGITS = frozenset('0123456789')
1089
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001090 # the valid octets for host and netmasks. only useful for IPv4.
Nick Coghlan7319f692012-07-07 21:43:30 +10001091 _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0))
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001092
Antoine Pitrou45aba182014-05-15 20:18:41 +02001093 _max_prefixlen = IPV4LENGTH
1094 # There are only a handful of valid v4 netmasks, so we cache them all
1095 # when constructed (see _make_netmask()).
1096 _netmask_cache = {}
1097
Nick Coghlandc9b2552012-05-20 21:01:57 +10001098 def __init__(self, address):
1099 self._version = 4
Nick Coghlandc9b2552012-05-20 21:01:57 +10001100
1101 def _explode_shorthand_ip_string(self):
1102 return str(self)
1103
Antoine Pitrou45aba182014-05-15 20:18:41 +02001104 @classmethod
1105 def _make_netmask(cls, arg):
1106 """Make a (netmask, prefix_len) tuple from the given argument.
1107
1108 Argument can be:
1109 - an integer (the prefix length)
1110 - a string representing the prefix length (e.g. "24")
1111 - a string representing the prefix netmask (e.g. "255.255.255.0")
1112 """
1113 if arg not in cls._netmask_cache:
1114 if isinstance(arg, int):
1115 prefixlen = arg
1116 else:
1117 try:
1118 # Check for a netmask in prefix length form
1119 prefixlen = cls._prefix_from_prefix_string(arg)
1120 except NetmaskValueError:
1121 # Check for a netmask or hostmask in dotted-quad form.
1122 # This may raise NetmaskValueError.
1123 prefixlen = cls._prefix_from_ip_string(arg)
1124 netmask = IPv4Address(cls._ip_int_from_prefix(prefixlen))
1125 cls._netmask_cache[arg] = netmask, prefixlen
1126 return cls._netmask_cache[arg]
1127
1128 @classmethod
1129 def _ip_int_from_string(cls, ip_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001130 """Turn the given IP string into an integer for comparison.
1131
1132 Args:
1133 ip_str: A string, the IP ip_str.
1134
1135 Returns:
1136 The IP ip_str as an integer.
1137
1138 Raises:
1139 AddressValueError: if ip_str isn't a valid IPv4 Address.
1140
1141 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001142 if not ip_str:
1143 raise AddressValueError('Address cannot be empty')
1144
Nick Coghlandc9b2552012-05-20 21:01:57 +10001145 octets = ip_str.split('.')
1146 if len(octets) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001147 raise AddressValueError("Expected 4 octets in %r" % ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001148
Nick Coghlan7319f692012-07-07 21:43:30 +10001149 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001150 return int.from_bytes(map(cls._parse_octet, octets), 'big')
Nick Coghlan7319f692012-07-07 21:43:30 +10001151 except ValueError as exc:
1152 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001153
Antoine Pitrou45aba182014-05-15 20:18:41 +02001154 @classmethod
1155 def _parse_octet(cls, octet_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001156 """Convert a decimal octet into an integer.
1157
1158 Args:
1159 octet_str: A string, the number to parse.
1160
1161 Returns:
1162 The octet as an integer.
1163
1164 Raises:
1165 ValueError: if the octet isn't strictly a decimal from [0..255].
1166
1167 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001168 if not octet_str:
1169 raise ValueError("Empty octet not permitted")
Nick Coghlandc9b2552012-05-20 21:01:57 +10001170 # Whitelist the characters, since int() allows a lot of bizarre stuff.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001171 if not cls._DECIMAL_DIGITS.issuperset(octet_str):
Nick Coghlan07c4e332012-07-08 23:06:45 +10001172 msg = "Only decimal digits permitted in %r"
1173 raise ValueError(msg % octet_str)
1174 # We do the length check second, since the invalid character error
1175 # is likely to be more informative for the user
1176 if len(octet_str) > 3:
1177 msg = "At most 3 characters permitted in %r"
1178 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001179 # Convert to integer (we know digits are legal)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001180 octet_int = int(octet_str, 10)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001181 # Any octets that look like they *might* be written in octal,
1182 # and which don't look exactly the same in both octal and
1183 # decimal are rejected as ambiguous
1184 if octet_int > 7 and octet_str[0] == '0':
Nick Coghlan07c4e332012-07-08 23:06:45 +10001185 msg = "Ambiguous (octal/decimal) value in %r not permitted"
1186 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001187 if octet_int > 255:
Nick Coghlanb582ecc2012-07-07 22:15:22 +10001188 raise ValueError("Octet %d (> 255) not permitted" % octet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001189 return octet_int
1190
Antoine Pitrou45aba182014-05-15 20:18:41 +02001191 @classmethod
1192 def _string_from_ip_int(cls, ip_int):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001193 """Turns a 32-bit integer into dotted decimal notation.
1194
1195 Args:
1196 ip_int: An integer, the IP address.
1197
1198 Returns:
1199 The IP address as a string in dotted decimal notation.
1200
1201 """
Nick Coghlan7319f692012-07-07 21:43:30 +10001202 return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001203
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001204 def _is_valid_netmask(self, netmask):
1205 """Verify that the netmask is valid.
1206
1207 Args:
1208 netmask: A string, either a prefix or dotted decimal
1209 netmask.
1210
1211 Returns:
1212 A boolean, True if the prefix represents a valid IPv4
1213 netmask.
1214
1215 """
1216 mask = netmask.split('.')
1217 if len(mask) == 4:
Nick Coghlan7319f692012-07-07 21:43:30 +10001218 try:
1219 for x in mask:
1220 if int(x) not in self._valid_mask_octets:
1221 return False
1222 except ValueError:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001223 # Found something that isn't an integer or isn't valid
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001224 return False
Nick Coghlan7319f692012-07-07 21:43:30 +10001225 for idx, y in enumerate(mask):
1226 if idx > 0 and y > mask[idx - 1]:
1227 return False
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001228 return True
1229 try:
1230 netmask = int(netmask)
1231 except ValueError:
1232 return False
1233 return 0 <= netmask <= self._max_prefixlen
1234
1235 def _is_hostmask(self, ip_str):
1236 """Test if the IP string is a hostmask (rather than a netmask).
1237
1238 Args:
1239 ip_str: A string, the potential hostmask.
1240
1241 Returns:
1242 A boolean, True if the IP string is a hostmask.
1243
1244 """
1245 bits = ip_str.split('.')
1246 try:
Nick Coghlan7319f692012-07-07 21:43:30 +10001247 parts = [x for x in map(int, bits) if x in self._valid_mask_octets]
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001248 except ValueError:
1249 return False
1250 if len(parts) != len(bits):
1251 return False
1252 if parts[0] < parts[-1]:
1253 return True
1254 return False
1255
Eric V. Smithebdaaf42014-04-14 12:58:07 -04001256 def _reverse_pointer(self):
1257 """Return the reverse DNS pointer name for the IPv4 address.
1258
1259 This implements the method described in RFC1035 3.5.
1260
1261 """
1262 reverse_octets = str(self).split('.')[::-1]
1263 return '.'.join(reverse_octets) + '.in-addr.arpa'
1264
Nick Coghlandc9b2552012-05-20 21:01:57 +10001265 @property
1266 def max_prefixlen(self):
1267 return self._max_prefixlen
1268
1269 @property
1270 def version(self):
1271 return self._version
1272
Nick Coghlandc9b2552012-05-20 21:01:57 +10001273
1274class IPv4Address(_BaseV4, _BaseAddress):
1275
1276 """Represent and manipulate single IPv4 Addresses."""
1277
1278 def __init__(self, address):
1279
1280 """
1281 Args:
1282 address: A string or integer representing the IP
1283
1284 Additionally, an integer can be passed, so
1285 IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1286 or, more generally
1287 IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1288 IPv4Address('192.0.2.1')
1289
1290 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001291 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001292
1293 """
1294 _BaseAddress.__init__(self, address)
1295 _BaseV4.__init__(self, address)
1296
1297 # Efficient constructor from integer.
1298 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001299 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001300 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001301 return
1302
1303 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001304 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001305 self._check_packed_address(address, 4)
Nick Coghlandb7920b2012-08-20 10:19:12 +10001306 self._ip = int.from_bytes(address, 'big')
Nick Coghlandc9b2552012-05-20 21:01:57 +10001307 return
1308
1309 # Assume input argument to be string or any object representation
1310 # which converts into a formatted IP string.
1311 addr_str = str(address)
1312 self._ip = self._ip_int_from_string(addr_str)
1313
1314 @property
1315 def packed(self):
1316 """The binary representation of this address."""
1317 return v4_int_to_packed(self._ip)
1318
Nick Coghlan730f67f2012-08-05 22:02:18 +10001319 @property
1320 def is_reserved(self):
1321 """Test if the address is otherwise IETF reserved.
1322
1323 Returns:
1324 A boolean, True if the address is within the
1325 reserved IPv4 Network range.
1326
1327 """
1328 reserved_network = IPv4Network('240.0.0.0/4')
1329 return self in reserved_network
1330
1331 @property
Peter Moodybe9c1b12013-10-22 12:36:21 -07001332 @functools.lru_cache()
Nick Coghlan730f67f2012-08-05 22:02:18 +10001333 def is_private(self):
1334 """Test if this address is allocated for private networks.
1335
1336 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001337 A boolean, True if the address is reserved per
1338 iana-ipv4-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001339
1340 """
Peter Moody22c31762013-10-21 13:58:06 -07001341 return (self in IPv4Network('0.0.0.0/8') or
1342 self in IPv4Network('10.0.0.0/8') or
Peter Moody22c31762013-10-21 13:58:06 -07001343 self in IPv4Network('127.0.0.0/8') or
1344 self in IPv4Network('169.254.0.0/16') or
1345 self in IPv4Network('172.16.0.0/12') or
1346 self in IPv4Network('192.0.0.0/29') or
1347 self in IPv4Network('192.0.0.170/31') or
1348 self in IPv4Network('192.0.2.0/24') or
1349 self in IPv4Network('192.168.0.0/16') or
1350 self in IPv4Network('198.18.0.0/15') or
1351 self in IPv4Network('198.51.100.0/24') or
1352 self in IPv4Network('203.0.113.0/24') or
1353 self in IPv4Network('240.0.0.0/4') or
1354 self in IPv4Network('255.255.255.255/32'))
1355
Nick Coghlan730f67f2012-08-05 22:02:18 +10001356
1357 @property
1358 def is_multicast(self):
1359 """Test if the address is reserved for multicast use.
1360
1361 Returns:
1362 A boolean, True if the address is multicast.
1363 See RFC 3171 for details.
1364
1365 """
1366 multicast_network = IPv4Network('224.0.0.0/4')
1367 return self in multicast_network
1368
1369 @property
1370 def is_unspecified(self):
1371 """Test if the address is unspecified.
1372
1373 Returns:
1374 A boolean, True if this is the unspecified address as defined in
1375 RFC 5735 3.
1376
1377 """
1378 unspecified_address = IPv4Address('0.0.0.0')
1379 return self == unspecified_address
1380
1381 @property
1382 def is_loopback(self):
1383 """Test if the address is a loopback address.
1384
1385 Returns:
1386 A boolean, True if the address is a loopback per RFC 3330.
1387
1388 """
1389 loopback_network = IPv4Network('127.0.0.0/8')
1390 return self in loopback_network
1391
1392 @property
1393 def is_link_local(self):
1394 """Test if the address is reserved for link-local.
1395
1396 Returns:
1397 A boolean, True if the address is link-local per RFC 3927.
1398
1399 """
1400 linklocal_network = IPv4Network('169.254.0.0/16')
1401 return self in linklocal_network
1402
Nick Coghlandc9b2552012-05-20 21:01:57 +10001403
1404class IPv4Interface(IPv4Address):
1405
Nick Coghlandc9b2552012-05-20 21:01:57 +10001406 def __init__(self, address):
1407 if isinstance(address, (bytes, int)):
1408 IPv4Address.__init__(self, address)
1409 self.network = IPv4Network(self._ip)
1410 self._prefixlen = self._max_prefixlen
1411 return
1412
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001413 if isinstance(address, tuple):
1414 IPv4Address.__init__(self, address[0])
1415 if len(address) > 1:
1416 self._prefixlen = int(address[1])
1417 else:
1418 self._prefixlen = self._max_prefixlen
1419
1420 self.network = IPv4Network(address, strict=False)
1421 self.netmask = self.network.netmask
1422 self.hostmask = self.network.hostmask
1423 return
1424
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001425 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001426 IPv4Address.__init__(self, addr[0])
1427
1428 self.network = IPv4Network(address, strict=False)
1429 self._prefixlen = self.network._prefixlen
1430
1431 self.netmask = self.network.netmask
1432 self.hostmask = self.network.hostmask
1433
Nick Coghlandc9b2552012-05-20 21:01:57 +10001434 def __str__(self):
1435 return '%s/%d' % (self._string_from_ip_int(self._ip),
1436 self.network.prefixlen)
1437
1438 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001439 address_equal = IPv4Address.__eq__(self, other)
1440 if not address_equal or address_equal is NotImplemented:
1441 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001442 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001443 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001444 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001445 # An interface with an associated network is NOT the
1446 # same as an unassociated address. That's why the hash
1447 # takes the extra info into account.
1448 return False
1449
1450 def __lt__(self, other):
1451 address_less = IPv4Address.__lt__(self, other)
1452 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001453 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001454 try:
1455 return self.network < other.network
1456 except AttributeError:
1457 # We *do* allow addresses and interfaces to be sorted. The
1458 # unassociated address is considered less than all interfaces.
1459 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001460
1461 def __hash__(self):
1462 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1463
Nick Coghlandc9b2552012-05-20 21:01:57 +10001464 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001465 def ip(self):
1466 return IPv4Address(self._ip)
1467
1468 @property
1469 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10001470 return '%s/%s' % (self._string_from_ip_int(self._ip),
1471 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001472
1473 @property
1474 def with_netmask(self):
1475 return '%s/%s' % (self._string_from_ip_int(self._ip),
1476 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001477
Nick Coghlandc9b2552012-05-20 21:01:57 +10001478 @property
1479 def with_hostmask(self):
1480 return '%s/%s' % (self._string_from_ip_int(self._ip),
1481 self.hostmask)
1482
1483
1484class IPv4Network(_BaseV4, _BaseNetwork):
1485
1486 """This class represents and manipulates 32-bit IPv4 network + addresses..
1487
1488 Attributes: [examples for IPv4Network('192.0.2.0/27')]
1489 .network_address: IPv4Address('192.0.2.0')
1490 .hostmask: IPv4Address('0.0.0.31')
1491 .broadcast_address: IPv4Address('192.0.2.32')
1492 .netmask: IPv4Address('255.255.255.224')
1493 .prefixlen: 27
1494
1495 """
Nick Coghlan51c30672012-05-27 00:25:58 +10001496 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001497 _address_class = IPv4Address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001498
Nick Coghlandc9b2552012-05-20 21:01:57 +10001499 def __init__(self, address, strict=True):
1500
1501 """Instantiate a new IPv4 network object.
1502
1503 Args:
1504 address: A string or integer representing the IP [& network].
1505 '192.0.2.0/24'
1506 '192.0.2.0/255.255.255.0'
1507 '192.0.0.2/0.0.0.255'
1508 are all functionally the same in IPv4. Similarly,
1509 '192.0.2.1'
1510 '192.0.2.1/255.255.255.255'
1511 '192.0.2.1/32'
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001512 are also functionally equivalent. That is to say, failing to
Nick Coghlandc9b2552012-05-20 21:01:57 +10001513 provide a subnetmask will create an object with a mask of /32.
1514
1515 If the mask (portion after the / in the argument) is given in
1516 dotted quad form, it is treated as a netmask if it starts with a
1517 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1518 starts with a zero field (e.g. 0.255.255.255 == /8), with the
1519 single exception of an all-zero mask which is treated as a
1520 netmask == /0. If no mask is given, a default of /32 is used.
1521
1522 Additionally, an integer can be passed, so
1523 IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1524 or, more generally
1525 IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1526 IPv4Interface('192.0.2.1')
1527
1528 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001529 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001530 NetmaskValueError: If the netmask isn't valid for
1531 an IPv4 address.
Sandro Tosib4386d32012-06-02 17:14:22 +02001532 ValueError: If strict is True and a network address is not
Nick Coghlandc9b2552012-05-20 21:01:57 +10001533 supplied.
1534
1535 """
1536
1537 _BaseV4.__init__(self, address)
1538 _BaseNetwork.__init__(self, address)
1539
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001540 # Constructing from a packed address or integer
1541 if isinstance(address, (int, bytes)):
Nick Coghlan297b1432012-07-08 17:11:04 +10001542 self.network_address = IPv4Address(address)
Antoine Pitrou45aba182014-05-15 20:18:41 +02001543 self.netmask, self._prefixlen = self._make_netmask(self._max_prefixlen)
1544 #fixme: address/network test here.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001545 return
1546
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001547 if isinstance(address, tuple):
1548 if len(address) > 1:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001549 arg = address[1]
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001550 else:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001551 # We weren't given an address[1]
1552 arg = self._max_prefixlen
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001553 self.network_address = IPv4Address(address[0])
Antoine Pitrou45aba182014-05-15 20:18:41 +02001554 self.netmask, self._prefixlen = self._make_netmask(arg)
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001555 packed = int(self.network_address)
1556 if packed & int(self.netmask) != packed:
1557 if strict:
1558 raise ValueError('%s has host bits set' % self)
1559 else:
1560 self.network_address = IPv4Address(packed &
1561 int(self.netmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001562 return
1563
1564 # Assume input argument to be string or any object representation
1565 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001566 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001567 self.network_address = IPv4Address(self._ip_int_from_string(addr[0]))
1568
Nick Coghlandc9b2552012-05-20 21:01:57 +10001569 if len(addr) == 2:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001570 arg = addr[1]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001571 else:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001572 arg = self._max_prefixlen
1573 self.netmask, self._prefixlen = self._make_netmask(arg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001574
1575 if strict:
1576 if (IPv4Address(int(self.network_address) & int(self.netmask)) !=
1577 self.network_address):
1578 raise ValueError('%s has host bits set' % self)
1579 self.network_address = IPv4Address(int(self.network_address) &
1580 int(self.netmask))
1581
1582 if self._prefixlen == (self._max_prefixlen - 1):
1583 self.hosts = self.__iter__
1584
Peter Moodye5019d52013-10-24 09:47:10 -07001585 @property
1586 @functools.lru_cache()
1587 def is_global(self):
1588 """Test if this address is allocated for public networks.
1589
1590 Returns:
1591 A boolean, True if the address is not reserved per
1592 iana-ipv4-special-registry.
1593
1594 """
1595 return (not (self.network_address in IPv4Network('100.64.0.0/10') and
1596 self.broadcast_address in IPv4Network('100.64.0.0/10')) and
1597 not self.is_private)
1598
1599
Nick Coghlandc9b2552012-05-20 21:01:57 +10001600
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001601class _BaseV6:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001602
1603 """Base IPv6 object.
1604
1605 The following methods are used by IPv6 objects in both single IP
1606 addresses and networks.
1607
1608 """
1609
1610 _ALL_ONES = (2**IPV6LENGTH) - 1
1611 _HEXTET_COUNT = 8
1612 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
Antoine Pitrou45aba182014-05-15 20:18:41 +02001613 _max_prefixlen = IPV6LENGTH
1614
1615 # There are only a bunch of valid v6 netmasks, so we cache them all
1616 # when constructed (see _make_netmask()).
1617 _netmask_cache = {}
Nick Coghlandc9b2552012-05-20 21:01:57 +10001618
1619 def __init__(self, address):
1620 self._version = 6
Nick Coghlandc9b2552012-05-20 21:01:57 +10001621
Antoine Pitrou45aba182014-05-15 20:18:41 +02001622 @classmethod
1623 def _make_netmask(cls, arg):
1624 """Make a (netmask, prefix_len) tuple from the given argument.
1625
1626 Argument can be:
1627 - an integer (the prefix length)
1628 - a string representing the prefix length (e.g. "24")
1629 - a string representing the prefix netmask (e.g. "255.255.255.0")
1630 """
1631 if arg not in cls._netmask_cache:
1632 if isinstance(arg, int):
1633 prefixlen = arg
1634 else:
1635 prefixlen = cls._prefix_from_prefix_string(arg)
1636 netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen))
1637 cls._netmask_cache[arg] = netmask, prefixlen
1638 return cls._netmask_cache[arg]
1639
1640 @classmethod
1641 def _ip_int_from_string(cls, ip_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001642 """Turn an IPv6 ip_str into an integer.
1643
1644 Args:
1645 ip_str: A string, the IPv6 ip_str.
1646
1647 Returns:
1648 An int, the IPv6 address
1649
1650 Raises:
1651 AddressValueError: if ip_str isn't a valid IPv6 Address.
1652
1653 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001654 if not ip_str:
1655 raise AddressValueError('Address cannot be empty')
1656
Nick Coghlandc9b2552012-05-20 21:01:57 +10001657 parts = ip_str.split(':')
1658
1659 # An IPv6 address needs at least 2 colons (3 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001660 _min_parts = 3
1661 if len(parts) < _min_parts:
1662 msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
1663 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001664
1665 # If the address has an IPv4-style suffix, convert it to hexadecimal.
1666 if '.' in parts[-1]:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001667 try:
1668 ipv4_int = IPv4Address(parts.pop())._ip
1669 except AddressValueError as exc:
1670 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001671 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1672 parts.append('%x' % (ipv4_int & 0xFFFF))
1673
1674 # An IPv6 address can't have more than 8 colons (9 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001675 # The extra colon comes from using the "::" notation for a single
1676 # leading or trailing zero part.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001677 _max_parts = cls._HEXTET_COUNT + 1
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001678 if len(parts) > _max_parts:
1679 msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
1680 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001681
1682 # Disregarding the endpoints, find '::' with nothing in between.
1683 # This indicates that a run of zeroes has been skipped.
Nick Coghlan7319f692012-07-07 21:43:30 +10001684 skip_index = None
1685 for i in range(1, len(parts) - 1):
1686 if not parts[i]:
1687 if skip_index is not None:
1688 # Can't have more than one '::'
1689 msg = "At most one '::' permitted in %r" % ip_str
1690 raise AddressValueError(msg)
1691 skip_index = i
Nick Coghlandc9b2552012-05-20 21:01:57 +10001692
1693 # parts_hi is the number of parts to copy from above/before the '::'
1694 # parts_lo is the number of parts to copy from below/after the '::'
1695 if skip_index is not None:
1696 # If we found a '::', then check if it also covers the endpoints.
1697 parts_hi = skip_index
1698 parts_lo = len(parts) - skip_index - 1
1699 if not parts[0]:
1700 parts_hi -= 1
1701 if parts_hi:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001702 msg = "Leading ':' only permitted as part of '::' in %r"
1703 raise AddressValueError(msg % ip_str) # ^: requires ^::
Nick Coghlandc9b2552012-05-20 21:01:57 +10001704 if not parts[-1]:
1705 parts_lo -= 1
1706 if parts_lo:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001707 msg = "Trailing ':' only permitted as part of '::' in %r"
1708 raise AddressValueError(msg % ip_str) # :$ requires ::$
Antoine Pitrou45aba182014-05-15 20:18:41 +02001709 parts_skipped = cls._HEXTET_COUNT - (parts_hi + parts_lo)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001710 if parts_skipped < 1:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001711 msg = "Expected at most %d other parts with '::' in %r"
Antoine Pitrou45aba182014-05-15 20:18:41 +02001712 raise AddressValueError(msg % (cls._HEXTET_COUNT-1, ip_str))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001713 else:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001714 # Otherwise, allocate the entire address to parts_hi. The
1715 # endpoints could still be empty, but _parse_hextet() will check
1716 # for that.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001717 if len(parts) != cls._HEXTET_COUNT:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001718 msg = "Exactly %d parts expected without '::' in %r"
Antoine Pitrou45aba182014-05-15 20:18:41 +02001719 raise AddressValueError(msg % (cls._HEXTET_COUNT, ip_str))
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001720 if not parts[0]:
1721 msg = "Leading ':' only permitted as part of '::' in %r"
1722 raise AddressValueError(msg % ip_str) # ^: requires ^::
1723 if not parts[-1]:
1724 msg = "Trailing ':' only permitted as part of '::' in %r"
1725 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001726 parts_hi = len(parts)
1727 parts_lo = 0
1728 parts_skipped = 0
1729
1730 try:
1731 # Now, parse the hextets into a 128-bit integer.
1732 ip_int = 0
1733 for i in range(parts_hi):
1734 ip_int <<= 16
Antoine Pitrou45aba182014-05-15 20:18:41 +02001735 ip_int |= cls._parse_hextet(parts[i])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001736 ip_int <<= 16 * parts_skipped
1737 for i in range(-parts_lo, 0):
1738 ip_int <<= 16
Antoine Pitrou45aba182014-05-15 20:18:41 +02001739 ip_int |= cls._parse_hextet(parts[i])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001740 return ip_int
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001741 except ValueError as exc:
1742 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001743
Antoine Pitrou45aba182014-05-15 20:18:41 +02001744 @classmethod
1745 def _parse_hextet(cls, hextet_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001746 """Convert an IPv6 hextet string into an integer.
1747
1748 Args:
1749 hextet_str: A string, the number to parse.
1750
1751 Returns:
1752 The hextet as an integer.
1753
1754 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001755 ValueError: if the input isn't strictly a hex number from
1756 [0..FFFF].
Nick Coghlandc9b2552012-05-20 21:01:57 +10001757
1758 """
1759 # Whitelist the characters, since int() allows a lot of bizarre stuff.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001760 if not cls._HEX_DIGITS.issuperset(hextet_str):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001761 raise ValueError("Only hex digits permitted in %r" % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001762 # We do the length check second, since the invalid character error
1763 # is likely to be more informative for the user
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001764 if len(hextet_str) > 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001765 msg = "At most 4 characters permitted in %r"
1766 raise ValueError(msg % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001767 # Length check means we can skip checking the integer value
1768 return int(hextet_str, 16)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001769
Antoine Pitrou45aba182014-05-15 20:18:41 +02001770 @classmethod
1771 def _compress_hextets(cls, hextets):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001772 """Compresses a list of hextets.
1773
1774 Compresses a list of strings, replacing the longest continuous
1775 sequence of "0" in the list with "" and adding empty strings at
1776 the beginning or at the end of the string such that subsequently
1777 calling ":".join(hextets) will produce the compressed version of
1778 the IPv6 address.
1779
1780 Args:
1781 hextets: A list of strings, the hextets to compress.
1782
1783 Returns:
1784 A list of strings.
1785
1786 """
1787 best_doublecolon_start = -1
1788 best_doublecolon_len = 0
1789 doublecolon_start = -1
1790 doublecolon_len = 0
Nick Coghlandb7920b2012-08-20 10:19:12 +10001791 for index, hextet in enumerate(hextets):
1792 if hextet == '0':
Nick Coghlandc9b2552012-05-20 21:01:57 +10001793 doublecolon_len += 1
1794 if doublecolon_start == -1:
1795 # Start of a sequence of zeros.
1796 doublecolon_start = index
1797 if doublecolon_len > best_doublecolon_len:
1798 # This is the longest sequence of zeros so far.
1799 best_doublecolon_len = doublecolon_len
1800 best_doublecolon_start = doublecolon_start
1801 else:
1802 doublecolon_len = 0
1803 doublecolon_start = -1
1804
1805 if best_doublecolon_len > 1:
1806 best_doublecolon_end = (best_doublecolon_start +
1807 best_doublecolon_len)
1808 # For zeros at the end of the address.
1809 if best_doublecolon_end == len(hextets):
1810 hextets += ['']
1811 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1812 # For zeros at the beginning of the address.
1813 if best_doublecolon_start == 0:
1814 hextets = [''] + hextets
1815
1816 return hextets
1817
Antoine Pitrou45aba182014-05-15 20:18:41 +02001818 @classmethod
1819 def _string_from_ip_int(cls, ip_int=None):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001820 """Turns a 128-bit integer into hexadecimal notation.
1821
1822 Args:
1823 ip_int: An integer, the IP address.
1824
1825 Returns:
1826 A string, the hexadecimal representation of the address.
1827
1828 Raises:
1829 ValueError: The address is bigger than 128 bits of all ones.
1830
1831 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001832 if ip_int is None:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001833 ip_int = int(cls._ip)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001834
Antoine Pitrou45aba182014-05-15 20:18:41 +02001835 if ip_int > cls._ALL_ONES:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001836 raise ValueError('IPv6 address is too large')
1837
1838 hex_str = '%032x' % ip_int
Nick Coghlan7319f692012-07-07 21:43:30 +10001839 hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001840
Antoine Pitrou45aba182014-05-15 20:18:41 +02001841 hextets = cls._compress_hextets(hextets)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001842 return ':'.join(hextets)
1843
1844 def _explode_shorthand_ip_string(self):
1845 """Expand a shortened IPv6 address.
1846
1847 Args:
1848 ip_str: A string, the IPv6 address.
1849
1850 Returns:
1851 A string, the expanded IPv6 address.
1852
1853 """
1854 if isinstance(self, IPv6Network):
1855 ip_str = str(self.network_address)
1856 elif isinstance(self, IPv6Interface):
1857 ip_str = str(self.ip)
1858 else:
1859 ip_str = str(self)
1860
1861 ip_int = self._ip_int_from_string(ip_str)
Nick Coghlan7319f692012-07-07 21:43:30 +10001862 hex_str = '%032x' % ip_int
1863 parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001864 if isinstance(self, (_BaseNetwork, IPv6Interface)):
Nick Coghlane3ded952012-08-05 22:45:22 +10001865 return '%s/%d' % (':'.join(parts), self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001866 return ':'.join(parts)
1867
Eric V. Smithebdaaf42014-04-14 12:58:07 -04001868 def _reverse_pointer(self):
1869 """Return the reverse DNS pointer name for the IPv6 address.
1870
1871 This implements the method described in RFC3596 2.5.
1872
1873 """
1874 reverse_chars = self.exploded[::-1].replace(':', '')
1875 return '.'.join(reverse_chars) + '.ip6.arpa'
1876
Nick Coghlandc9b2552012-05-20 21:01:57 +10001877 @property
1878 def max_prefixlen(self):
1879 return self._max_prefixlen
1880
1881 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001882 def version(self):
1883 return self._version
1884
Nick Coghlandc9b2552012-05-20 21:01:57 +10001885
1886class IPv6Address(_BaseV6, _BaseAddress):
1887
Sandro Tosib95c6342012-05-23 23:17:22 +02001888 """Represent and manipulate single IPv6 Addresses."""
Nick Coghlandc9b2552012-05-20 21:01:57 +10001889
1890 def __init__(self, address):
1891 """Instantiate a new IPv6 address object.
1892
1893 Args:
1894 address: A string or integer representing the IP
1895
1896 Additionally, an integer can be passed, so
1897 IPv6Address('2001:db8::') ==
1898 IPv6Address(42540766411282592856903984951653826560)
1899 or, more generally
1900 IPv6Address(int(IPv6Address('2001:db8::'))) ==
1901 IPv6Address('2001:db8::')
1902
1903 Raises:
1904 AddressValueError: If address isn't a valid IPv6 address.
1905
1906 """
1907 _BaseAddress.__init__(self, address)
1908 _BaseV6.__init__(self, address)
1909
1910 # Efficient constructor from integer.
1911 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001912 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001913 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001914 return
1915
1916 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001917 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001918 self._check_packed_address(address, 16)
Nick Coghlandb7920b2012-08-20 10:19:12 +10001919 self._ip = int.from_bytes(address, 'big')
Nick Coghlandc9b2552012-05-20 21:01:57 +10001920 return
1921
1922 # Assume input argument to be string or any object representation
1923 # which converts into a formatted IP string.
1924 addr_str = str(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001925 self._ip = self._ip_int_from_string(addr_str)
1926
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001927 @property
1928 def packed(self):
1929 """The binary representation of this address."""
1930 return v6_int_to_packed(self._ip)
1931
Nick Coghlan730f67f2012-08-05 22:02:18 +10001932 @property
1933 def is_multicast(self):
1934 """Test if the address is reserved for multicast use.
1935
1936 Returns:
1937 A boolean, True if the address is a multicast address.
1938 See RFC 2373 2.7 for details.
1939
1940 """
1941 multicast_network = IPv6Network('ff00::/8')
1942 return self in multicast_network
1943
1944 @property
1945 def is_reserved(self):
1946 """Test if the address is otherwise IETF reserved.
1947
1948 Returns:
1949 A boolean, True if the address is within one of the
1950 reserved IPv6 Network ranges.
1951
1952 """
1953 reserved_networks = [IPv6Network('::/8'), IPv6Network('100::/8'),
1954 IPv6Network('200::/7'), IPv6Network('400::/6'),
1955 IPv6Network('800::/5'), IPv6Network('1000::/4'),
1956 IPv6Network('4000::/3'), IPv6Network('6000::/3'),
1957 IPv6Network('8000::/3'), IPv6Network('A000::/3'),
1958 IPv6Network('C000::/3'), IPv6Network('E000::/4'),
1959 IPv6Network('F000::/5'), IPv6Network('F800::/6'),
1960 IPv6Network('FE00::/9')]
1961
1962 return any(self in x for x in reserved_networks)
1963
1964 @property
1965 def is_link_local(self):
1966 """Test if the address is reserved for link-local.
1967
1968 Returns:
1969 A boolean, True if the address is reserved per RFC 4291.
1970
1971 """
1972 linklocal_network = IPv6Network('fe80::/10')
1973 return self in linklocal_network
1974
1975 @property
1976 def is_site_local(self):
1977 """Test if the address is reserved for site-local.
1978
1979 Note that the site-local address space has been deprecated by RFC 3879.
1980 Use is_private to test if this address is in the space of unique local
1981 addresses as defined by RFC 4193.
1982
1983 Returns:
1984 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1985
1986 """
1987 sitelocal_network = IPv6Network('fec0::/10')
1988 return self in sitelocal_network
1989
1990 @property
Peter Moodybe9c1b12013-10-22 12:36:21 -07001991 @functools.lru_cache()
Nick Coghlan730f67f2012-08-05 22:02:18 +10001992 def is_private(self):
1993 """Test if this address is allocated for private networks.
1994
1995 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001996 A boolean, True if the address is reserved per
1997 iana-ipv6-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001998
1999 """
Peter Moody22c31762013-10-21 13:58:06 -07002000 return (self in IPv6Network('::1/128') or
2001 self in IPv6Network('::/128') or
2002 self in IPv6Network('::ffff:0:0/96') or
2003 self in IPv6Network('100::/64') or
2004 self in IPv6Network('2001::/23') or
2005 self in IPv6Network('2001:2::/48') or
2006 self in IPv6Network('2001:db8::/32') or
2007 self in IPv6Network('2001:10::/28') or
2008 self in IPv6Network('fc00::/7') or
2009 self in IPv6Network('fe80::/10'))
2010
2011 @property
2012 def is_global(self):
2013 """Test if this address is allocated for public networks.
2014
2015 Returns:
2016 A boolean, true if the address is not reserved per
2017 iana-ipv6-special-registry.
2018
2019 """
2020 return not self.is_private
Nick Coghlan730f67f2012-08-05 22:02:18 +10002021
2022 @property
2023 def is_unspecified(self):
2024 """Test if the address is unspecified.
2025
2026 Returns:
2027 A boolean, True if this is the unspecified address as defined in
2028 RFC 2373 2.5.2.
2029
2030 """
2031 return self._ip == 0
2032
2033 @property
2034 def is_loopback(self):
2035 """Test if the address is a loopback address.
2036
2037 Returns:
2038 A boolean, True if the address is a loopback address as defined in
2039 RFC 2373 2.5.3.
2040
2041 """
2042 return self._ip == 1
2043
2044 @property
2045 def ipv4_mapped(self):
2046 """Return the IPv4 mapped address.
2047
2048 Returns:
2049 If the IPv6 address is a v4 mapped address, return the
2050 IPv4 mapped address. Return None otherwise.
2051
2052 """
2053 if (self._ip >> 32) != 0xFFFF:
2054 return None
2055 return IPv4Address(self._ip & 0xFFFFFFFF)
2056
2057 @property
2058 def teredo(self):
2059 """Tuple of embedded teredo IPs.
2060
2061 Returns:
2062 Tuple of the (server, client) IPs or None if the address
2063 doesn't appear to be a teredo address (doesn't start with
2064 2001::/32)
2065
2066 """
2067 if (self._ip >> 96) != 0x20010000:
2068 return None
2069 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
2070 IPv4Address(~self._ip & 0xFFFFFFFF))
2071
2072 @property
2073 def sixtofour(self):
2074 """Return the IPv4 6to4 embedded address.
2075
2076 Returns:
2077 The IPv4 6to4-embedded address if present or None if the
2078 address doesn't appear to contain a 6to4 embedded address.
2079
2080 """
2081 if (self._ip >> 112) != 0x2002:
2082 return None
2083 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
2084
Nick Coghlandc9b2552012-05-20 21:01:57 +10002085
2086class IPv6Interface(IPv6Address):
2087
2088 def __init__(self, address):
2089 if isinstance(address, (bytes, int)):
2090 IPv6Address.__init__(self, address)
2091 self.network = IPv6Network(self._ip)
2092 self._prefixlen = self._max_prefixlen
2093 return
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002094 if isinstance(address, tuple):
2095 IPv6Address.__init__(self, address[0])
2096 if len(address) > 1:
2097 self._prefixlen = int(address[1])
2098 else:
2099 self._prefixlen = self._max_prefixlen
2100 self.network = IPv6Network(address, strict=False)
2101 self.netmask = self.network.netmask
2102 self.hostmask = self.network.hostmask
2103 return
Nick Coghlandc9b2552012-05-20 21:01:57 +10002104
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002105 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002106 IPv6Address.__init__(self, addr[0])
2107 self.network = IPv6Network(address, strict=False)
2108 self.netmask = self.network.netmask
2109 self._prefixlen = self.network._prefixlen
2110 self.hostmask = self.network.hostmask
2111
Nick Coghlandc9b2552012-05-20 21:01:57 +10002112 def __str__(self):
2113 return '%s/%d' % (self._string_from_ip_int(self._ip),
2114 self.network.prefixlen)
2115
2116 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10002117 address_equal = IPv6Address.__eq__(self, other)
2118 if not address_equal or address_equal is NotImplemented:
2119 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10002120 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10002121 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10002122 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10002123 # An interface with an associated network is NOT the
2124 # same as an unassociated address. That's why the hash
2125 # takes the extra info into account.
2126 return False
2127
2128 def __lt__(self, other):
2129 address_less = IPv6Address.__lt__(self, other)
2130 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10002131 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10002132 try:
2133 return self.network < other.network
2134 except AttributeError:
2135 # We *do* allow addresses and interfaces to be sorted. The
2136 # unassociated address is considered less than all interfaces.
2137 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10002138
2139 def __hash__(self):
2140 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
2141
2142 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10002143 def ip(self):
2144 return IPv6Address(self._ip)
2145
2146 @property
2147 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10002148 return '%s/%s' % (self._string_from_ip_int(self._ip),
2149 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002150
2151 @property
2152 def with_netmask(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10002153 return '%s/%s' % (self._string_from_ip_int(self._ip),
2154 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02002155
Nick Coghlandc9b2552012-05-20 21:01:57 +10002156 @property
2157 def with_hostmask(self):
2158 return '%s/%s' % (self._string_from_ip_int(self._ip),
2159 self.hostmask)
2160
Nick Coghlan730f67f2012-08-05 22:02:18 +10002161 @property
2162 def is_unspecified(self):
2163 return self._ip == 0 and self.network.is_unspecified
2164
2165 @property
2166 def is_loopback(self):
2167 return self._ip == 1 and self.network.is_loopback
2168
Nick Coghlandc9b2552012-05-20 21:01:57 +10002169
2170class IPv6Network(_BaseV6, _BaseNetwork):
2171
2172 """This class represents and manipulates 128-bit IPv6 networks.
2173
2174 Attributes: [examples for IPv6('2001:db8::1000/124')]
2175 .network_address: IPv6Address('2001:db8::1000')
2176 .hostmask: IPv6Address('::f')
2177 .broadcast_address: IPv6Address('2001:db8::100f')
2178 .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
2179 .prefixlen: 124
2180
2181 """
2182
Nick Coghlan51c30672012-05-27 00:25:58 +10002183 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10002184 _address_class = IPv6Address
2185
Nick Coghlandc9b2552012-05-20 21:01:57 +10002186 def __init__(self, address, strict=True):
2187 """Instantiate a new IPv6 Network object.
2188
2189 Args:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02002190 address: A string or integer representing the IPv6 network or the
2191 IP and prefix/netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +10002192 '2001:db8::/128'
2193 '2001:db8:0000:0000:0000:0000:0000:0000/128'
2194 '2001:db8::'
2195 are all functionally the same in IPv6. That is to say,
2196 failing to provide a subnetmask will create an object with
2197 a mask of /128.
2198
2199 Additionally, an integer can be passed, so
2200 IPv6Network('2001:db8::') ==
2201 IPv6Network(42540766411282592856903984951653826560)
2202 or, more generally
2203 IPv6Network(int(IPv6Network('2001:db8::'))) ==
2204 IPv6Network('2001:db8::')
2205
2206 strict: A boolean. If true, ensure that we have been passed
2207 A true network address, eg, 2001:db8::1000/124 and not an
2208 IP address on a network, eg, 2001:db8::1/124.
2209
2210 Raises:
2211 AddressValueError: If address isn't a valid IPv6 address.
2212 NetmaskValueError: If the netmask isn't valid for
2213 an IPv6 address.
2214 ValueError: If strict was True and a network address was not
2215 supplied.
2216
2217 """
2218 _BaseV6.__init__(self, address)
2219 _BaseNetwork.__init__(self, address)
2220
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002221 # Efficient constructor from integer or packed address
2222 if isinstance(address, (bytes, int)):
Nick Coghlandc9b2552012-05-20 21:01:57 +10002223 self.network_address = IPv6Address(address)
Antoine Pitrou45aba182014-05-15 20:18:41 +02002224 self.netmask, self._prefixlen = self._make_netmask(self._max_prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002225 return
2226
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002227 if isinstance(address, tuple):
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002228 if len(address) > 1:
Antoine Pitrou45aba182014-05-15 20:18:41 +02002229 arg = address[1]
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002230 else:
Antoine Pitrou45aba182014-05-15 20:18:41 +02002231 arg = self._max_prefixlen
2232 self.netmask, self._prefixlen = self._make_netmask(arg)
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002233 self.network_address = IPv6Address(address[0])
2234 packed = int(self.network_address)
2235 if packed & int(self.netmask) != packed:
2236 if strict:
2237 raise ValueError('%s has host bits set' % self)
2238 else:
2239 self.network_address = IPv6Address(packed &
2240 int(self.netmask))
Hynek Schlawacked36b2e2012-06-08 15:21:21 +02002241 return
Nick Coghlandc9b2552012-05-20 21:01:57 +10002242
2243 # Assume input argument to be string or any object representation
2244 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002245 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002246
2247 self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))
2248
2249 if len(addr) == 2:
Antoine Pitrou45aba182014-05-15 20:18:41 +02002250 arg = addr[1]
Nick Coghlandc9b2552012-05-20 21:01:57 +10002251 else:
Antoine Pitrou45aba182014-05-15 20:18:41 +02002252 arg = self._max_prefixlen
2253 self.netmask, self._prefixlen = self._make_netmask(arg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002254
Nick Coghlandc9b2552012-05-20 21:01:57 +10002255 if strict:
2256 if (IPv6Address(int(self.network_address) & int(self.netmask)) !=
2257 self.network_address):
Nick Coghlan912238e2012-07-07 13:34:50 +10002258 raise ValueError('%s has host bits set' % self)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002259 self.network_address = IPv6Address(int(self.network_address) &
2260 int(self.netmask))
2261
2262 if self._prefixlen == (self._max_prefixlen - 1):
2263 self.hosts = self.__iter__
2264
Peter Moody1243c7d2014-03-11 09:55:46 -07002265 def hosts(self):
2266 """Generate Iterator over usable hosts in a network.
2267
2268 This is like __iter__ except it doesn't return the
2269 Subnet-Router anycast address.
2270
2271 """
2272 network = int(self.network_address)
2273 broadcast = int(self.broadcast_address)
2274 for x in range(network + 1, broadcast + 1):
2275 yield self._address_class(x)
2276
Nick Coghlan730f67f2012-08-05 22:02:18 +10002277 @property
2278 def is_site_local(self):
2279 """Test if the address is reserved for site-local.
2280
2281 Note that the site-local address space has been deprecated by RFC 3879.
2282 Use is_private to test if this address is in the space of unique local
2283 addresses as defined by RFC 4193.
2284
2285 Returns:
2286 A boolean, True if the address is reserved per RFC 3513 2.5.6.
2287
2288 """
2289 return (self.network_address.is_site_local and
2290 self.broadcast_address.is_site_local)