blob: 6c225f3037093857ce015dc2c9373287a8f825a9 [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):
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200167 """Find a sequence of sorted deduplicated IPv#Address.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000168
169 Args:
Sandro Tosi876ecad2012-05-23 22:26:55 +0200170 addresses: a list of IPv#Address objects.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000171
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200172 Yields:
173 A tuple containing the first and last IP addresses in the sequence.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000174
175 """
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200176 it = iter(addresses)
177 first = last = next(it)
178 for ip in it:
179 if ip._ip != last._ip + 1:
180 yield first, last
181 first = ip
182 last = ip
183 yield first, last
Nick Coghlandc9b2552012-05-20 21:01:57 +1000184
Sandro Tosib95c6342012-05-23 23:17:22 +0200185
Nick Coghlandc9b2552012-05-20 21:01:57 +1000186def _count_righthand_zero_bits(number, bits):
187 """Count the number of zero bits on the right hand side.
188
189 Args:
190 number: an integer.
191 bits: maximum number of bits to count.
192
193 Returns:
194 The number of zero bits on the right hand side of the number.
195
196 """
197 if number == 0:
198 return bits
Antoine Pitrou824db302014-05-15 20:21:48 +0200199 return min(bits, (~number & (number-1)).bit_length())
Nick Coghlandc9b2552012-05-20 21:01:57 +1000200
201
202def summarize_address_range(first, last):
203 """Summarize a network range given the first and last IP addresses.
204
205 Example:
Eli Bendersky948af232012-10-07 07:23:50 -0700206 >>> list(summarize_address_range(IPv4Address('192.0.2.0'),
207 ... IPv4Address('192.0.2.130')))
208 ... #doctest: +NORMALIZE_WHITESPACE
Nick Coghlandc9b2552012-05-20 21:01:57 +1000209 [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'),
Eli Bendersky948af232012-10-07 07:23:50 -0700210 IPv4Network('192.0.2.130/32')]
Nick Coghlandc9b2552012-05-20 21:01:57 +1000211
212 Args:
213 first: the first IPv4Address or IPv6Address in the range.
214 last: the last IPv4Address or IPv6Address in the range.
215
216 Returns:
217 An iterator of the summarized IPv(4|6) network objects.
218
219 Raise:
220 TypeError:
221 If the first and last objects are not IP addresses.
222 If the first and last objects are not the same version.
223 ValueError:
224 If the last object is not greater than the first.
Nick Coghlan51c30672012-05-27 00:25:58 +1000225 If the version of the first address is not 4 or 6.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000226
227 """
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200228 if (not (isinstance(first, _BaseAddress) and
229 isinstance(last, _BaseAddress))):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000230 raise TypeError('first and last must be IP addresses, not networks')
231 if first.version != last.version:
232 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000233 first, last))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000234 if first > last:
235 raise ValueError('last IP address must be greater than first')
236
Nick Coghlandc9b2552012-05-20 21:01:57 +1000237 if first.version == 4:
238 ip = IPv4Network
239 elif first.version == 6:
240 ip = IPv6Network
241 else:
242 raise ValueError('unknown IP version')
243
244 ip_bits = first._max_prefixlen
245 first_int = first._ip
246 last_int = last._ip
247 while first_int <= last_int:
Nick Coghlan7319f692012-07-07 21:43:30 +1000248 nbits = min(_count_righthand_zero_bits(first_int, ip_bits),
249 (last_int - first_int + 1).bit_length() - 1)
Antoine Pitrou824db302014-05-15 20:21:48 +0200250 net = ip((first_int, ip_bits - nbits))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000251 yield net
Nick Coghlan7319f692012-07-07 21:43:30 +1000252 first_int += 1 << nbits
253 if first_int - 1 == ip._ALL_ONES:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000254 break
Nick Coghlandc9b2552012-05-20 21:01:57 +1000255
Sandro Tosib95c6342012-05-23 23:17:22 +0200256
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200257def _collapse_addresses_internal(addresses):
Nick Coghlandc9b2552012-05-20 21:01:57 +1000258 """Loops through the addresses, collapsing concurrent netblocks.
259
260 Example:
261
262 ip1 = IPv4Network('192.0.2.0/26')
263 ip2 = IPv4Network('192.0.2.64/26')
264 ip3 = IPv4Network('192.0.2.128/26')
265 ip4 = IPv4Network('192.0.2.192/26')
266
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200267 _collapse_addresses_internal([ip1, ip2, ip3, ip4]) ->
Nick Coghlandc9b2552012-05-20 21:01:57 +1000268 [IPv4Network('192.0.2.0/24')]
269
270 This shouldn't be called directly; it is called via
271 collapse_addresses([]).
272
273 Args:
274 addresses: A list of IPv4Network's or IPv6Network's
275
276 Returns:
277 A list of IPv4Network's or IPv6Network's depending on what we were
278 passed.
279
280 """
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200281 # First merge
282 to_merge = list(addresses)
283 subnets = {}
284 while to_merge:
285 net = to_merge.pop()
286 supernet = net.supernet()
287 existing = subnets.get(supernet)
288 if existing is None:
289 subnets[supernet] = net
290 elif existing != net:
291 # Merge consecutive subnets
292 del subnets[supernet]
293 to_merge.append(supernet)
294 # Then iterate over resulting networks, skipping subsumed subnets
295 last = None
296 for net in sorted(subnets.values()):
297 if last is not None:
298 # Since they are sorted, last.network_address <= net.network_address
299 # is a given.
300 if last.broadcast_address >= net.broadcast_address:
301 continue
302 yield net
303 last = net
Nick Coghlandc9b2552012-05-20 21:01:57 +1000304
305
306def collapse_addresses(addresses):
307 """Collapse a list of IP objects.
308
309 Example:
310 collapse_addresses([IPv4Network('192.0.2.0/25'),
311 IPv4Network('192.0.2.128/25')]) ->
312 [IPv4Network('192.0.2.0/24')]
313
314 Args:
315 addresses: An iterator of IPv4Network or IPv6Network objects.
316
317 Returns:
318 An iterator of the collapsed IPv(4|6)Network objects.
319
320 Raises:
321 TypeError: If passed a list of mixed version objects.
322
323 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000324 addrs = []
325 ips = []
326 nets = []
327
328 # split IP addresses and networks
329 for ip in addresses:
330 if isinstance(ip, _BaseAddress):
331 if ips and ips[-1]._version != ip._version:
332 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000333 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000334 ips.append(ip)
335 elif ip._prefixlen == ip._max_prefixlen:
336 if ips and ips[-1]._version != ip._version:
337 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000338 ip, ips[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000339 try:
340 ips.append(ip.ip)
341 except AttributeError:
342 ips.append(ip.network_address)
343 else:
344 if nets and nets[-1]._version != ip._version:
345 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000346 ip, nets[-1]))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000347 nets.append(ip)
348
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200349 # sort and dedup
350 ips = sorted(set(ips))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000351
Antoine Pitroue6f250e2015-01-18 16:22:47 +0100352 # find consecutive address ranges in the sorted sequence and summarize them
Serhiy Storchakab53f0fb2015-01-19 00:41:32 +0200353 if ips:
354 for first, last in _find_address_range(ips):
355 addrs.extend(summarize_address_range(first, last))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000356
Antoine Pitrou1e71c532014-05-15 20:40:53 +0200357 return _collapse_addresses_internal(addrs + nets)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000358
359
360def get_mixed_type_key(obj):
361 """Return a key suitable for sorting between networks and addresses.
362
363 Address and Network objects are not sortable by default; they're
364 fundamentally different so the expression
365
366 IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
367
368 doesn't make any sense. There are some times however, where you may wish
369 to have ipaddress sort these for you anyway. If you need to do this, you
370 can use this function as the key= argument to sorted().
371
372 Args:
373 obj: either a Network or Address object.
374 Returns:
375 appropriate key.
376
377 """
378 if isinstance(obj, _BaseNetwork):
379 return obj._get_networks_key()
380 elif isinstance(obj, _BaseAddress):
381 return obj._get_address_key()
382 return NotImplemented
383
384
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200385class _IPAddressBase:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000386
387 """The mother class."""
388
389 @property
390 def exploded(self):
391 """Return the longhand version of the IP address as a string."""
392 return self._explode_shorthand_ip_string()
393
394 @property
395 def compressed(self):
396 """Return the shorthand version of the IP address as a string."""
397 return str(self)
398
Nick Coghland9722652012-06-17 16:33:00 +1000399 @property
Eric V. Smithebdaaf42014-04-14 12:58:07 -0400400 def reverse_pointer(self):
401 """The name of the reverse DNS pointer for the IP address, e.g.:
402 >>> ipaddress.ip_address("127.0.0.1").reverse_pointer
403 '1.0.0.127.in-addr.arpa'
404 >>> ipaddress.ip_address("2001:db8::1").reverse_pointer
405 '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'
406
407 """
408 return self._reverse_pointer()
409
410 @property
Nick Coghland9722652012-06-17 16:33:00 +1000411 def version(self):
412 msg = '%200s has no version specified' % (type(self),)
413 raise NotImplementedError(msg)
414
Nick Coghlan297b1432012-07-08 17:11:04 +1000415 def _check_int_address(self, address):
416 if address < 0:
417 msg = "%d (< 0) is not permitted as an IPv%d address"
418 raise AddressValueError(msg % (address, self._version))
419 if address > self._ALL_ONES:
420 msg = "%d (>= 2**%d) is not permitted as an IPv%d address"
421 raise AddressValueError(msg % (address, self._max_prefixlen,
422 self._version))
423
424 def _check_packed_address(self, address, expected_len):
425 address_len = len(address)
426 if address_len != expected_len:
427 msg = "%r (len %d != %d) is not permitted as an IPv%d address"
428 raise AddressValueError(msg % (address, address_len,
429 expected_len, self._version))
430
Antoine Pitrou45aba182014-05-15 20:18:41 +0200431 @classmethod
432 def _ip_int_from_prefix(cls, prefixlen):
Nick Coghlan932346f2014-02-08 23:17:36 +1000433 """Turn the prefix length into a bitwise netmask
Nick Coghlandc9b2552012-05-20 21:01:57 +1000434
435 Args:
436 prefixlen: An integer, the prefix length.
437
438 Returns:
439 An integer.
440
441 """
Antoine Pitrou45aba182014-05-15 20:18:41 +0200442 return cls._ALL_ONES ^ (cls._ALL_ONES >> prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000443
Antoine Pitrou45aba182014-05-15 20:18:41 +0200444 @classmethod
445 def _prefix_from_ip_int(cls, ip_int):
Nick Coghlan932346f2014-02-08 23:17:36 +1000446 """Return prefix length from the bitwise netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000447
448 Args:
Berker Peksagf23530f2014-10-19 18:04:38 +0300449 ip_int: An integer, the netmask in expanded bitwise format
Nick Coghlandc9b2552012-05-20 21:01:57 +1000450
451 Returns:
452 An integer, the prefix length.
453
Nick Coghlan932346f2014-02-08 23:17:36 +1000454 Raises:
455 ValueError: If the input intermingles zeroes & ones
Nick Coghlandc9b2552012-05-20 21:01:57 +1000456 """
Nick Coghlan932346f2014-02-08 23:17:36 +1000457 trailing_zeroes = _count_righthand_zero_bits(ip_int,
Antoine Pitrou45aba182014-05-15 20:18:41 +0200458 cls._max_prefixlen)
459 prefixlen = cls._max_prefixlen - trailing_zeroes
Nick Coghlan932346f2014-02-08 23:17:36 +1000460 leading_ones = ip_int >> trailing_zeroes
461 all_ones = (1 << prefixlen) - 1
462 if leading_ones != all_ones:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200463 byteslen = cls._max_prefixlen // 8
Nick Coghlan932346f2014-02-08 23:17:36 +1000464 details = ip_int.to_bytes(byteslen, 'big')
465 msg = 'Netmask pattern %r mixes zeroes & ones'
466 raise ValueError(msg % details)
467 return prefixlen
Nick Coghlandc9b2552012-05-20 21:01:57 +1000468
Antoine Pitrou45aba182014-05-15 20:18:41 +0200469 @classmethod
470 def _report_invalid_netmask(cls, netmask_str):
Nick Coghlan932346f2014-02-08 23:17:36 +1000471 msg = '%r is not a valid netmask' % netmask_str
472 raise NetmaskValueError(msg) from None
473
Antoine Pitrou45aba182014-05-15 20:18:41 +0200474 @classmethod
475 def _prefix_from_prefix_string(cls, prefixlen_str):
Nick Coghlan932346f2014-02-08 23:17:36 +1000476 """Return prefix length from a numeric string
Nick Coghlandc9b2552012-05-20 21:01:57 +1000477
478 Args:
Nick Coghlan932346f2014-02-08 23:17:36 +1000479 prefixlen_str: The string to be converted
Nick Coghlandc9b2552012-05-20 21:01:57 +1000480
481 Returns:
Nick Coghlan932346f2014-02-08 23:17:36 +1000482 An integer, the prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000483
Nick Coghlan932346f2014-02-08 23:17:36 +1000484 Raises:
485 NetmaskValueError: If the input is not a valid netmask
Nick Coghlandc9b2552012-05-20 21:01:57 +1000486 """
Nick Coghlan932346f2014-02-08 23:17:36 +1000487 # int allows a leading +/- as well as surrounding whitespace,
488 # so we ensure that isn't the case
489 if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
Antoine Pitrou45aba182014-05-15 20:18:41 +0200490 cls._report_invalid_netmask(prefixlen_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000491 try:
492 prefixlen = int(prefixlen_str)
493 except ValueError:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200494 cls._report_invalid_netmask(prefixlen_str)
495 if not (0 <= prefixlen <= cls._max_prefixlen):
496 cls._report_invalid_netmask(prefixlen_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000497 return prefixlen
498
Antoine Pitrou45aba182014-05-15 20:18:41 +0200499 @classmethod
500 def _prefix_from_ip_string(cls, ip_str):
Nick Coghlan932346f2014-02-08 23:17:36 +1000501 """Turn a netmask/hostmask string into a prefix length
502
503 Args:
504 ip_str: The netmask/hostmask to be converted
505
506 Returns:
507 An integer, the prefix length.
508
509 Raises:
510 NetmaskValueError: If the input is not a valid netmask/hostmask
511 """
512 # Parse the netmask/hostmask like an IP address.
513 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200514 ip_int = cls._ip_int_from_string(ip_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000515 except AddressValueError:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200516 cls._report_invalid_netmask(ip_str)
Nick Coghlan932346f2014-02-08 23:17:36 +1000517
518 # Try matching a netmask (this would be /1*0*/ as a bitwise regexp).
519 # Note that the two ambiguous cases (all-ones and all-zeroes) are
520 # treated as netmasks.
521 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200522 return cls._prefix_from_ip_int(ip_int)
Nick Coghlan932346f2014-02-08 23:17:36 +1000523 except ValueError:
524 pass
525
526 # Invert the bits, and try matching a /0+1+/ hostmask instead.
Antoine Pitrou45aba182014-05-15 20:18:41 +0200527 ip_int ^= cls._ALL_ONES
Nick Coghlan932346f2014-02-08 23:17:36 +1000528 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200529 return cls._prefix_from_ip_int(ip_int)
Nick Coghlan932346f2014-02-08 23:17:36 +1000530 except ValueError:
Antoine Pitrou45aba182014-05-15 20:18:41 +0200531 cls._report_invalid_netmask(ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000532
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +0200533 def __reduce__(self):
534 return self.__class__, (str(self),)
535
Nick Coghlan730f67f2012-08-05 22:02:18 +1000536
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200537@functools.total_ordering
Nick Coghlandc9b2552012-05-20 21:01:57 +1000538class _BaseAddress(_IPAddressBase):
539
540 """A generic IP object.
541
542 This IP class contains the version independent methods which are
543 used by single IP addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000544 """
545
Nick Coghlandc9b2552012-05-20 21:01:57 +1000546 def __int__(self):
547 return self._ip
548
Nick Coghlandc9b2552012-05-20 21:01:57 +1000549 def __eq__(self, other):
550 try:
551 return (self._ip == other._ip
552 and self._version == other._version)
553 except AttributeError:
554 return NotImplemented
555
Nick Coghlandc9b2552012-05-20 21:01:57 +1000556 def __lt__(self, other):
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200557 if not isinstance(other, _BaseAddress):
558 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000559 if self._version != other._version:
560 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000561 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000562 if self._ip != other._ip:
563 return self._ip < other._ip
564 return False
565
Nick Coghlandc9b2552012-05-20 21:01:57 +1000566 # Shorthand for Integer addition and subtraction. This is not
567 # meant to ever support addition/subtraction of addresses.
568 def __add__(self, other):
569 if not isinstance(other, int):
570 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000571 return self.__class__(int(self) + other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000572
573 def __sub__(self, other):
574 if not isinstance(other, int):
575 return NotImplemented
Nick Coghlan51c30672012-05-27 00:25:58 +1000576 return self.__class__(int(self) - other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000577
578 def __repr__(self):
579 return '%s(%r)' % (self.__class__.__name__, str(self))
580
581 def __str__(self):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200582 return str(self._string_from_ip_int(self._ip))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000583
584 def __hash__(self):
585 return hash(hex(int(self._ip)))
586
587 def _get_address_key(self):
588 return (self._version, self)
589
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +0200590 def __reduce__(self):
591 return self.__class__, (self._ip,)
592
Nick Coghlandc9b2552012-05-20 21:01:57 +1000593
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200594@functools.total_ordering
Nick Coghlandc9b2552012-05-20 21:01:57 +1000595class _BaseNetwork(_IPAddressBase):
596
Nick Coghlan51c30672012-05-27 00:25:58 +1000597 """A generic IP network object.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000598
599 This IP class contains the version independent methods which are
600 used by networks.
601
602 """
Nick Coghlandc9b2552012-05-20 21:01:57 +1000603 def __init__(self, address):
604 self._cache = {}
605
Nick Coghlandc9b2552012-05-20 21:01:57 +1000606 def __repr__(self):
607 return '%s(%r)' % (self.__class__.__name__, str(self))
608
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200609 def __str__(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000610 return '%s/%d' % (self.network_address, self.prefixlen)
Hynek Schlawack454a74d2012-06-04 18:14:02 +0200611
Nick Coghlandc9b2552012-05-20 21:01:57 +1000612 def hosts(self):
613 """Generate Iterator over usable hosts in a network.
614
Sandro Tosib95c6342012-05-23 23:17:22 +0200615 This is like __iter__ except it doesn't return the network
616 or broadcast addresses.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000617
618 """
Nick Coghlan7319f692012-07-07 21:43:30 +1000619 network = int(self.network_address)
620 broadcast = int(self.broadcast_address)
621 for x in range(network + 1, broadcast):
622 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000623
624 def __iter__(self):
Nick Coghlan7319f692012-07-07 21:43:30 +1000625 network = int(self.network_address)
626 broadcast = int(self.broadcast_address)
627 for x in range(network, broadcast + 1):
628 yield self._address_class(x)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000629
630 def __getitem__(self, n):
631 network = int(self.network_address)
632 broadcast = int(self.broadcast_address)
633 if n >= 0:
634 if network + n > broadcast:
635 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000636 return self._address_class(network + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000637 else:
638 n += 1
639 if broadcast + n < network:
640 raise IndexError
Nick Coghlan51c30672012-05-27 00:25:58 +1000641 return self._address_class(broadcast + n)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000642
643 def __lt__(self, other):
Serhiy Storchakaf186e122015-01-26 10:11:16 +0200644 if not isinstance(other, _BaseNetwork):
645 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000646 if self._version != other._version:
647 raise TypeError('%s and %s are not of the same version' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000648 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000649 if self.network_address != other.network_address:
650 return self.network_address < other.network_address
651 if self.netmask != other.netmask:
652 return self.netmask < other.netmask
653 return False
654
Nick Coghlandc9b2552012-05-20 21:01:57 +1000655 def __eq__(self, other):
Nick Coghlan9a9c28c2012-07-07 23:05:59 +1000656 try:
657 return (self._version == other._version and
658 self.network_address == other.network_address and
659 int(self.netmask) == int(other.netmask))
660 except AttributeError:
661 return NotImplemented
Nick Coghlandc9b2552012-05-20 21:01:57 +1000662
Nick Coghlandc9b2552012-05-20 21:01:57 +1000663 def __hash__(self):
664 return hash(int(self.network_address) ^ int(self.netmask))
665
666 def __contains__(self, other):
667 # always false if one is v4 and the other is v6.
668 if self._version != other._version:
669 return False
670 # dealing with another network.
671 if isinstance(other, _BaseNetwork):
672 return False
673 # dealing with another address
674 else:
675 # address
676 return (int(self.network_address) <= int(other._ip) <=
677 int(self.broadcast_address))
678
679 def overlaps(self, other):
680 """Tell if self is partly contained in other."""
681 return self.network_address in other or (
682 self.broadcast_address in other or (
683 other.network_address in self or (
684 other.broadcast_address in self)))
685
686 @property
687 def broadcast_address(self):
688 x = self._cache.get('broadcast_address')
689 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000690 x = self._address_class(int(self.network_address) |
691 int(self.hostmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000692 self._cache['broadcast_address'] = x
693 return x
694
695 @property
696 def hostmask(self):
697 x = self._cache.get('hostmask')
698 if x is None:
Nick Coghlan51c30672012-05-27 00:25:58 +1000699 x = self._address_class(int(self.netmask) ^ self._ALL_ONES)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000700 self._cache['hostmask'] = x
701 return x
702
703 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000704 def with_prefixlen(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000705 return '%s/%d' % (self.network_address, self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000706
707 @property
708 def with_netmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000709 return '%s/%s' % (self.network_address, self.netmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000710
711 @property
712 def with_hostmask(self):
Nick Coghlan912238e2012-07-07 13:34:50 +1000713 return '%s/%s' % (self.network_address, self.hostmask)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000714
715 @property
716 def num_addresses(self):
717 """Number of hosts in the current subnet."""
718 return int(self.broadcast_address) - int(self.network_address) + 1
719
720 @property
Nick Coghlan51c30672012-05-27 00:25:58 +1000721 def _address_class(self):
Nick Coghland9722652012-06-17 16:33:00 +1000722 # Returning bare address objects (rather than interfaces) allows for
723 # more consistent behaviour across the network address, broadcast
724 # address and individual host addresses.
725 msg = '%200s has no associated address class' % (type(self),)
726 raise NotImplementedError(msg)
Nick Coghlan51c30672012-05-27 00:25:58 +1000727
728 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +1000729 def prefixlen(self):
730 return self._prefixlen
731
732 def address_exclude(self, other):
733 """Remove an address from a larger block.
734
735 For example:
736
737 addr1 = ip_network('192.0.2.0/28')
738 addr2 = ip_network('192.0.2.1/32')
739 addr1.address_exclude(addr2) =
740 [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
741 IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
742
743 or IPv6:
744
745 addr1 = ip_network('2001:db8::1/32')
746 addr2 = ip_network('2001:db8::1/128')
747 addr1.address_exclude(addr2) =
748 [ip_network('2001:db8::1/128'),
749 ip_network('2001:db8::2/127'),
750 ip_network('2001:db8::4/126'),
751 ip_network('2001:db8::8/125'),
752 ...
753 ip_network('2001:db8:8000::/33')]
754
755 Args:
756 other: An IPv4Network or IPv6Network object of the same type.
757
758 Returns:
Ezio Melotti3f5db392013-01-27 06:20:14 +0200759 An iterator of the IPv(4|6)Network objects which is self
Nick Coghlandc9b2552012-05-20 21:01:57 +1000760 minus other.
761
762 Raises:
Ezio Melotti30b9d5d2013-08-17 15:50:46 +0300763 TypeError: If self and other are of differing address
Nick Coghlandc9b2552012-05-20 21:01:57 +1000764 versions, or if other is not a network object.
765 ValueError: If other is not completely contained by self.
766
767 """
768 if not self._version == other._version:
769 raise TypeError("%s and %s are not of the same version" % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000770 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000771
772 if not isinstance(other, _BaseNetwork):
Nick Coghlan912238e2012-07-07 13:34:50 +1000773 raise TypeError("%s is not a network object" % other)
Nick Coghlandc9b2552012-05-20 21:01:57 +1000774
775 if not (other.network_address >= self.network_address and
776 other.broadcast_address <= self.broadcast_address):
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200777 raise ValueError('%s not contained in %s' % (other, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000778 if other == self:
Raymond Hettingerbb6c0aa2014-11-22 22:14:41 -0800779 return
Nick Coghlandc9b2552012-05-20 21:01:57 +1000780
Nick Coghlandc9b2552012-05-20 21:01:57 +1000781 # Make sure we're comparing the network of other.
Nick Coghlan912238e2012-07-07 13:34:50 +1000782 other = other.__class__('%s/%s' % (other.network_address,
783 other.prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000784
785 s1, s2 = self.subnets()
786 while s1 != other and s2 != other:
787 if (other.network_address >= s1.network_address and
788 other.broadcast_address <= s1.broadcast_address):
789 yield s2
790 s1, s2 = s1.subnets()
791 elif (other.network_address >= s2.network_address and
792 other.broadcast_address <= s2.broadcast_address):
793 yield s1
794 s1, s2 = s2.subnets()
795 else:
796 # If we got here, there's a bug somewhere.
797 raise AssertionError('Error performing exclusion: '
798 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000799 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000800 if s1 == other:
801 yield s2
802 elif s2 == other:
803 yield s1
804 else:
805 # If we got here, there's a bug somewhere.
806 raise AssertionError('Error performing exclusion: '
807 's1: %s s2: %s other: %s' %
Nick Coghlan912238e2012-07-07 13:34:50 +1000808 (s1, s2, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000809
810 def compare_networks(self, other):
811 """Compare two IP objects.
812
813 This is only concerned about the comparison of the integer
814 representation of the network addresses. This means that the
815 host bits aren't considered at all in this method. If you want
816 to compare host bits, you can easily enough do a
817 'HostA._ip < HostB._ip'
818
819 Args:
820 other: An IP object.
821
822 Returns:
823 If the IP versions of self and other are the same, returns:
824
825 -1 if self < other:
826 eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
827 IPv6Network('2001:db8::1000/124') <
828 IPv6Network('2001:db8::2000/124')
829 0 if self == other
830 eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
831 IPv6Network('2001:db8::1000/124') ==
832 IPv6Network('2001:db8::1000/124')
833 1 if self > other
834 eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
835 IPv6Network('2001:db8::2000/124') >
836 IPv6Network('2001:db8::1000/124')
837
838 Raises:
839 TypeError if the IP versions are different.
840
841 """
842 # does this need to raise a ValueError?
843 if self._version != other._version:
844 raise TypeError('%s and %s are not of the same type' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000845 self, other))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000846 # self._version == other._version below here:
847 if self.network_address < other.network_address:
848 return -1
849 if self.network_address > other.network_address:
850 return 1
851 # self.network_address == other.network_address below here:
852 if self.netmask < other.netmask:
853 return -1
854 if self.netmask > other.netmask:
855 return 1
856 return 0
857
858 def _get_networks_key(self):
859 """Network-only key function.
860
861 Returns an object that identifies this address' network and
862 netmask. This function is a suitable "key" argument for sorted()
863 and list.sort().
864
865 """
866 return (self._version, self.network_address, self.netmask)
867
868 def subnets(self, prefixlen_diff=1, new_prefix=None):
869 """The subnets which join to make the current subnet.
870
871 In the case that self contains only one IP
872 (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
873 for IPv6), yield an iterator with just ourself.
874
875 Args:
876 prefixlen_diff: An integer, the amount the prefix length
877 should be increased by. This should not be set if
878 new_prefix is also set.
879 new_prefix: The desired new prefix length. This must be a
880 larger number (smaller prefix) than the existing prefix.
881 This should not be set if prefixlen_diff is also set.
882
883 Returns:
884 An iterator of IPv(4|6) objects.
885
886 Raises:
887 ValueError: The prefixlen_diff is too small or too large.
888 OR
889 prefixlen_diff and new_prefix are both set or new_prefix
890 is a smaller number than the current prefix (smaller
891 number means a larger network)
892
893 """
894 if self._prefixlen == self._max_prefixlen:
895 yield self
896 return
897
898 if new_prefix is not None:
899 if new_prefix < self._prefixlen:
900 raise ValueError('new prefix must be longer')
901 if prefixlen_diff != 1:
902 raise ValueError('cannot set prefixlen_diff and new_prefix')
903 prefixlen_diff = new_prefix - self._prefixlen
904
905 if prefixlen_diff < 0:
906 raise ValueError('prefix length diff must be > 0')
907 new_prefixlen = self._prefixlen + prefixlen_diff
908
Nick Coghlan932346f2014-02-08 23:17:36 +1000909 if new_prefixlen > self._max_prefixlen:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000910 raise ValueError(
911 'prefix length diff %d is invalid for netblock %s' % (
Nick Coghlan912238e2012-07-07 13:34:50 +1000912 new_prefixlen, self))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000913
Antoine Pitrou824db302014-05-15 20:21:48 +0200914 start = int(self.network_address)
915 end = int(self.broadcast_address)
916 step = (int(self.hostmask) + 1) >> prefixlen_diff
917 for new_addr in range(start, end, step):
918 current = self.__class__((new_addr, new_prefixlen))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000919 yield current
920
Nick Coghlandc9b2552012-05-20 21:01:57 +1000921 def supernet(self, prefixlen_diff=1, new_prefix=None):
922 """The supernet containing the current network.
923
924 Args:
925 prefixlen_diff: An integer, the amount the prefix length of
926 the network should be decreased by. For example, given a
927 /24 network and a prefixlen_diff of 3, a supernet with a
928 /21 netmask is returned.
929
930 Returns:
931 An IPv4 network object.
932
933 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +0200934 ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
935 a negative prefix length.
Nick Coghlandc9b2552012-05-20 21:01:57 +1000936 OR
937 If prefixlen_diff and new_prefix are both set or new_prefix is a
938 larger number than the current prefix (larger number means a
939 smaller network)
940
941 """
942 if self._prefixlen == 0:
943 return self
944
945 if new_prefix is not None:
946 if new_prefix > self._prefixlen:
947 raise ValueError('new prefix must be shorter')
948 if prefixlen_diff != 1:
949 raise ValueError('cannot set prefixlen_diff and new_prefix')
950 prefixlen_diff = self._prefixlen - new_prefix
951
Antoine Pitrou5fb195f2014-05-12 20:36:46 +0200952 new_prefixlen = self.prefixlen - prefixlen_diff
953 if new_prefixlen < 0:
Nick Coghlandc9b2552012-05-20 21:01:57 +1000954 raise ValueError(
955 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
956 (self.prefixlen, prefixlen_diff))
Antoine Pitrou5fb195f2014-05-12 20:36:46 +0200957 return self.__class__((
958 int(self.network_address) & (int(self.netmask) << prefixlen_diff),
959 new_prefixlen
960 ))
Nick Coghlandc9b2552012-05-20 21:01:57 +1000961
Nick Coghlan730f67f2012-08-05 22:02:18 +1000962 @property
963 def is_multicast(self):
964 """Test if the address is reserved for multicast use.
965
966 Returns:
967 A boolean, True if the address is a multicast address.
968 See RFC 2373 2.7 for details.
969
970 """
971 return (self.network_address.is_multicast and
972 self.broadcast_address.is_multicast)
973
974 @property
975 def is_reserved(self):
976 """Test if the address is otherwise IETF reserved.
977
978 Returns:
979 A boolean, True if the address is within one of the
980 reserved IPv6 Network ranges.
981
982 """
983 return (self.network_address.is_reserved and
984 self.broadcast_address.is_reserved)
985
986 @property
987 def is_link_local(self):
988 """Test if the address is reserved for link-local.
989
990 Returns:
991 A boolean, True if the address is reserved per RFC 4291.
992
993 """
994 return (self.network_address.is_link_local and
995 self.broadcast_address.is_link_local)
996
997 @property
998 def is_private(self):
999 """Test if this address is allocated for private networks.
1000
1001 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001002 A boolean, True if the address is reserved per
1003 iana-ipv4-special-registry or iana-ipv6-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001004
1005 """
1006 return (self.network_address.is_private and
1007 self.broadcast_address.is_private)
1008
1009 @property
Peter Moody22c31762013-10-21 13:58:06 -07001010 def is_global(self):
Peter Moodybe9c1b12013-10-22 12:36:21 -07001011 """Test if this address is allocated for public networks.
Peter Moody22c31762013-10-21 13:58:06 -07001012
1013 Returns:
1014 A boolean, True if the address is not reserved per
1015 iana-ipv4-special-registry or iana-ipv6-special-registry.
1016
1017 """
1018 return not self.is_private
1019
1020 @property
Nick Coghlan730f67f2012-08-05 22:02:18 +10001021 def is_unspecified(self):
1022 """Test if the address is unspecified.
1023
1024 Returns:
1025 A boolean, True if this is the unspecified address as defined in
1026 RFC 2373 2.5.2.
1027
1028 """
1029 return (self.network_address.is_unspecified and
1030 self.broadcast_address.is_unspecified)
1031
1032 @property
1033 def is_loopback(self):
1034 """Test if the address is a loopback address.
1035
1036 Returns:
1037 A boolean, True if the address is a loopback address as defined in
1038 RFC 2373 2.5.3.
1039
1040 """
1041 return (self.network_address.is_loopback and
1042 self.broadcast_address.is_loopback)
1043
Nick Coghlandc9b2552012-05-20 21:01:57 +10001044
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001045class _BaseV4:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001046
1047 """Base IPv4 object.
1048
1049 The following methods are used by IPv4 objects in both single IP
1050 addresses and networks.
1051
1052 """
1053
1054 # Equivalent to 255.255.255.255 or 32 bits of 1's.
1055 _ALL_ONES = (2**IPV4LENGTH) - 1
1056 _DECIMAL_DIGITS = frozenset('0123456789')
1057
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001058 # the valid octets for host and netmasks. only useful for IPv4.
Raymond Hettingerdf1b6992014-11-09 15:56:33 -08001059 _valid_mask_octets = frozenset({255, 254, 252, 248, 240, 224, 192, 128, 0})
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001060
Antoine Pitrou45aba182014-05-15 20:18:41 +02001061 _max_prefixlen = IPV4LENGTH
1062 # There are only a handful of valid v4 netmasks, so we cache them all
1063 # when constructed (see _make_netmask()).
1064 _netmask_cache = {}
1065
Nick Coghlandc9b2552012-05-20 21:01:57 +10001066 def __init__(self, address):
1067 self._version = 4
Nick Coghlandc9b2552012-05-20 21:01:57 +10001068
1069 def _explode_shorthand_ip_string(self):
1070 return str(self)
1071
Antoine Pitrou45aba182014-05-15 20:18:41 +02001072 @classmethod
1073 def _make_netmask(cls, arg):
1074 """Make a (netmask, prefix_len) tuple from the given argument.
1075
1076 Argument can be:
1077 - an integer (the prefix length)
1078 - a string representing the prefix length (e.g. "24")
1079 - a string representing the prefix netmask (e.g. "255.255.255.0")
1080 """
1081 if arg not in cls._netmask_cache:
1082 if isinstance(arg, int):
1083 prefixlen = arg
1084 else:
1085 try:
1086 # Check for a netmask in prefix length form
1087 prefixlen = cls._prefix_from_prefix_string(arg)
1088 except NetmaskValueError:
1089 # Check for a netmask or hostmask in dotted-quad form.
1090 # This may raise NetmaskValueError.
1091 prefixlen = cls._prefix_from_ip_string(arg)
1092 netmask = IPv4Address(cls._ip_int_from_prefix(prefixlen))
1093 cls._netmask_cache[arg] = netmask, prefixlen
1094 return cls._netmask_cache[arg]
1095
1096 @classmethod
1097 def _ip_int_from_string(cls, ip_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001098 """Turn the given IP string into an integer for comparison.
1099
1100 Args:
1101 ip_str: A string, the IP ip_str.
1102
1103 Returns:
1104 The IP ip_str as an integer.
1105
1106 Raises:
1107 AddressValueError: if ip_str isn't a valid IPv4 Address.
1108
1109 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001110 if not ip_str:
1111 raise AddressValueError('Address cannot be empty')
1112
Nick Coghlandc9b2552012-05-20 21:01:57 +10001113 octets = ip_str.split('.')
1114 if len(octets) != 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001115 raise AddressValueError("Expected 4 octets in %r" % ip_str)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001116
Nick Coghlan7319f692012-07-07 21:43:30 +10001117 try:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001118 return int.from_bytes(map(cls._parse_octet, octets), 'big')
Nick Coghlan7319f692012-07-07 21:43:30 +10001119 except ValueError as exc:
1120 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001121
Antoine Pitrou45aba182014-05-15 20:18:41 +02001122 @classmethod
1123 def _parse_octet(cls, octet_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001124 """Convert a decimal octet into an integer.
1125
1126 Args:
1127 octet_str: A string, the number to parse.
1128
1129 Returns:
1130 The octet as an integer.
1131
1132 Raises:
1133 ValueError: if the octet isn't strictly a decimal from [0..255].
1134
1135 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001136 if not octet_str:
1137 raise ValueError("Empty octet not permitted")
Nick Coghlandc9b2552012-05-20 21:01:57 +10001138 # Whitelist the characters, since int() allows a lot of bizarre stuff.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001139 if not cls._DECIMAL_DIGITS.issuperset(octet_str):
Nick Coghlan07c4e332012-07-08 23:06:45 +10001140 msg = "Only decimal digits permitted in %r"
1141 raise ValueError(msg % octet_str)
1142 # We do the length check second, since the invalid character error
1143 # is likely to be more informative for the user
1144 if len(octet_str) > 3:
1145 msg = "At most 3 characters permitted in %r"
1146 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001147 # Convert to integer (we know digits are legal)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001148 octet_int = int(octet_str, 10)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001149 # Any octets that look like they *might* be written in octal,
1150 # and which don't look exactly the same in both octal and
1151 # decimal are rejected as ambiguous
1152 if octet_int > 7 and octet_str[0] == '0':
Nick Coghlan07c4e332012-07-08 23:06:45 +10001153 msg = "Ambiguous (octal/decimal) value in %r not permitted"
1154 raise ValueError(msg % octet_str)
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001155 if octet_int > 255:
Nick Coghlanb582ecc2012-07-07 22:15:22 +10001156 raise ValueError("Octet %d (> 255) not permitted" % octet_int)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001157 return octet_int
1158
Antoine Pitrou45aba182014-05-15 20:18:41 +02001159 @classmethod
1160 def _string_from_ip_int(cls, ip_int):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001161 """Turns a 32-bit integer into dotted decimal notation.
1162
1163 Args:
1164 ip_int: An integer, the IP address.
1165
1166 Returns:
1167 The IP address as a string in dotted decimal notation.
1168
1169 """
Nick Coghlan7319f692012-07-07 21:43:30 +10001170 return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001171
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001172 def _is_valid_netmask(self, netmask):
1173 """Verify that the netmask is valid.
1174
1175 Args:
1176 netmask: A string, either a prefix or dotted decimal
1177 netmask.
1178
1179 Returns:
1180 A boolean, True if the prefix represents a valid IPv4
1181 netmask.
1182
1183 """
1184 mask = netmask.split('.')
1185 if len(mask) == 4:
Nick Coghlan7319f692012-07-07 21:43:30 +10001186 try:
1187 for x in mask:
1188 if int(x) not in self._valid_mask_octets:
1189 return False
1190 except ValueError:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001191 # Found something that isn't an integer or isn't valid
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001192 return False
Nick Coghlan7319f692012-07-07 21:43:30 +10001193 for idx, y in enumerate(mask):
1194 if idx > 0 and y > mask[idx - 1]:
1195 return False
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001196 return True
1197 try:
1198 netmask = int(netmask)
1199 except ValueError:
1200 return False
1201 return 0 <= netmask <= self._max_prefixlen
1202
1203 def _is_hostmask(self, ip_str):
1204 """Test if the IP string is a hostmask (rather than a netmask).
1205
1206 Args:
1207 ip_str: A string, the potential hostmask.
1208
1209 Returns:
1210 A boolean, True if the IP string is a hostmask.
1211
1212 """
1213 bits = ip_str.split('.')
1214 try:
Nick Coghlan7319f692012-07-07 21:43:30 +10001215 parts = [x for x in map(int, bits) if x in self._valid_mask_octets]
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001216 except ValueError:
1217 return False
1218 if len(parts) != len(bits):
1219 return False
1220 if parts[0] < parts[-1]:
1221 return True
1222 return False
1223
Eric V. Smithebdaaf42014-04-14 12:58:07 -04001224 def _reverse_pointer(self):
1225 """Return the reverse DNS pointer name for the IPv4 address.
1226
1227 This implements the method described in RFC1035 3.5.
1228
1229 """
1230 reverse_octets = str(self).split('.')[::-1]
1231 return '.'.join(reverse_octets) + '.in-addr.arpa'
1232
Nick Coghlandc9b2552012-05-20 21:01:57 +10001233 @property
1234 def max_prefixlen(self):
1235 return self._max_prefixlen
1236
1237 @property
1238 def version(self):
1239 return self._version
1240
Nick Coghlandc9b2552012-05-20 21:01:57 +10001241
1242class IPv4Address(_BaseV4, _BaseAddress):
1243
1244 """Represent and manipulate single IPv4 Addresses."""
1245
1246 def __init__(self, address):
1247
1248 """
1249 Args:
1250 address: A string or integer representing the IP
1251
1252 Additionally, an integer can be passed, so
1253 IPv4Address('192.0.2.1') == IPv4Address(3221225985).
1254 or, more generally
1255 IPv4Address(int(IPv4Address('192.0.2.1'))) ==
1256 IPv4Address('192.0.2.1')
1257
1258 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001259 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001260
1261 """
Nick Coghlandc9b2552012-05-20 21:01:57 +10001262 _BaseV4.__init__(self, address)
1263
1264 # Efficient constructor from integer.
1265 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001266 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001267 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001268 return
1269
1270 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001271 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001272 self._check_packed_address(address, 4)
Nick Coghlandb7920b2012-08-20 10:19:12 +10001273 self._ip = int.from_bytes(address, 'big')
Nick Coghlandc9b2552012-05-20 21:01:57 +10001274 return
1275
1276 # Assume input argument to be string or any object representation
1277 # which converts into a formatted IP string.
1278 addr_str = str(address)
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +02001279 if '/' in addr_str:
1280 raise AddressValueError("Unexpected '/' in %r" % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001281 self._ip = self._ip_int_from_string(addr_str)
1282
1283 @property
1284 def packed(self):
1285 """The binary representation of this address."""
1286 return v4_int_to_packed(self._ip)
1287
Nick Coghlan730f67f2012-08-05 22:02:18 +10001288 @property
1289 def is_reserved(self):
1290 """Test if the address is otherwise IETF reserved.
1291
1292 Returns:
1293 A boolean, True if the address is within the
1294 reserved IPv4 Network range.
1295
1296 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001297 return self in self._constants._reserved_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001298
1299 @property
Peter Moodybe9c1b12013-10-22 12:36:21 -07001300 @functools.lru_cache()
Nick Coghlan730f67f2012-08-05 22:02:18 +10001301 def is_private(self):
1302 """Test if this address is allocated for private networks.
1303
1304 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001305 A boolean, True if the address is reserved per
1306 iana-ipv4-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001307
1308 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001309 return any(self in net for net in self._constants._private_networks)
Nick Coghlan730f67f2012-08-05 22:02:18 +10001310
1311 @property
1312 def is_multicast(self):
1313 """Test if the address is reserved for multicast use.
1314
1315 Returns:
1316 A boolean, True if the address is multicast.
1317 See RFC 3171 for details.
1318
1319 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001320 return self in self._constants._multicast_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001321
1322 @property
1323 def is_unspecified(self):
1324 """Test if the address is unspecified.
1325
1326 Returns:
1327 A boolean, True if this is the unspecified address as defined in
1328 RFC 5735 3.
1329
1330 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001331 return self == self._constants._unspecified_address
Nick Coghlan730f67f2012-08-05 22:02:18 +10001332
1333 @property
1334 def is_loopback(self):
1335 """Test if the address is a loopback address.
1336
1337 Returns:
1338 A boolean, True if the address is a loopback per RFC 3330.
1339
1340 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001341 return self in self._constants._loopback_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001342
1343 @property
1344 def is_link_local(self):
1345 """Test if the address is reserved for link-local.
1346
1347 Returns:
1348 A boolean, True if the address is link-local per RFC 3927.
1349
1350 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001351 return self in self._constants._linklocal_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001352
Nick Coghlandc9b2552012-05-20 21:01:57 +10001353
1354class IPv4Interface(IPv4Address):
1355
Nick Coghlandc9b2552012-05-20 21:01:57 +10001356 def __init__(self, address):
1357 if isinstance(address, (bytes, int)):
1358 IPv4Address.__init__(self, address)
1359 self.network = IPv4Network(self._ip)
1360 self._prefixlen = self._max_prefixlen
1361 return
1362
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001363 if isinstance(address, tuple):
1364 IPv4Address.__init__(self, address[0])
1365 if len(address) > 1:
1366 self._prefixlen = int(address[1])
1367 else:
1368 self._prefixlen = self._max_prefixlen
1369
1370 self.network = IPv4Network(address, strict=False)
1371 self.netmask = self.network.netmask
1372 self.hostmask = self.network.hostmask
1373 return
1374
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001375 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001376 IPv4Address.__init__(self, addr[0])
1377
1378 self.network = IPv4Network(address, strict=False)
1379 self._prefixlen = self.network._prefixlen
1380
1381 self.netmask = self.network.netmask
1382 self.hostmask = self.network.hostmask
1383
Nick Coghlandc9b2552012-05-20 21:01:57 +10001384 def __str__(self):
1385 return '%s/%d' % (self._string_from_ip_int(self._ip),
1386 self.network.prefixlen)
1387
1388 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10001389 address_equal = IPv4Address.__eq__(self, other)
1390 if not address_equal or address_equal is NotImplemented:
1391 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10001392 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001393 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10001394 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10001395 # An interface with an associated network is NOT the
1396 # same as an unassociated address. That's why the hash
1397 # takes the extra info into account.
1398 return False
1399
1400 def __lt__(self, other):
1401 address_less = IPv4Address.__lt__(self, other)
1402 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001403 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10001404 try:
1405 return self.network < other.network
1406 except AttributeError:
1407 # We *do* allow addresses and interfaces to be sorted. The
1408 # unassociated address is considered less than all interfaces.
1409 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10001410
1411 def __hash__(self):
1412 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
1413
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +02001414 __reduce__ = _IPAddressBase.__reduce__
1415
Nick Coghlandc9b2552012-05-20 21:01:57 +10001416 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001417 def ip(self):
1418 return IPv4Address(self._ip)
1419
1420 @property
1421 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10001422 return '%s/%s' % (self._string_from_ip_int(self._ip),
1423 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001424
1425 @property
1426 def with_netmask(self):
1427 return '%s/%s' % (self._string_from_ip_int(self._ip),
1428 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001429
Nick Coghlandc9b2552012-05-20 21:01:57 +10001430 @property
1431 def with_hostmask(self):
1432 return '%s/%s' % (self._string_from_ip_int(self._ip),
1433 self.hostmask)
1434
1435
1436class IPv4Network(_BaseV4, _BaseNetwork):
1437
1438 """This class represents and manipulates 32-bit IPv4 network + addresses..
1439
1440 Attributes: [examples for IPv4Network('192.0.2.0/27')]
1441 .network_address: IPv4Address('192.0.2.0')
1442 .hostmask: IPv4Address('0.0.0.31')
1443 .broadcast_address: IPv4Address('192.0.2.32')
1444 .netmask: IPv4Address('255.255.255.224')
1445 .prefixlen: 27
1446
1447 """
Nick Coghlan51c30672012-05-27 00:25:58 +10001448 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10001449 _address_class = IPv4Address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001450
Nick Coghlandc9b2552012-05-20 21:01:57 +10001451 def __init__(self, address, strict=True):
1452
1453 """Instantiate a new IPv4 network object.
1454
1455 Args:
1456 address: A string or integer representing the IP [& network].
1457 '192.0.2.0/24'
1458 '192.0.2.0/255.255.255.0'
1459 '192.0.0.2/0.0.0.255'
1460 are all functionally the same in IPv4. Similarly,
1461 '192.0.2.1'
1462 '192.0.2.1/255.255.255.255'
1463 '192.0.2.1/32'
Ezio Melotti30b9d5d2013-08-17 15:50:46 +03001464 are also functionally equivalent. That is to say, failing to
Nick Coghlandc9b2552012-05-20 21:01:57 +10001465 provide a subnetmask will create an object with a mask of /32.
1466
1467 If the mask (portion after the / in the argument) is given in
1468 dotted quad form, it is treated as a netmask if it starts with a
1469 non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
1470 starts with a zero field (e.g. 0.255.255.255 == /8), with the
1471 single exception of an all-zero mask which is treated as a
1472 netmask == /0. If no mask is given, a default of /32 is used.
1473
1474 Additionally, an integer can be passed, so
1475 IPv4Network('192.0.2.1') == IPv4Network(3221225985)
1476 or, more generally
1477 IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
1478 IPv4Interface('192.0.2.1')
1479
1480 Raises:
Sandro Tosib4386d32012-06-02 17:14:22 +02001481 AddressValueError: If ipaddress isn't a valid IPv4 address.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001482 NetmaskValueError: If the netmask isn't valid for
1483 an IPv4 address.
Sandro Tosib4386d32012-06-02 17:14:22 +02001484 ValueError: If strict is True and a network address is not
Nick Coghlandc9b2552012-05-20 21:01:57 +10001485 supplied.
1486
1487 """
1488
1489 _BaseV4.__init__(self, address)
1490 _BaseNetwork.__init__(self, address)
1491
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001492 # Constructing from a packed address or integer
1493 if isinstance(address, (int, bytes)):
Nick Coghlan297b1432012-07-08 17:11:04 +10001494 self.network_address = IPv4Address(address)
Antoine Pitrou45aba182014-05-15 20:18:41 +02001495 self.netmask, self._prefixlen = self._make_netmask(self._max_prefixlen)
1496 #fixme: address/network test here.
Nick Coghlandc9b2552012-05-20 21:01:57 +10001497 return
1498
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001499 if isinstance(address, tuple):
1500 if len(address) > 1:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001501 arg = address[1]
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001502 else:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001503 # We weren't given an address[1]
1504 arg = self._max_prefixlen
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001505 self.network_address = IPv4Address(address[0])
Antoine Pitrou45aba182014-05-15 20:18:41 +02001506 self.netmask, self._prefixlen = self._make_netmask(arg)
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02001507 packed = int(self.network_address)
1508 if packed & int(self.netmask) != packed:
1509 if strict:
1510 raise ValueError('%s has host bits set' % self)
1511 else:
1512 self.network_address = IPv4Address(packed &
1513 int(self.netmask))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001514 return
1515
1516 # Assume input argument to be string or any object representation
1517 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001518 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001519 self.network_address = IPv4Address(self._ip_int_from_string(addr[0]))
1520
Nick Coghlandc9b2552012-05-20 21:01:57 +10001521 if len(addr) == 2:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001522 arg = addr[1]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001523 else:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001524 arg = self._max_prefixlen
1525 self.netmask, self._prefixlen = self._make_netmask(arg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001526
1527 if strict:
1528 if (IPv4Address(int(self.network_address) & int(self.netmask)) !=
1529 self.network_address):
1530 raise ValueError('%s has host bits set' % self)
1531 self.network_address = IPv4Address(int(self.network_address) &
1532 int(self.netmask))
1533
1534 if self._prefixlen == (self._max_prefixlen - 1):
1535 self.hosts = self.__iter__
1536
Peter Moodye5019d52013-10-24 09:47:10 -07001537 @property
1538 @functools.lru_cache()
1539 def is_global(self):
1540 """Test if this address is allocated for public networks.
1541
1542 Returns:
1543 A boolean, True if the address is not reserved per
1544 iana-ipv4-special-registry.
1545
1546 """
1547 return (not (self.network_address in IPv4Network('100.64.0.0/10') and
1548 self.broadcast_address in IPv4Network('100.64.0.0/10')) and
1549 not self.is_private)
1550
1551
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001552class _IPv4Constants:
1553 _linklocal_network = IPv4Network('169.254.0.0/16')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001554
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001555 _loopback_network = IPv4Network('127.0.0.0/8')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001556
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001557 _multicast_network = IPv4Network('224.0.0.0/4')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001558
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001559 _private_networks = [
1560 IPv4Network('0.0.0.0/8'),
1561 IPv4Network('10.0.0.0/8'),
1562 IPv4Network('127.0.0.0/8'),
1563 IPv4Network('169.254.0.0/16'),
1564 IPv4Network('172.16.0.0/12'),
1565 IPv4Network('192.0.0.0/29'),
1566 IPv4Network('192.0.0.170/31'),
1567 IPv4Network('192.0.2.0/24'),
1568 IPv4Network('192.168.0.0/16'),
1569 IPv4Network('198.18.0.0/15'),
1570 IPv4Network('198.51.100.0/24'),
1571 IPv4Network('203.0.113.0/24'),
1572 IPv4Network('240.0.0.0/4'),
1573 IPv4Network('255.255.255.255/32'),
1574 ]
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001575
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001576 _reserved_network = IPv4Network('240.0.0.0/4')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001577
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001578 _unspecified_address = IPv4Address('0.0.0.0')
1579
1580
1581IPv4Address._constants = _IPv4Constants
Antoine Pitrouf573ce92014-05-23 23:12:24 +02001582
Nick Coghlandc9b2552012-05-20 21:01:57 +10001583
Hynek Schlawackc4b78a32012-06-01 11:48:32 +02001584class _BaseV6:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001585
1586 """Base IPv6 object.
1587
1588 The following methods are used by IPv6 objects in both single IP
1589 addresses and networks.
1590
1591 """
1592
1593 _ALL_ONES = (2**IPV6LENGTH) - 1
1594 _HEXTET_COUNT = 8
1595 _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
Antoine Pitrou45aba182014-05-15 20:18:41 +02001596 _max_prefixlen = IPV6LENGTH
1597
1598 # There are only a bunch of valid v6 netmasks, so we cache them all
1599 # when constructed (see _make_netmask()).
1600 _netmask_cache = {}
Nick Coghlandc9b2552012-05-20 21:01:57 +10001601
1602 def __init__(self, address):
1603 self._version = 6
Nick Coghlandc9b2552012-05-20 21:01:57 +10001604
Antoine Pitrou45aba182014-05-15 20:18:41 +02001605 @classmethod
1606 def _make_netmask(cls, arg):
1607 """Make a (netmask, prefix_len) tuple from the given argument.
1608
1609 Argument can be:
1610 - an integer (the prefix length)
1611 - a string representing the prefix length (e.g. "24")
1612 - a string representing the prefix netmask (e.g. "255.255.255.0")
1613 """
1614 if arg not in cls._netmask_cache:
1615 if isinstance(arg, int):
1616 prefixlen = arg
1617 else:
1618 prefixlen = cls._prefix_from_prefix_string(arg)
1619 netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen))
1620 cls._netmask_cache[arg] = netmask, prefixlen
1621 return cls._netmask_cache[arg]
1622
1623 @classmethod
1624 def _ip_int_from_string(cls, ip_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001625 """Turn an IPv6 ip_str into an integer.
1626
1627 Args:
1628 ip_str: A string, the IPv6 ip_str.
1629
1630 Returns:
1631 An int, the IPv6 address
1632
1633 Raises:
1634 AddressValueError: if ip_str isn't a valid IPv6 Address.
1635
1636 """
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001637 if not ip_str:
1638 raise AddressValueError('Address cannot be empty')
1639
Nick Coghlandc9b2552012-05-20 21:01:57 +10001640 parts = ip_str.split(':')
1641
1642 # An IPv6 address needs at least 2 colons (3 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001643 _min_parts = 3
1644 if len(parts) < _min_parts:
1645 msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
1646 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001647
1648 # If the address has an IPv4-style suffix, convert it to hexadecimal.
1649 if '.' in parts[-1]:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001650 try:
1651 ipv4_int = IPv4Address(parts.pop())._ip
1652 except AddressValueError as exc:
1653 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001654 parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
1655 parts.append('%x' % (ipv4_int & 0xFFFF))
1656
1657 # An IPv6 address can't have more than 8 colons (9 parts).
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001658 # The extra colon comes from using the "::" notation for a single
1659 # leading or trailing zero part.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001660 _max_parts = cls._HEXTET_COUNT + 1
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001661 if len(parts) > _max_parts:
1662 msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
1663 raise AddressValueError(msg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001664
1665 # Disregarding the endpoints, find '::' with nothing in between.
1666 # This indicates that a run of zeroes has been skipped.
Nick Coghlan7319f692012-07-07 21:43:30 +10001667 skip_index = None
1668 for i in range(1, len(parts) - 1):
1669 if not parts[i]:
1670 if skip_index is not None:
1671 # Can't have more than one '::'
1672 msg = "At most one '::' permitted in %r" % ip_str
1673 raise AddressValueError(msg)
1674 skip_index = i
Nick Coghlandc9b2552012-05-20 21:01:57 +10001675
1676 # parts_hi is the number of parts to copy from above/before the '::'
1677 # parts_lo is the number of parts to copy from below/after the '::'
1678 if skip_index is not None:
1679 # If we found a '::', then check if it also covers the endpoints.
1680 parts_hi = skip_index
1681 parts_lo = len(parts) - skip_index - 1
1682 if not parts[0]:
1683 parts_hi -= 1
1684 if parts_hi:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001685 msg = "Leading ':' only permitted as part of '::' in %r"
1686 raise AddressValueError(msg % ip_str) # ^: requires ^::
Nick Coghlandc9b2552012-05-20 21:01:57 +10001687 if not parts[-1]:
1688 parts_lo -= 1
1689 if parts_lo:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001690 msg = "Trailing ':' only permitted as part of '::' in %r"
1691 raise AddressValueError(msg % ip_str) # :$ requires ::$
Antoine Pitrou45aba182014-05-15 20:18:41 +02001692 parts_skipped = cls._HEXTET_COUNT - (parts_hi + parts_lo)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001693 if parts_skipped < 1:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001694 msg = "Expected at most %d other parts with '::' in %r"
Antoine Pitrou45aba182014-05-15 20:18:41 +02001695 raise AddressValueError(msg % (cls._HEXTET_COUNT-1, ip_str))
Nick Coghlandc9b2552012-05-20 21:01:57 +10001696 else:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001697 # Otherwise, allocate the entire address to parts_hi. The
1698 # endpoints could still be empty, but _parse_hextet() will check
1699 # for that.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001700 if len(parts) != cls._HEXTET_COUNT:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001701 msg = "Exactly %d parts expected without '::' in %r"
Antoine Pitrou45aba182014-05-15 20:18:41 +02001702 raise AddressValueError(msg % (cls._HEXTET_COUNT, ip_str))
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001703 if not parts[0]:
1704 msg = "Leading ':' only permitted as part of '::' in %r"
1705 raise AddressValueError(msg % ip_str) # ^: requires ^::
1706 if not parts[-1]:
1707 msg = "Trailing ':' only permitted as part of '::' in %r"
1708 raise AddressValueError(msg % ip_str) # :$ requires ::$
Nick Coghlandc9b2552012-05-20 21:01:57 +10001709 parts_hi = len(parts)
1710 parts_lo = 0
1711 parts_skipped = 0
1712
1713 try:
1714 # Now, parse the hextets into a 128-bit integer.
1715 ip_int = 0
1716 for i in range(parts_hi):
1717 ip_int <<= 16
Antoine Pitrou45aba182014-05-15 20:18:41 +02001718 ip_int |= cls._parse_hextet(parts[i])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001719 ip_int <<= 16 * parts_skipped
1720 for i in range(-parts_lo, 0):
1721 ip_int <<= 16
Antoine Pitrou45aba182014-05-15 20:18:41 +02001722 ip_int |= cls._parse_hextet(parts[i])
Nick Coghlandc9b2552012-05-20 21:01:57 +10001723 return ip_int
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001724 except ValueError as exc:
1725 raise AddressValueError("%s in %r" % (exc, ip_str)) from None
Nick Coghlandc9b2552012-05-20 21:01:57 +10001726
Antoine Pitrou45aba182014-05-15 20:18:41 +02001727 @classmethod
1728 def _parse_hextet(cls, hextet_str):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001729 """Convert an IPv6 hextet string into an integer.
1730
1731 Args:
1732 hextet_str: A string, the number to parse.
1733
1734 Returns:
1735 The hextet as an integer.
1736
1737 Raises:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02001738 ValueError: if the input isn't strictly a hex number from
1739 [0..FFFF].
Nick Coghlandc9b2552012-05-20 21:01:57 +10001740
1741 """
1742 # Whitelist the characters, since int() allows a lot of bizarre stuff.
Antoine Pitrou45aba182014-05-15 20:18:41 +02001743 if not cls._HEX_DIGITS.issuperset(hextet_str):
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001744 raise ValueError("Only hex digits permitted in %r" % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001745 # We do the length check second, since the invalid character error
1746 # is likely to be more informative for the user
Nick Coghlan3c2570c2012-07-07 01:13:55 +10001747 if len(hextet_str) > 4:
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10001748 msg = "At most 4 characters permitted in %r"
1749 raise ValueError(msg % hextet_str)
Nick Coghlan07c4e332012-07-08 23:06:45 +10001750 # Length check means we can skip checking the integer value
1751 return int(hextet_str, 16)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001752
Antoine Pitrou45aba182014-05-15 20:18:41 +02001753 @classmethod
1754 def _compress_hextets(cls, hextets):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001755 """Compresses a list of hextets.
1756
1757 Compresses a list of strings, replacing the longest continuous
1758 sequence of "0" in the list with "" and adding empty strings at
1759 the beginning or at the end of the string such that subsequently
1760 calling ":".join(hextets) will produce the compressed version of
1761 the IPv6 address.
1762
1763 Args:
1764 hextets: A list of strings, the hextets to compress.
1765
1766 Returns:
1767 A list of strings.
1768
1769 """
1770 best_doublecolon_start = -1
1771 best_doublecolon_len = 0
1772 doublecolon_start = -1
1773 doublecolon_len = 0
Nick Coghlandb7920b2012-08-20 10:19:12 +10001774 for index, hextet in enumerate(hextets):
1775 if hextet == '0':
Nick Coghlandc9b2552012-05-20 21:01:57 +10001776 doublecolon_len += 1
1777 if doublecolon_start == -1:
1778 # Start of a sequence of zeros.
1779 doublecolon_start = index
1780 if doublecolon_len > best_doublecolon_len:
1781 # This is the longest sequence of zeros so far.
1782 best_doublecolon_len = doublecolon_len
1783 best_doublecolon_start = doublecolon_start
1784 else:
1785 doublecolon_len = 0
1786 doublecolon_start = -1
1787
1788 if best_doublecolon_len > 1:
1789 best_doublecolon_end = (best_doublecolon_start +
1790 best_doublecolon_len)
1791 # For zeros at the end of the address.
1792 if best_doublecolon_end == len(hextets):
1793 hextets += ['']
1794 hextets[best_doublecolon_start:best_doublecolon_end] = ['']
1795 # For zeros at the beginning of the address.
1796 if best_doublecolon_start == 0:
1797 hextets = [''] + hextets
1798
1799 return hextets
1800
Antoine Pitrou45aba182014-05-15 20:18:41 +02001801 @classmethod
1802 def _string_from_ip_int(cls, ip_int=None):
Nick Coghlandc9b2552012-05-20 21:01:57 +10001803 """Turns a 128-bit integer into hexadecimal notation.
1804
1805 Args:
1806 ip_int: An integer, the IP address.
1807
1808 Returns:
1809 A string, the hexadecimal representation of the address.
1810
1811 Raises:
1812 ValueError: The address is bigger than 128 bits of all ones.
1813
1814 """
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001815 if ip_int is None:
Antoine Pitrou45aba182014-05-15 20:18:41 +02001816 ip_int = int(cls._ip)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001817
Antoine Pitrou45aba182014-05-15 20:18:41 +02001818 if ip_int > cls._ALL_ONES:
Nick Coghlandc9b2552012-05-20 21:01:57 +10001819 raise ValueError('IPv6 address is too large')
1820
1821 hex_str = '%032x' % ip_int
Nick Coghlan7319f692012-07-07 21:43:30 +10001822 hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001823
Antoine Pitrou45aba182014-05-15 20:18:41 +02001824 hextets = cls._compress_hextets(hextets)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001825 return ':'.join(hextets)
1826
1827 def _explode_shorthand_ip_string(self):
1828 """Expand a shortened IPv6 address.
1829
1830 Args:
1831 ip_str: A string, the IPv6 address.
1832
1833 Returns:
1834 A string, the expanded IPv6 address.
1835
1836 """
1837 if isinstance(self, IPv6Network):
1838 ip_str = str(self.network_address)
1839 elif isinstance(self, IPv6Interface):
1840 ip_str = str(self.ip)
1841 else:
1842 ip_str = str(self)
1843
1844 ip_int = self._ip_int_from_string(ip_str)
Nick Coghlan7319f692012-07-07 21:43:30 +10001845 hex_str = '%032x' % ip_int
1846 parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
Nick Coghlandc9b2552012-05-20 21:01:57 +10001847 if isinstance(self, (_BaseNetwork, IPv6Interface)):
Nick Coghlane3ded952012-08-05 22:45:22 +10001848 return '%s/%d' % (':'.join(parts), self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001849 return ':'.join(parts)
1850
Eric V. Smithebdaaf42014-04-14 12:58:07 -04001851 def _reverse_pointer(self):
1852 """Return the reverse DNS pointer name for the IPv6 address.
1853
1854 This implements the method described in RFC3596 2.5.
1855
1856 """
1857 reverse_chars = self.exploded[::-1].replace(':', '')
1858 return '.'.join(reverse_chars) + '.ip6.arpa'
1859
Nick Coghlandc9b2552012-05-20 21:01:57 +10001860 @property
1861 def max_prefixlen(self):
1862 return self._max_prefixlen
1863
1864 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10001865 def version(self):
1866 return self._version
1867
Nick Coghlandc9b2552012-05-20 21:01:57 +10001868
1869class IPv6Address(_BaseV6, _BaseAddress):
1870
Sandro Tosib95c6342012-05-23 23:17:22 +02001871 """Represent and manipulate single IPv6 Addresses."""
Nick Coghlandc9b2552012-05-20 21:01:57 +10001872
1873 def __init__(self, address):
1874 """Instantiate a new IPv6 address object.
1875
1876 Args:
1877 address: A string or integer representing the IP
1878
1879 Additionally, an integer can be passed, so
1880 IPv6Address('2001:db8::') ==
1881 IPv6Address(42540766411282592856903984951653826560)
1882 or, more generally
1883 IPv6Address(int(IPv6Address('2001:db8::'))) ==
1884 IPv6Address('2001:db8::')
1885
1886 Raises:
1887 AddressValueError: If address isn't a valid IPv6 address.
1888
1889 """
Nick Coghlandc9b2552012-05-20 21:01:57 +10001890 _BaseV6.__init__(self, address)
1891
1892 # Efficient constructor from integer.
1893 if isinstance(address, int):
Nick Coghlan297b1432012-07-08 17:11:04 +10001894 self._check_int_address(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001895 self._ip = address
Nick Coghlandc9b2552012-05-20 21:01:57 +10001896 return
1897
1898 # Constructing from a packed address
Nick Coghlan5cf896f2012-07-07 01:43:31 +10001899 if isinstance(address, bytes):
Nick Coghlan297b1432012-07-08 17:11:04 +10001900 self._check_packed_address(address, 16)
Nick Coghlandb7920b2012-08-20 10:19:12 +10001901 self._ip = int.from_bytes(address, 'big')
Nick Coghlandc9b2552012-05-20 21:01:57 +10001902 return
1903
1904 # Assume input argument to be string or any object representation
1905 # which converts into a formatted IP string.
1906 addr_str = str(address)
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +02001907 if '/' in addr_str:
1908 raise AddressValueError("Unexpected '/' in %r" % address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10001909 self._ip = self._ip_int_from_string(addr_str)
1910
Hynek Schlawack91c5a342012-06-05 11:55:58 +02001911 @property
1912 def packed(self):
1913 """The binary representation of this address."""
1914 return v6_int_to_packed(self._ip)
1915
Nick Coghlan730f67f2012-08-05 22:02:18 +10001916 @property
1917 def is_multicast(self):
1918 """Test if the address is reserved for multicast use.
1919
1920 Returns:
1921 A boolean, True if the address is a multicast address.
1922 See RFC 2373 2.7 for details.
1923
1924 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001925 return self in self._constants._multicast_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001926
1927 @property
1928 def is_reserved(self):
1929 """Test if the address is otherwise IETF reserved.
1930
1931 Returns:
1932 A boolean, True if the address is within one of the
1933 reserved IPv6 Network ranges.
1934
1935 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001936 return any(self in x for x in self._constants._reserved_networks)
Nick Coghlan730f67f2012-08-05 22:02:18 +10001937
1938 @property
1939 def is_link_local(self):
1940 """Test if the address is reserved for link-local.
1941
1942 Returns:
1943 A boolean, True if the address is reserved per RFC 4291.
1944
1945 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001946 return self in self._constants._linklocal_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001947
1948 @property
1949 def is_site_local(self):
1950 """Test if the address is reserved for site-local.
1951
1952 Note that the site-local address space has been deprecated by RFC 3879.
1953 Use is_private to test if this address is in the space of unique local
1954 addresses as defined by RFC 4193.
1955
1956 Returns:
1957 A boolean, True if the address is reserved per RFC 3513 2.5.6.
1958
1959 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001960 return self in self._constants._sitelocal_network
Nick Coghlan730f67f2012-08-05 22:02:18 +10001961
1962 @property
Peter Moodybe9c1b12013-10-22 12:36:21 -07001963 @functools.lru_cache()
Nick Coghlan730f67f2012-08-05 22:02:18 +10001964 def is_private(self):
1965 """Test if this address is allocated for private networks.
1966
1967 Returns:
Peter Moody22c31762013-10-21 13:58:06 -07001968 A boolean, True if the address is reserved per
1969 iana-ipv6-special-registry.
Nick Coghlan730f67f2012-08-05 22:02:18 +10001970
1971 """
Antoine Pitroub19e75d2014-05-24 00:32:29 +02001972 return any(self in net for net in self._constants._private_networks)
Peter Moody22c31762013-10-21 13:58:06 -07001973
1974 @property
1975 def is_global(self):
1976 """Test if this address is allocated for public networks.
1977
1978 Returns:
1979 A boolean, true if the address is not reserved per
1980 iana-ipv6-special-registry.
1981
1982 """
1983 return not self.is_private
Nick Coghlan730f67f2012-08-05 22:02:18 +10001984
1985 @property
1986 def is_unspecified(self):
1987 """Test if the address is unspecified.
1988
1989 Returns:
1990 A boolean, True if this is the unspecified address as defined in
1991 RFC 2373 2.5.2.
1992
1993 """
1994 return self._ip == 0
1995
1996 @property
1997 def is_loopback(self):
1998 """Test if the address is a loopback address.
1999
2000 Returns:
2001 A boolean, True if the address is a loopback address as defined in
2002 RFC 2373 2.5.3.
2003
2004 """
2005 return self._ip == 1
2006
2007 @property
2008 def ipv4_mapped(self):
2009 """Return the IPv4 mapped address.
2010
2011 Returns:
2012 If the IPv6 address is a v4 mapped address, return the
2013 IPv4 mapped address. Return None otherwise.
2014
2015 """
2016 if (self._ip >> 32) != 0xFFFF:
2017 return None
2018 return IPv4Address(self._ip & 0xFFFFFFFF)
2019
2020 @property
2021 def teredo(self):
2022 """Tuple of embedded teredo IPs.
2023
2024 Returns:
2025 Tuple of the (server, client) IPs or None if the address
2026 doesn't appear to be a teredo address (doesn't start with
2027 2001::/32)
2028
2029 """
2030 if (self._ip >> 96) != 0x20010000:
2031 return None
2032 return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
2033 IPv4Address(~self._ip & 0xFFFFFFFF))
2034
2035 @property
2036 def sixtofour(self):
2037 """Return the IPv4 6to4 embedded address.
2038
2039 Returns:
2040 The IPv4 6to4-embedded address if present or None if the
2041 address doesn't appear to contain a 6to4 embedded address.
2042
2043 """
2044 if (self._ip >> 112) != 0x2002:
2045 return None
2046 return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
2047
Nick Coghlandc9b2552012-05-20 21:01:57 +10002048
2049class IPv6Interface(IPv6Address):
2050
2051 def __init__(self, address):
2052 if isinstance(address, (bytes, int)):
2053 IPv6Address.__init__(self, address)
2054 self.network = IPv6Network(self._ip)
2055 self._prefixlen = self._max_prefixlen
2056 return
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002057 if isinstance(address, tuple):
2058 IPv6Address.__init__(self, address[0])
2059 if len(address) > 1:
2060 self._prefixlen = int(address[1])
2061 else:
2062 self._prefixlen = self._max_prefixlen
2063 self.network = IPv6Network(address, strict=False)
2064 self.netmask = self.network.netmask
2065 self.hostmask = self.network.hostmask
2066 return
Nick Coghlandc9b2552012-05-20 21:01:57 +10002067
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002068 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002069 IPv6Address.__init__(self, addr[0])
2070 self.network = IPv6Network(address, strict=False)
2071 self.netmask = self.network.netmask
2072 self._prefixlen = self.network._prefixlen
2073 self.hostmask = self.network.hostmask
2074
Nick Coghlandc9b2552012-05-20 21:01:57 +10002075 def __str__(self):
2076 return '%s/%d' % (self._string_from_ip_int(self._ip),
2077 self.network.prefixlen)
2078
2079 def __eq__(self, other):
Nick Coghlan3008ec02012-07-08 00:45:33 +10002080 address_equal = IPv6Address.__eq__(self, other)
2081 if not address_equal or address_equal is NotImplemented:
2082 return address_equal
Nick Coghlandc9b2552012-05-20 21:01:57 +10002083 try:
Nick Coghlan3008ec02012-07-08 00:45:33 +10002084 return self.network == other.network
Nick Coghlandc9b2552012-05-20 21:01:57 +10002085 except AttributeError:
Nick Coghlan3008ec02012-07-08 00:45:33 +10002086 # An interface with an associated network is NOT the
2087 # same as an unassociated address. That's why the hash
2088 # takes the extra info into account.
2089 return False
2090
2091 def __lt__(self, other):
2092 address_less = IPv6Address.__lt__(self, other)
2093 if address_less is NotImplemented:
Nick Coghlandc9b2552012-05-20 21:01:57 +10002094 return NotImplemented
Nick Coghlan3008ec02012-07-08 00:45:33 +10002095 try:
2096 return self.network < other.network
2097 except AttributeError:
2098 # We *do* allow addresses and interfaces to be sorted. The
2099 # unassociated address is considered less than all interfaces.
2100 return False
Nick Coghlandc9b2552012-05-20 21:01:57 +10002101
2102 def __hash__(self):
2103 return self._ip ^ self._prefixlen ^ int(self.network.network_address)
2104
Serhiy Storchaka5f38f5c2015-01-18 22:36:33 +02002105 __reduce__ = _IPAddressBase.__reduce__
2106
Nick Coghlandc9b2552012-05-20 21:01:57 +10002107 @property
Nick Coghlandc9b2552012-05-20 21:01:57 +10002108 def ip(self):
2109 return IPv6Address(self._ip)
2110
2111 @property
2112 def with_prefixlen(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10002113 return '%s/%s' % (self._string_from_ip_int(self._ip),
2114 self._prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002115
2116 @property
2117 def with_netmask(self):
Nick Coghlana8517ad2012-08-20 10:04:26 +10002118 return '%s/%s' % (self._string_from_ip_int(self._ip),
2119 self.netmask)
Hynek Schlawack072b1e12012-05-26 12:04:56 +02002120
Nick Coghlandc9b2552012-05-20 21:01:57 +10002121 @property
2122 def with_hostmask(self):
2123 return '%s/%s' % (self._string_from_ip_int(self._ip),
2124 self.hostmask)
2125
Nick Coghlan730f67f2012-08-05 22:02:18 +10002126 @property
2127 def is_unspecified(self):
2128 return self._ip == 0 and self.network.is_unspecified
2129
2130 @property
2131 def is_loopback(self):
2132 return self._ip == 1 and self.network.is_loopback
2133
Nick Coghlandc9b2552012-05-20 21:01:57 +10002134
2135class IPv6Network(_BaseV6, _BaseNetwork):
2136
2137 """This class represents and manipulates 128-bit IPv6 networks.
2138
2139 Attributes: [examples for IPv6('2001:db8::1000/124')]
2140 .network_address: IPv6Address('2001:db8::1000')
2141 .hostmask: IPv6Address('::f')
2142 .broadcast_address: IPv6Address('2001:db8::100f')
2143 .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
2144 .prefixlen: 124
2145
2146 """
2147
Nick Coghlan51c30672012-05-27 00:25:58 +10002148 # Class to use when creating address objects
Nick Coghlan51c30672012-05-27 00:25:58 +10002149 _address_class = IPv6Address
2150
Nick Coghlandc9b2552012-05-20 21:01:57 +10002151 def __init__(self, address, strict=True):
2152 """Instantiate a new IPv6 Network object.
2153
2154 Args:
Hynek Schlawack072b1e12012-05-26 12:04:56 +02002155 address: A string or integer representing the IPv6 network or the
2156 IP and prefix/netmask.
Nick Coghlandc9b2552012-05-20 21:01:57 +10002157 '2001:db8::/128'
2158 '2001:db8:0000:0000:0000:0000:0000:0000/128'
2159 '2001:db8::'
2160 are all functionally the same in IPv6. That is to say,
2161 failing to provide a subnetmask will create an object with
2162 a mask of /128.
2163
2164 Additionally, an integer can be passed, so
2165 IPv6Network('2001:db8::') ==
2166 IPv6Network(42540766411282592856903984951653826560)
2167 or, more generally
2168 IPv6Network(int(IPv6Network('2001:db8::'))) ==
2169 IPv6Network('2001:db8::')
2170
2171 strict: A boolean. If true, ensure that we have been passed
2172 A true network address, eg, 2001:db8::1000/124 and not an
2173 IP address on a network, eg, 2001:db8::1/124.
2174
2175 Raises:
2176 AddressValueError: If address isn't a valid IPv6 address.
2177 NetmaskValueError: If the netmask isn't valid for
2178 an IPv6 address.
2179 ValueError: If strict was True and a network address was not
2180 supplied.
2181
2182 """
2183 _BaseV6.__init__(self, address)
2184 _BaseNetwork.__init__(self, address)
2185
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002186 # Efficient constructor from integer or packed address
2187 if isinstance(address, (bytes, int)):
Nick Coghlandc9b2552012-05-20 21:01:57 +10002188 self.network_address = IPv6Address(address)
Antoine Pitrou45aba182014-05-15 20:18:41 +02002189 self.netmask, self._prefixlen = self._make_netmask(self._max_prefixlen)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002190 return
2191
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002192 if isinstance(address, tuple):
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002193 if len(address) > 1:
Antoine Pitrou45aba182014-05-15 20:18:41 +02002194 arg = address[1]
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002195 else:
Antoine Pitrou45aba182014-05-15 20:18:41 +02002196 arg = self._max_prefixlen
2197 self.netmask, self._prefixlen = self._make_netmask(arg)
Antoine Pitrou5fb195f2014-05-12 20:36:46 +02002198 self.network_address = IPv6Address(address[0])
2199 packed = int(self.network_address)
2200 if packed & int(self.netmask) != packed:
2201 if strict:
2202 raise ValueError('%s has host bits set' % self)
2203 else:
2204 self.network_address = IPv6Address(packed &
2205 int(self.netmask))
Hynek Schlawacked36b2e2012-06-08 15:21:21 +02002206 return
Nick Coghlandc9b2552012-05-20 21:01:57 +10002207
2208 # Assume input argument to be string or any object representation
2209 # which converts into a formatted IP prefix string.
Nick Coghlan36f8dcd2012-07-07 19:23:53 +10002210 addr = _split_optional_netmask(address)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002211
2212 self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))
2213
2214 if len(addr) == 2:
Antoine Pitrou45aba182014-05-15 20:18:41 +02002215 arg = addr[1]
Nick Coghlandc9b2552012-05-20 21:01:57 +10002216 else:
Antoine Pitrou45aba182014-05-15 20:18:41 +02002217 arg = self._max_prefixlen
2218 self.netmask, self._prefixlen = self._make_netmask(arg)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002219
Nick Coghlandc9b2552012-05-20 21:01:57 +10002220 if strict:
2221 if (IPv6Address(int(self.network_address) & int(self.netmask)) !=
2222 self.network_address):
Nick Coghlan912238e2012-07-07 13:34:50 +10002223 raise ValueError('%s has host bits set' % self)
Nick Coghlandc9b2552012-05-20 21:01:57 +10002224 self.network_address = IPv6Address(int(self.network_address) &
2225 int(self.netmask))
2226
2227 if self._prefixlen == (self._max_prefixlen - 1):
2228 self.hosts = self.__iter__
2229
Peter Moody1243c7d2014-03-11 09:55:46 -07002230 def hosts(self):
2231 """Generate Iterator over usable hosts in a network.
2232
2233 This is like __iter__ except it doesn't return the
2234 Subnet-Router anycast address.
2235
2236 """
2237 network = int(self.network_address)
2238 broadcast = int(self.broadcast_address)
2239 for x in range(network + 1, broadcast + 1):
2240 yield self._address_class(x)
2241
Nick Coghlan730f67f2012-08-05 22:02:18 +10002242 @property
2243 def is_site_local(self):
2244 """Test if the address is reserved for site-local.
2245
2246 Note that the site-local address space has been deprecated by RFC 3879.
2247 Use is_private to test if this address is in the space of unique local
2248 addresses as defined by RFC 4193.
2249
2250 Returns:
2251 A boolean, True if the address is reserved per RFC 3513 2.5.6.
2252
2253 """
2254 return (self.network_address.is_site_local and
2255 self.broadcast_address.is_site_local)
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002256
2257
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002258class _IPv6Constants:
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002259
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002260 _linklocal_network = IPv6Network('fe80::/10')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002261
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002262 _multicast_network = IPv6Network('ff00::/8')
2263
2264 _private_networks = [
2265 IPv6Network('::1/128'),
2266 IPv6Network('::/128'),
2267 IPv6Network('::ffff:0:0/96'),
2268 IPv6Network('100::/64'),
2269 IPv6Network('2001::/23'),
2270 IPv6Network('2001:2::/48'),
2271 IPv6Network('2001:db8::/32'),
2272 IPv6Network('2001:10::/28'),
2273 IPv6Network('fc00::/7'),
2274 IPv6Network('fe80::/10'),
2275 ]
2276
2277 _reserved_networks = [
2278 IPv6Network('::/8'), IPv6Network('100::/8'),
2279 IPv6Network('200::/7'), IPv6Network('400::/6'),
2280 IPv6Network('800::/5'), IPv6Network('1000::/4'),
2281 IPv6Network('4000::/3'), IPv6Network('6000::/3'),
2282 IPv6Network('8000::/3'), IPv6Network('A000::/3'),
2283 IPv6Network('C000::/3'), IPv6Network('E000::/4'),
2284 IPv6Network('F000::/5'), IPv6Network('F800::/6'),
2285 IPv6Network('FE00::/9'),
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002286 ]
2287
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002288 _sitelocal_network = IPv6Network('fec0::/10')
Antoine Pitrouf573ce92014-05-23 23:12:24 +02002289
Antoine Pitroub19e75d2014-05-24 00:32:29 +02002290
2291IPv6Address._constants = _IPv6Constants