You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

2172 lines
70 KiB

  1. # Copyright 2007 Google Inc.
  2. # Licensed to PSF under a Contributor Agreement.
  3. """A fast, lightweight IPv4/IPv6 manipulation library in Python.
  4. This library is used to create/poke/manipulate IPv4 and IPv6 addresses
  5. and networks.
  6. """
  7. from __future__ import unicode_literals
  8. __version__ = '1.0.7'
  9. import struct
  10. # Compatibility functions
  11. _compat_int_types = (int,)
  12. try:
  13. _compat_int_types = (int, long)
  14. except NameError:
  15. pass
  16. try:
  17. _compat_str = unicode
  18. except NameError:
  19. _compat_str = str
  20. assert bytes != str
  21. if b'\0'[0] == 0: # Python 3 semantics
  22. _compat_bytes_to_byte_vals = lambda byt: byt
  23. else:
  24. _compat_bytes_to_byte_vals = (lambda byt:
  25. [struct.unpack(b'!B', b)[0] for b in byt])
  26. try:
  27. _compat_int_from_byte_vals = int.from_bytes
  28. except AttributeError:
  29. def _compat_int_from_byte_vals(bytvals, endianess):
  30. assert endianess == 'big'
  31. res = 0
  32. for bv in bytvals:
  33. assert isinstance(bv, _compat_int_types)
  34. res = (res << 8) + bv
  35. return res
  36. def _compat_to_bytes(intval, length, endianess):
  37. assert isinstance(intval, _compat_int_types)
  38. assert endianess == 'big'
  39. if length == 4:
  40. if intval < 0 or intval >= 2 ** 32:
  41. raise struct.error("integer out of range for 'I' format code")
  42. return struct.pack(b'!I', intval)
  43. elif length == 16:
  44. if intval < 0 or intval >= 2 ** 128:
  45. raise struct.error("integer out of range for 'QQ' format code")
  46. return struct.pack(b'!QQ', intval >> 64, intval & 0xffffffffffffffff)
  47. else:
  48. raise NotImplementedError()
  49. if hasattr(int, 'bit_length'):
  50. # Not int.bit_length , since that won't work in 2.7 where long exists
  51. _compat_bit_length = lambda i: i.bit_length()
  52. else:
  53. _compat_bit_length = lambda i: len(bin(abs(i))) - 2
  54. def _compat_range(start, end):
  55. i = start
  56. while i < end:
  57. yield i
  58. i += 1
  59. IPV4LENGTH = 32
  60. IPV6LENGTH = 128
  61. class AddressValueError(ValueError):
  62. """A Value Error related to the address."""
  63. class NetmaskValueError(ValueError):
  64. """A Value Error related to the netmask."""
  65. def ip_address(address):
  66. """Take an IP string/int and return an object of the correct type.
  67. Args:
  68. address: A string or integer, the IP address. Either IPv4 or
  69. IPv6 addresses may be supplied; integers less than 2**32 will
  70. be considered to be IPv4 by default.
  71. Returns:
  72. An IPv4Address or IPv6Address object.
  73. Raises:
  74. ValueError: if the *address* passed isn't either a v4 or a v6
  75. address
  76. """
  77. try:
  78. return IPv4Address(address)
  79. except (AddressValueError, NetmaskValueError):
  80. pass
  81. try:
  82. return IPv6Address(address)
  83. except (AddressValueError, NetmaskValueError):
  84. pass
  85. if isinstance(address, bytes):
  86. raise AddressValueError(
  87. '%r does not appear to be an IPv4 or IPv6 address. '
  88. 'Did you pass in a bytes (str in Python 2) instead of'
  89. ' a unicode object?' % address)
  90. raise ValueError('%r does not appear to be an IPv4 or IPv6 address' %
  91. address)
  92. def ip_network(address, strict=True):
  93. """Take an IP string/int and return an object of the correct type.
  94. Args:
  95. address: A string or integer, the IP network. Either IPv4 or
  96. IPv6 networks may be supplied; integers less than 2**32 will
  97. be considered to be IPv4 by default.
  98. Returns:
  99. An IPv4Network or IPv6Network object.
  100. Raises:
  101. ValueError: if the string passed isn't either a v4 or a v6
  102. address. Or if the network has host bits set.
  103. """
  104. try:
  105. return IPv4Network(address, strict)
  106. except (AddressValueError, NetmaskValueError):
  107. pass
  108. try:
  109. return IPv6Network(address, strict)
  110. except (AddressValueError, NetmaskValueError):
  111. pass
  112. raise ValueError('%r does not appear to be an IPv4 or IPv6 network' %
  113. address)
  114. def ip_interface(address):
  115. """Take an IP string/int and return an object of the correct type.
  116. Args:
  117. address: A string or integer, the IP address. Either IPv4 or
  118. IPv6 addresses may be supplied; integers less than 2**32 will
  119. be considered to be IPv4 by default.
  120. Returns:
  121. An IPv4Interface or IPv6Interface object.
  122. Raises:
  123. ValueError: if the string passed isn't either a v4 or a v6
  124. address.
  125. Notes:
  126. The IPv?Interface classes describe an Address on a particular
  127. Network, so they're basically a combination of both the Address
  128. and Network classes.
  129. """
  130. try:
  131. return IPv4Interface(address)
  132. except (AddressValueError, NetmaskValueError):
  133. pass
  134. try:
  135. return IPv6Interface(address)
  136. except (AddressValueError, NetmaskValueError):
  137. pass
  138. raise ValueError('%r does not appear to be an IPv4 or IPv6 interface' %
  139. address)
  140. def v4_int_to_packed(address):
  141. """Represent an address as 4 packed bytes in network (big-endian) order.
  142. Args:
  143. address: An integer representation of an IPv4 IP address.
  144. Returns:
  145. The integer address packed as 4 bytes in network (big-endian) order.
  146. Raises:
  147. ValueError: If the integer is negative or too large to be an
  148. IPv4 IP address.
  149. """
  150. try:
  151. return _compat_to_bytes(address, 4, 'big')
  152. except:
  153. raise ValueError("Address negative or too large for IPv4")
  154. def v6_int_to_packed(address):
  155. """Represent an address as 16 packed bytes in network (big-endian) order.
  156. Args:
  157. address: An integer representation of an IPv6 IP address.
  158. Returns:
  159. The integer address packed as 16 bytes in network (big-endian) order.
  160. """
  161. try:
  162. return _compat_to_bytes(address, 16, 'big')
  163. except:
  164. raise ValueError("Address negative or too large for IPv6")
  165. def _split_optional_netmask(address):
  166. """Helper to split the netmask and raise AddressValueError if needed"""
  167. addr = _compat_str(address).split('/')
  168. if len(addr) > 2:
  169. raise AddressValueError("Only one '/' permitted in %r" % address)
  170. return addr
  171. def _find_address_range(addresses):
  172. """Find a sequence of IPv#Address.
  173. Args:
  174. addresses: a list of IPv#Address objects.
  175. Returns:
  176. A tuple containing the first and last IP addresses in the sequence.
  177. """
  178. first = last = addresses[0]
  179. for ip in addresses[1:]:
  180. if ip._ip == last._ip + 1:
  181. last = ip
  182. else:
  183. break
  184. return (first, last)
  185. def _count_righthand_zero_bits(number, bits):
  186. """Count the number of zero bits on the right hand side.
  187. Args:
  188. number: an integer.
  189. bits: maximum number of bits to count.
  190. Returns:
  191. The number of zero bits on the right hand side of the number.
  192. """
  193. if number == 0:
  194. return bits
  195. for i in range(bits):
  196. if (number >> i) & 1:
  197. return i
  198. # All bits of interest were zero, even if there are more in the number
  199. return bits
  200. def summarize_address_range(first, last):
  201. """Summarize a network range given the first and last IP addresses.
  202. Example:
  203. >>> list(summarize_address_range(IPv4Address('192.0.2.0'),
  204. ... IPv4Address('192.0.2.130')))
  205. ... #doctest: +NORMALIZE_WHITESPACE
  206. [IPv4Network('192.0.2.0/25'), IPv4Network('192.0.2.128/31'),
  207. IPv4Network('192.0.2.130/32')]
  208. Args:
  209. first: the first IPv4Address or IPv6Address in the range.
  210. last: the last IPv4Address or IPv6Address in the range.
  211. Returns:
  212. An iterator of the summarized IPv(4|6) network objects.
  213. Raise:
  214. TypeError:
  215. If the first and last objects are not IP addresses.
  216. If the first and last objects are not the same version.
  217. ValueError:
  218. If the last object is not greater than the first.
  219. If the version of the first address is not 4 or 6.
  220. """
  221. if (not (isinstance(first, _BaseAddress) and
  222. isinstance(last, _BaseAddress))):
  223. raise TypeError('first and last must be IP addresses, not networks')
  224. if first.version != last.version:
  225. raise TypeError("%s and %s are not of the same version" %
  226. (first, last))
  227. if first > last:
  228. raise ValueError('last IP address must be greater than first')
  229. if first.version == 4:
  230. ip = IPv4Network
  231. elif first.version == 6:
  232. ip = IPv6Network
  233. else:
  234. raise ValueError('unknown IP version')
  235. ip_bits = first._max_prefixlen
  236. first_int = first._ip
  237. last_int = last._ip
  238. while first_int <= last_int:
  239. nbits = min(_count_righthand_zero_bits(first_int, ip_bits),
  240. _compat_bit_length(last_int - first_int + 1) - 1)
  241. net = ip('%s/%d' % (first, ip_bits - nbits))
  242. yield net
  243. first_int += 1 << nbits
  244. if first_int - 1 == ip._ALL_ONES:
  245. break
  246. first = first.__class__(first_int)
  247. def _collapse_addresses_recursive(addresses):
  248. """Loops through the addresses, collapsing concurrent netblocks.
  249. Example:
  250. ip1 = IPv4Network('192.0.2.0/26')
  251. ip2 = IPv4Network('192.0.2.64/26')
  252. ip3 = IPv4Network('192.0.2.128/26')
  253. ip4 = IPv4Network('192.0.2.192/26')
  254. _collapse_addresses_recursive([ip1, ip2, ip3, ip4]) ->
  255. [IPv4Network('192.0.2.0/24')]
  256. This shouldn't be called directly; it is called via
  257. collapse_addresses([]).
  258. Args:
  259. addresses: A list of IPv4Network's or IPv6Network's
  260. Returns:
  261. A list of IPv4Network's or IPv6Network's depending on what we were
  262. passed.
  263. """
  264. while True:
  265. last_addr = None
  266. ret_array = []
  267. optimized = False
  268. for cur_addr in addresses:
  269. if not ret_array:
  270. last_addr = cur_addr
  271. ret_array.append(cur_addr)
  272. elif (cur_addr.network_address >= last_addr.network_address and
  273. cur_addr.broadcast_address <= last_addr.broadcast_address):
  274. optimized = True
  275. elif cur_addr == list(last_addr.supernet().subnets())[1]:
  276. ret_array[-1] = last_addr = last_addr.supernet()
  277. optimized = True
  278. else:
  279. last_addr = cur_addr
  280. ret_array.append(cur_addr)
  281. addresses = ret_array
  282. if not optimized:
  283. return addresses
  284. def collapse_addresses(addresses):
  285. """Collapse a list of IP objects.
  286. Example:
  287. collapse_addresses([IPv4Network('192.0.2.0/25'),
  288. IPv4Network('192.0.2.128/25')]) ->
  289. [IPv4Network('192.0.2.0/24')]
  290. Args:
  291. addresses: An iterator of IPv4Network or IPv6Network objects.
  292. Returns:
  293. An iterator of the collapsed IPv(4|6)Network objects.
  294. Raises:
  295. TypeError: If passed a list of mixed version objects.
  296. """
  297. i = 0
  298. addrs = []
  299. ips = []
  300. nets = []
  301. # split IP addresses and networks
  302. for ip in addresses:
  303. if isinstance(ip, _BaseAddress):
  304. if ips and ips[-1]._version != ip._version:
  305. raise TypeError("%s and %s are not of the same version" % (
  306. ip, ips[-1]))
  307. ips.append(ip)
  308. elif ip._prefixlen == ip._max_prefixlen:
  309. if ips and ips[-1]._version != ip._version:
  310. raise TypeError("%s and %s are not of the same version" % (
  311. ip, ips[-1]))
  312. try:
  313. ips.append(ip.ip)
  314. except AttributeError:
  315. ips.append(ip.network_address)
  316. else:
  317. if nets and nets[-1]._version != ip._version:
  318. raise TypeError("%s and %s are not of the same version" % (
  319. ip, nets[-1]))
  320. nets.append(ip)
  321. # sort and dedup
  322. ips = sorted(set(ips))
  323. nets = sorted(set(nets))
  324. while i < len(ips):
  325. (first, last) = _find_address_range(ips[i:])
  326. i = ips.index(last) + 1
  327. addrs.extend(summarize_address_range(first, last))
  328. return iter(_collapse_addresses_recursive(sorted(
  329. addrs + nets, key=_BaseNetwork._get_networks_key)))
  330. def get_mixed_type_key(obj):
  331. """Return a key suitable for sorting between networks and addresses.
  332. Address and Network objects are not sortable by default; they're
  333. fundamentally different so the expression
  334. IPv4Address('192.0.2.0') <= IPv4Network('192.0.2.0/24')
  335. doesn't make any sense. There are some times however, where you may wish
  336. to have ipaddress sort these for you anyway. If you need to do this, you
  337. can use this function as the key= argument to sorted().
  338. Args:
  339. obj: either a Network or Address object.
  340. Returns:
  341. appropriate key.
  342. """
  343. if isinstance(obj, _BaseNetwork):
  344. return obj._get_networks_key()
  345. elif isinstance(obj, _BaseAddress):
  346. return obj._get_address_key()
  347. return NotImplemented
  348. class _TotalOrderingMixin(object):
  349. # Helper that derives the other comparison operations from
  350. # __lt__ and __eq__
  351. # We avoid functools.total_ordering because it doesn't handle
  352. # NotImplemented correctly yet (http://bugs.python.org/issue10042)
  353. def __eq__(self, other):
  354. raise NotImplementedError
  355. def __ne__(self, other):
  356. equal = self.__eq__(other)
  357. if equal is NotImplemented:
  358. return NotImplemented
  359. return not equal
  360. def __lt__(self, other):
  361. raise NotImplementedError
  362. def __le__(self, other):
  363. less = self.__lt__(other)
  364. if less is NotImplemented or not less:
  365. return self.__eq__(other)
  366. return less
  367. def __gt__(self, other):
  368. less = self.__lt__(other)
  369. if less is NotImplemented:
  370. return NotImplemented
  371. equal = self.__eq__(other)
  372. if equal is NotImplemented:
  373. return NotImplemented
  374. return not (less or equal)
  375. def __ge__(self, other):
  376. less = self.__lt__(other)
  377. if less is NotImplemented:
  378. return NotImplemented
  379. return not less
  380. class _IPAddressBase(_TotalOrderingMixin):
  381. """The mother class."""
  382. @property
  383. def exploded(self):
  384. """Return the longhand version of the IP address as a string."""
  385. return self._explode_shorthand_ip_string()
  386. @property
  387. def compressed(self):
  388. """Return the shorthand version of the IP address as a string."""
  389. return _compat_str(self)
  390. @property
  391. def version(self):
  392. msg = '%200s has no version specified' % (type(self),)
  393. raise NotImplementedError(msg)
  394. def _check_int_address(self, address):
  395. if address < 0:
  396. msg = "%d (< 0) is not permitted as an IPv%d address"
  397. raise AddressValueError(msg % (address, self._version))
  398. if address > self._ALL_ONES:
  399. msg = "%d (>= 2**%d) is not permitted as an IPv%d address"
  400. raise AddressValueError(msg % (address, self._max_prefixlen,
  401. self._version))
  402. def _check_packed_address(self, address, expected_len):
  403. address_len = len(address)
  404. if address_len != expected_len:
  405. msg = ("%r (len %d != %d) is not permitted as an IPv%d address "
  406. "(did you pass in a bytes instead of a unicode object?)")
  407. raise AddressValueError(msg % (address, address_len,
  408. expected_len, self._version))
  409. def _ip_int_from_prefix(self, prefixlen=None):
  410. """Turn the prefix length netmask into a int for comparison.
  411. Args:
  412. prefixlen: An integer, the prefix length.
  413. Returns:
  414. An integer.
  415. """
  416. if prefixlen is None:
  417. prefixlen = self._prefixlen
  418. return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen)
  419. def _prefix_from_ip_int(self, ip_int, mask=32):
  420. """Return prefix length from the decimal netmask.
  421. Args:
  422. ip_int: An integer, the IP address.
  423. mask: The netmask. Defaults to 32.
  424. Returns:
  425. An integer, the prefix length.
  426. """
  427. return mask - _count_righthand_zero_bits(ip_int, mask)
  428. def _ip_string_from_prefix(self, prefixlen=None):
  429. """Turn a prefix length into a dotted decimal string.
  430. Args:
  431. prefixlen: An integer, the netmask prefix length.
  432. Returns:
  433. A string, the dotted decimal netmask string.
  434. """
  435. if not prefixlen:
  436. prefixlen = self._prefixlen
  437. return self._string_from_ip_int(self._ip_int_from_prefix(prefixlen))
  438. class _BaseAddress(_IPAddressBase):
  439. """A generic IP object.
  440. This IP class contains the version independent methods which are
  441. used by single IP addresses.
  442. """
  443. def __init__(self, address):
  444. if (not isinstance(address, bytes) and '/' in _compat_str(address)):
  445. raise AddressValueError("Unexpected '/' in %r" % address)
  446. def __int__(self):
  447. return self._ip
  448. def __eq__(self, other):
  449. try:
  450. return (self._ip == other._ip
  451. and self._version == other._version)
  452. except AttributeError:
  453. return NotImplemented
  454. def __lt__(self, other):
  455. if self._version != other._version:
  456. raise TypeError('%s and %s are not of the same version' % (
  457. self, other))
  458. if not isinstance(other, _BaseAddress):
  459. raise TypeError('%s and %s are not of the same type' % (
  460. self, other))
  461. if self._ip != other._ip:
  462. return self._ip < other._ip
  463. return False
  464. # Shorthand for Integer addition and subtraction. This is not
  465. # meant to ever support addition/subtraction of addresses.
  466. def __add__(self, other):
  467. if not isinstance(other, _compat_int_types):
  468. return NotImplemented
  469. return self.__class__(int(self) + other)
  470. def __sub__(self, other):
  471. if not isinstance(other, _compat_int_types):
  472. return NotImplemented
  473. return self.__class__(int(self) - other)
  474. def __repr__(self):
  475. return '%s(%r)' % (self.__class__.__name__, _compat_str(self))
  476. def __str__(self):
  477. return _compat_str(self._string_from_ip_int(self._ip))
  478. def __hash__(self):
  479. return hash(hex(int(self._ip)))
  480. def _get_address_key(self):
  481. return (self._version, self)
  482. class _BaseNetwork(_IPAddressBase):
  483. """A generic IP network object.
  484. This IP class contains the version independent methods which are
  485. used by networks.
  486. """
  487. def __init__(self, address):
  488. self._cache = {}
  489. def __repr__(self):
  490. return '%s(%r)' % (self.__class__.__name__, _compat_str(self))
  491. def __str__(self):
  492. return '%s/%d' % (self.network_address, self.prefixlen)
  493. def hosts(self):
  494. """Generate Iterator over usable hosts in a network.
  495. This is like __iter__ except it doesn't return the network
  496. or broadcast addresses.
  497. """
  498. network = int(self.network_address)
  499. broadcast = int(self.broadcast_address)
  500. for x in _compat_range(network + 1, broadcast):
  501. yield self._address_class(x)
  502. def __iter__(self):
  503. network = int(self.network_address)
  504. broadcast = int(self.broadcast_address)
  505. for x in _compat_range(network, broadcast + 1):
  506. yield self._address_class(x)
  507. def __getitem__(self, n):
  508. network = int(self.network_address)
  509. broadcast = int(self.broadcast_address)
  510. if n >= 0:
  511. if network + n > broadcast:
  512. raise IndexError
  513. return self._address_class(network + n)
  514. else:
  515. n += 1
  516. if broadcast + n < network:
  517. raise IndexError
  518. return self._address_class(broadcast + n)
  519. def __lt__(self, other):
  520. if self._version != other._version:
  521. raise TypeError('%s and %s are not of the same version' % (
  522. self, other))
  523. if not isinstance(other, _BaseNetwork):
  524. raise TypeError('%s and %s are not of the same type' % (
  525. self, other))
  526. if self.network_address != other.network_address:
  527. return self.network_address < other.network_address
  528. if self.netmask != other.netmask:
  529. return self.netmask < other.netmask
  530. return False
  531. def __eq__(self, other):
  532. try:
  533. return (self._version == other._version and
  534. self.network_address == other.network_address and
  535. int(self.netmask) == int(other.netmask))
  536. except AttributeError:
  537. return NotImplemented
  538. def __hash__(self):
  539. return hash(int(self.network_address) ^ int(self.netmask))
  540. def __contains__(self, other):
  541. # always false if one is v4 and the other is v6.
  542. if self._version != other._version:
  543. return False
  544. # dealing with another network.
  545. if isinstance(other, _BaseNetwork):
  546. return False
  547. # dealing with another address
  548. else:
  549. # address
  550. return (int(self.network_address) <= int(other._ip) <=
  551. int(self.broadcast_address))
  552. def overlaps(self, other):
  553. """Tell if self is partly contained in other."""
  554. return self.network_address in other or (
  555. self.broadcast_address in other or (
  556. other.network_address in self or (
  557. other.broadcast_address in self)))
  558. @property
  559. def broadcast_address(self):
  560. x = self._cache.get('broadcast_address')
  561. if x is None:
  562. x = self._address_class(int(self.network_address) |
  563. int(self.hostmask))
  564. self._cache['broadcast_address'] = x
  565. return x
  566. @property
  567. def hostmask(self):
  568. x = self._cache.get('hostmask')
  569. if x is None:
  570. x = self._address_class(int(self.netmask) ^ self._ALL_ONES)
  571. self._cache['hostmask'] = x
  572. return x
  573. @property
  574. def with_prefixlen(self):
  575. return '%s/%d' % (self.network_address, self._prefixlen)
  576. @property
  577. def with_netmask(self):
  578. return '%s/%s' % (self.network_address, self.netmask)
  579. @property
  580. def with_hostmask(self):
  581. return '%s/%s' % (self.network_address, self.hostmask)
  582. @property
  583. def num_addresses(self):
  584. """Number of hosts in the current subnet."""
  585. return int(self.broadcast_address) - int(self.network_address) + 1
  586. @property
  587. def _address_class(self):
  588. # Returning bare address objects (rather than interfaces) allows for
  589. # more consistent behaviour across the network address, broadcast
  590. # address and individual host addresses.
  591. msg = '%200s has no associated address class' % (type(self),)
  592. raise NotImplementedError(msg)
  593. @property
  594. def prefixlen(self):
  595. return self._prefixlen
  596. def address_exclude(self, other):
  597. """Remove an address from a larger block.
  598. For example:
  599. addr1 = ip_network('192.0.2.0/28')
  600. addr2 = ip_network('192.0.2.1/32')
  601. addr1.address_exclude(addr2) =
  602. [IPv4Network('192.0.2.0/32'), IPv4Network('192.0.2.2/31'),
  603. IPv4Network('192.0.2.4/30'), IPv4Network('192.0.2.8/29')]
  604. or IPv6:
  605. addr1 = ip_network('2001:db8::1/32')
  606. addr2 = ip_network('2001:db8::1/128')
  607. addr1.address_exclude(addr2) =
  608. [ip_network('2001:db8::1/128'),
  609. ip_network('2001:db8::2/127'),
  610. ip_network('2001:db8::4/126'),
  611. ip_network('2001:db8::8/125'),
  612. ...
  613. ip_network('2001:db8:8000::/33')]
  614. Args:
  615. other: An IPv4Network or IPv6Network object of the same type.
  616. Returns:
  617. An iterator of the IPv(4|6)Network objects which is self
  618. minus other.
  619. Raises:
  620. TypeError: If self and other are of difffering address
  621. versions, or if other is not a network object.
  622. ValueError: If other is not completely contained by self.
  623. """
  624. if not self._version == other._version:
  625. raise TypeError("%s and %s are not of the same version" % (
  626. self, other))
  627. if not isinstance(other, _BaseNetwork):
  628. raise TypeError("%s is not a network object" % other)
  629. if not (other.network_address >= self.network_address and
  630. other.broadcast_address <= self.broadcast_address):
  631. raise ValueError('%s not contained in %s' % (other, self))
  632. if other == self:
  633. raise StopIteration
  634. # Make sure we're comparing the network of other.
  635. other = other.__class__('%s/%s' % (other.network_address,
  636. other.prefixlen))
  637. s1, s2 = self.subnets()
  638. while s1 != other and s2 != other:
  639. if (other.network_address >= s1.network_address and
  640. other.broadcast_address <= s1.broadcast_address):
  641. yield s2
  642. s1, s2 = s1.subnets()
  643. elif (other.network_address >= s2.network_address and
  644. other.broadcast_address <= s2.broadcast_address):
  645. yield s1
  646. s1, s2 = s2.subnets()
  647. else:
  648. # If we got here, there's a bug somewhere.
  649. raise AssertionError('Error performing exclusion: '
  650. 's1: %s s2: %s other: %s' %
  651. (s1, s2, other))
  652. if s1 == other:
  653. yield s2
  654. elif s2 == other:
  655. yield s1
  656. else:
  657. # If we got here, there's a bug somewhere.
  658. raise AssertionError('Error performing exclusion: '
  659. 's1: %s s2: %s other: %s' %
  660. (s1, s2, other))
  661. def compare_networks(self, other):
  662. """Compare two IP objects.
  663. This is only concerned about the comparison of the integer
  664. representation of the network addresses. This means that the
  665. host bits aren't considered at all in this method. If you want
  666. to compare host bits, you can easily enough do a
  667. 'HostA._ip < HostB._ip'
  668. Args:
  669. other: An IP object.
  670. Returns:
  671. If the IP versions of self and other are the same, returns:
  672. -1 if self < other:
  673. eg: IPv4Network('192.0.2.0/25') < IPv4Network('192.0.2.128/25')
  674. IPv6Network('2001:db8::1000/124') <
  675. IPv6Network('2001:db8::2000/124')
  676. 0 if self == other
  677. eg: IPv4Network('192.0.2.0/24') == IPv4Network('192.0.2.0/24')
  678. IPv6Network('2001:db8::1000/124') ==
  679. IPv6Network('2001:db8::1000/124')
  680. 1 if self > other
  681. eg: IPv4Network('192.0.2.128/25') > IPv4Network('192.0.2.0/25')
  682. IPv6Network('2001:db8::2000/124') >
  683. IPv6Network('2001:db8::1000/124')
  684. Raises:
  685. TypeError if the IP versions are different.
  686. """
  687. # does this need to raise a ValueError?
  688. if self._version != other._version:
  689. raise TypeError('%s and %s are not of the same type' % (
  690. self, other))
  691. # self._version == other._version below here:
  692. if self.network_address < other.network_address:
  693. return -1
  694. if self.network_address > other.network_address:
  695. return 1
  696. # self.network_address == other.network_address below here:
  697. if self.netmask < other.netmask:
  698. return -1
  699. if self.netmask > other.netmask:
  700. return 1
  701. return 0
  702. def _get_networks_key(self):
  703. """Network-only key function.
  704. Returns an object that identifies this address' network and
  705. netmask. This function is a suitable "key" argument for sorted()
  706. and list.sort().
  707. """
  708. return (self._version, self.network_address, self.netmask)
  709. def subnets(self, prefixlen_diff=1, new_prefix=None):
  710. """The subnets which join to make the current subnet.
  711. In the case that self contains only one IP
  712. (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
  713. for IPv6), yield an iterator with just ourself.
  714. Args:
  715. prefixlen_diff: An integer, the amount the prefix length
  716. should be increased by. This should not be set if
  717. new_prefix is also set.
  718. new_prefix: The desired new prefix length. This must be a
  719. larger number (smaller prefix) than the existing prefix.
  720. This should not be set if prefixlen_diff is also set.
  721. Returns:
  722. An iterator of IPv(4|6) objects.
  723. Raises:
  724. ValueError: The prefixlen_diff is too small or too large.
  725. OR
  726. prefixlen_diff and new_prefix are both set or new_prefix
  727. is a smaller number than the current prefix (smaller
  728. number means a larger network)
  729. """
  730. if self._prefixlen == self._max_prefixlen:
  731. yield self
  732. return
  733. if new_prefix is not None:
  734. if new_prefix < self._prefixlen:
  735. raise ValueError('new prefix must be longer')
  736. if prefixlen_diff != 1:
  737. raise ValueError('cannot set prefixlen_diff and new_prefix')
  738. prefixlen_diff = new_prefix - self._prefixlen
  739. if prefixlen_diff < 0:
  740. raise ValueError('prefix length diff must be > 0')
  741. new_prefixlen = self._prefixlen + prefixlen_diff
  742. if not self._is_valid_netmask(str(new_prefixlen)):
  743. raise ValueError(
  744. 'prefix length diff %d is invalid for netblock %s' % (
  745. new_prefixlen, self))
  746. first = self.__class__('%s/%s' %
  747. (self.network_address,
  748. self._prefixlen + prefixlen_diff))
  749. yield first
  750. current = first
  751. while True:
  752. broadcast = current.broadcast_address
  753. if broadcast == self.broadcast_address:
  754. return
  755. new_addr = self._address_class(int(broadcast) + 1)
  756. current = self.__class__('%s/%s' % (new_addr,
  757. new_prefixlen))
  758. yield current
  759. def supernet(self, prefixlen_diff=1, new_prefix=None):
  760. """The supernet containing the current network.
  761. Args:
  762. prefixlen_diff: An integer, the amount the prefix length of
  763. the network should be decreased by. For example, given a
  764. /24 network and a prefixlen_diff of 3, a supernet with a
  765. /21 netmask is returned.
  766. Returns:
  767. An IPv4 network object.
  768. Raises:
  769. ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have
  770. a negative prefix length.
  771. OR
  772. If prefixlen_diff and new_prefix are both set or new_prefix is a
  773. larger number than the current prefix (larger number means a
  774. smaller network)
  775. """
  776. if self._prefixlen == 0:
  777. return self
  778. if new_prefix is not None:
  779. if new_prefix > self._prefixlen:
  780. raise ValueError('new prefix must be shorter')
  781. if prefixlen_diff != 1:
  782. raise ValueError('cannot set prefixlen_diff and new_prefix')
  783. prefixlen_diff = self._prefixlen - new_prefix
  784. if self.prefixlen - prefixlen_diff < 0:
  785. raise ValueError(
  786. 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
  787. (self.prefixlen, prefixlen_diff))
  788. # TODO (pmoody): optimize this.
  789. t = self.__class__('%s/%d' % (self.network_address,
  790. self.prefixlen - prefixlen_diff),
  791. strict=False)
  792. return t.__class__('%s/%d' % (t.network_address, t.prefixlen))
  793. @property
  794. def is_multicast(self):
  795. """Test if the address is reserved for multicast use.
  796. Returns:
  797. A boolean, True if the address is a multicast address.
  798. See RFC 2373 2.7 for details.
  799. """
  800. return (self.network_address.is_multicast and
  801. self.broadcast_address.is_multicast)
  802. @property
  803. def is_reserved(self):
  804. """Test if the address is otherwise IETF reserved.
  805. Returns:
  806. A boolean, True if the address is within one of the
  807. reserved IPv6 Network ranges.
  808. """
  809. return (self.network_address.is_reserved and
  810. self.broadcast_address.is_reserved)
  811. @property
  812. def is_link_local(self):
  813. """Test if the address is reserved for link-local.
  814. Returns:
  815. A boolean, True if the address is reserved per RFC 4291.
  816. """
  817. return (self.network_address.is_link_local and
  818. self.broadcast_address.is_link_local)
  819. @property
  820. def is_private(self):
  821. """Test if this address is allocated for private networks.
  822. Returns:
  823. A boolean, True if the address is reserved per RFC 4193.
  824. """
  825. return (self.network_address.is_private and
  826. self.broadcast_address.is_private)
  827. @property
  828. def is_unspecified(self):
  829. """Test if the address is unspecified.
  830. Returns:
  831. A boolean, True if this is the unspecified address as defined in
  832. RFC 2373 2.5.2.
  833. """
  834. return (self.network_address.is_unspecified and
  835. self.broadcast_address.is_unspecified)
  836. @property
  837. def is_loopback(self):
  838. """Test if the address is a loopback address.
  839. Returns:
  840. A boolean, True if the address is a loopback address as defined in
  841. RFC 2373 2.5.3.
  842. """
  843. return (self.network_address.is_loopback and
  844. self.broadcast_address.is_loopback)
  845. class _BaseV4(object):
  846. """Base IPv4 object.
  847. The following methods are used by IPv4 objects in both single IP
  848. addresses and networks.
  849. """
  850. # Equivalent to 255.255.255.255 or 32 bits of 1's.
  851. _ALL_ONES = (2 ** IPV4LENGTH) - 1
  852. _DECIMAL_DIGITS = frozenset('0123456789')
  853. # the valid octets for host and netmasks. only useful for IPv4.
  854. _valid_mask_octets = frozenset((255, 254, 252, 248, 240, 224, 192, 128, 0))
  855. def __init__(self, address):
  856. self._version = 4
  857. self._max_prefixlen = IPV4LENGTH
  858. def _explode_shorthand_ip_string(self):
  859. return _compat_str(self)
  860. def _ip_int_from_string(self, ip_str):
  861. """Turn the given IP string into an integer for comparison.
  862. Args:
  863. ip_str: A string, the IP ip_str.
  864. Returns:
  865. The IP ip_str as an integer.
  866. Raises:
  867. AddressValueError: if ip_str isn't a valid IPv4 Address.
  868. """
  869. if not ip_str:
  870. raise AddressValueError('Address cannot be empty')
  871. octets = ip_str.split('.')
  872. if len(octets) != 4:
  873. raise AddressValueError("Expected 4 octets in %r" % ip_str)
  874. try:
  875. bvs = map(self._parse_octet, octets)
  876. return _compat_int_from_byte_vals(bvs, 'big')
  877. except ValueError as exc:
  878. raise AddressValueError("%s in %r" % (exc, ip_str))
  879. def _parse_octet(self, octet_str):
  880. """Convert a decimal octet into an integer.
  881. Args:
  882. octet_str: A string, the number to parse.
  883. Returns:
  884. The octet as an integer.
  885. Raises:
  886. ValueError: if the octet isn't strictly a decimal from [0..255].
  887. """
  888. if not octet_str:
  889. raise ValueError("Empty octet not permitted")
  890. # Whitelist the characters, since int() allows a lot of bizarre stuff.
  891. if not self._DECIMAL_DIGITS.issuperset(octet_str):
  892. msg = "Only decimal digits permitted in %r"
  893. raise ValueError(msg % octet_str)
  894. # We do the length check second, since the invalid character error
  895. # is likely to be more informative for the user
  896. if len(octet_str) > 3:
  897. msg = "At most 3 characters permitted in %r"
  898. raise ValueError(msg % octet_str)
  899. # Convert to integer (we know digits are legal)
  900. octet_int = int(octet_str, 10)
  901. # Any octets that look like they *might* be written in octal,
  902. # and which don't look exactly the same in both octal and
  903. # decimal are rejected as ambiguous
  904. if octet_int > 7 and octet_str[0] == '0':
  905. msg = "Ambiguous (octal/decimal) value in %r not permitted"
  906. raise ValueError(msg % octet_str)
  907. if octet_int > 255:
  908. raise ValueError("Octet %d (> 255) not permitted" % octet_int)
  909. return octet_int
  910. def _string_from_ip_int(self, ip_int):
  911. """Turns a 32-bit integer into dotted decimal notation.
  912. Args:
  913. ip_int: An integer, the IP address.
  914. Returns:
  915. The IP address as a string in dotted decimal notation.
  916. """
  917. return '.'.join(_compat_str(struct.unpack(b'!B', b)[0]
  918. if isinstance(b, bytes)
  919. else b)
  920. for b in _compat_to_bytes(ip_int, 4, 'big'))
  921. def _is_valid_netmask(self, netmask):
  922. """Verify that the netmask is valid.
  923. Args:
  924. netmask: A string, either a prefix or dotted decimal
  925. netmask.
  926. Returns:
  927. A boolean, True if the prefix represents a valid IPv4
  928. netmask.
  929. """
  930. mask = netmask.split('.')
  931. if len(mask) == 4:
  932. try:
  933. for x in mask:
  934. if int(x) not in self._valid_mask_octets:
  935. return False
  936. except ValueError:
  937. # Found something that isn't an integer or isn't valid
  938. return False
  939. for idx, y in enumerate(mask):
  940. if idx > 0 and y > mask[idx - 1]:
  941. return False
  942. return True
  943. try:
  944. netmask = int(netmask)
  945. except ValueError:
  946. return False
  947. return 0 <= netmask <= self._max_prefixlen
  948. def _is_hostmask(self, ip_str):
  949. """Test if the IP string is a hostmask (rather than a netmask).
  950. Args:
  951. ip_str: A string, the potential hostmask.
  952. Returns:
  953. A boolean, True if the IP string is a hostmask.
  954. """
  955. bits = ip_str.split('.')
  956. try:
  957. parts = [x for x in map(int, bits) if x in self._valid_mask_octets]
  958. except ValueError:
  959. return False
  960. if len(parts) != len(bits):
  961. return False
  962. if parts[0] < parts[-1]:
  963. return True
  964. return False
  965. @property
  966. def max_prefixlen(self):
  967. return self._max_prefixlen
  968. @property
  969. def version(self):
  970. return self._version
  971. class IPv4Address(_BaseV4, _BaseAddress):
  972. """Represent and manipulate single IPv4 Addresses."""
  973. def __init__(self, address):
  974. """
  975. Args:
  976. address: A string or integer representing the IP
  977. Additionally, an integer can be passed, so
  978. IPv4Address('192.0.2.1') == IPv4Address(3221225985).
  979. or, more generally
  980. IPv4Address(int(IPv4Address('192.0.2.1'))) ==
  981. IPv4Address('192.0.2.1')
  982. Raises:
  983. AddressValueError: If ipaddress isn't a valid IPv4 address.
  984. """
  985. _BaseAddress.__init__(self, address)
  986. _BaseV4.__init__(self, address)
  987. # Efficient constructor from integer.
  988. if isinstance(address, _compat_int_types):
  989. self._check_int_address(address)
  990. self._ip = address
  991. return
  992. # Constructing from a packed address
  993. if isinstance(address, bytes):
  994. self._check_packed_address(address, 4)
  995. bvs = _compat_bytes_to_byte_vals(address)
  996. self._ip = _compat_int_from_byte_vals(bvs, 'big')
  997. return
  998. # Assume input argument to be string or any object representation
  999. # which converts into a formatted IP string.
  1000. addr_str = _compat_str(address)
  1001. self._ip = self._ip_int_from_string(addr_str)
  1002. @property
  1003. def packed(self):
  1004. """The binary representation of this address."""
  1005. return v4_int_to_packed(self._ip)
  1006. @property
  1007. def is_reserved(self):
  1008. """Test if the address is otherwise IETF reserved.
  1009. Returns:
  1010. A boolean, True if the address is within the
  1011. reserved IPv4 Network range.
  1012. """
  1013. reserved_network = IPv4Network('240.0.0.0/4')
  1014. return self in reserved_network
  1015. @property
  1016. def is_private(self):
  1017. """Test if this address is allocated for private networks.
  1018. Returns:
  1019. A boolean, True if the address is reserved per RFC 1918.
  1020. """
  1021. private_10 = IPv4Network('10.0.0.0/8')
  1022. private_172 = IPv4Network('172.16.0.0/12')
  1023. private_192 = IPv4Network('192.168.0.0/16')
  1024. return (self in private_10 or
  1025. self in private_172 or
  1026. self in private_192)
  1027. @property
  1028. def is_multicast(self):
  1029. """Test if the address is reserved for multicast use.
  1030. Returns:
  1031. A boolean, True if the address is multicast.
  1032. See RFC 3171 for details.
  1033. """
  1034. multicast_network = IPv4Network('224.0.0.0/4')
  1035. return self in multicast_network
  1036. @property
  1037. def is_unspecified(self):
  1038. """Test if the address is unspecified.
  1039. Returns:
  1040. A boolean, True if this is the unspecified address as defined in
  1041. RFC 5735 3.
  1042. """
  1043. unspecified_address = IPv4Address('0.0.0.0')
  1044. return self == unspecified_address
  1045. @property
  1046. def is_loopback(self):
  1047. """Test if the address is a loopback address.
  1048. Returns:
  1049. A boolean, True if the address is a loopback per RFC 3330.
  1050. """
  1051. loopback_network = IPv4Network('127.0.0.0/8')
  1052. return self in loopback_network
  1053. @property
  1054. def is_link_local(self):
  1055. """Test if the address is reserved for link-local.
  1056. Returns:
  1057. A boolean, True if the address is link-local per RFC 3927.
  1058. """
  1059. linklocal_network = IPv4Network('169.254.0.0/16')
  1060. return self in linklocal_network
  1061. class IPv4Interface(IPv4Address):
  1062. def __init__(self, address):
  1063. if isinstance(address, (bytes,) + _compat_int_types):
  1064. IPv4Address.__init__(self, address)
  1065. self.network = IPv4Network(self._ip)
  1066. self._prefixlen = self._max_prefixlen
  1067. return
  1068. addr = _split_optional_netmask(address)
  1069. IPv4Address.__init__(self, addr[0])
  1070. self.network = IPv4Network(address, strict=False)
  1071. self._prefixlen = self.network._prefixlen
  1072. self.netmask = self.network.netmask
  1073. self.hostmask = self.network.hostmask
  1074. def __str__(self):
  1075. return '%s/%d' % (self._string_from_ip_int(self._ip),
  1076. self.network.prefixlen)
  1077. def __eq__(self, other):
  1078. address_equal = IPv4Address.__eq__(self, other)
  1079. if not address_equal or address_equal is NotImplemented:
  1080. return address_equal
  1081. try:
  1082. return self.network == other.network
  1083. except AttributeError:
  1084. # An interface with an associated network is NOT the
  1085. # same as an unassociated address. That's why the hash
  1086. # takes the extra info into account.
  1087. return False
  1088. def __lt__(self, other):
  1089. address_less = IPv4Address.__lt__(self, other)
  1090. if address_less is NotImplemented:
  1091. return NotImplemented
  1092. try:
  1093. return self.network < other.network
  1094. except AttributeError:
  1095. # We *do* allow addresses and interfaces to be sorted. The
  1096. # unassociated address is considered less than all interfaces.
  1097. return False
  1098. def __hash__(self):
  1099. return self._ip ^ self._prefixlen ^ int(self.network.network_address)
  1100. @property
  1101. def ip(self):
  1102. return IPv4Address(self._ip)
  1103. @property
  1104. def with_prefixlen(self):
  1105. return '%s/%s' % (self._string_from_ip_int(self._ip),
  1106. self._prefixlen)
  1107. @property
  1108. def with_netmask(self):
  1109. return '%s/%s' % (self._string_from_ip_int(self._ip),
  1110. self.netmask)
  1111. @property
  1112. def with_hostmask(self):
  1113. return '%s/%s' % (self._string_from_ip_int(self._ip),
  1114. self.hostmask)
  1115. class IPv4Network(_BaseV4, _BaseNetwork):
  1116. """This class represents and manipulates 32-bit IPv4 network + addresses..
  1117. Attributes: [examples for IPv4Network('192.0.2.0/27')]
  1118. .network_address: IPv4Address('192.0.2.0')
  1119. .hostmask: IPv4Address('0.0.0.31')
  1120. .broadcast_address: IPv4Address('192.0.2.32')
  1121. .netmask: IPv4Address('255.255.255.224')
  1122. .prefixlen: 27
  1123. """
  1124. # Class to use when creating address objects
  1125. _address_class = IPv4Address
  1126. def __init__(self, address, strict=True):
  1127. """Instantiate a new IPv4 network object.
  1128. Args:
  1129. address: A string or integer representing the IP [& network].
  1130. '192.0.2.0/24'
  1131. '192.0.2.0/255.255.255.0'
  1132. '192.0.0.2/0.0.0.255'
  1133. are all functionally the same in IPv4. Similarly,
  1134. '192.0.2.1'
  1135. '192.0.2.1/255.255.255.255'
  1136. '192.0.2.1/32'
  1137. are also functionaly equivalent. That is to say, failing to
  1138. provide a subnetmask will create an object with a mask of /32.
  1139. If the mask (portion after the / in the argument) is given in
  1140. dotted quad form, it is treated as a netmask if it starts with a
  1141. non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
  1142. starts with a zero field (e.g. 0.255.255.255 == /8), with the
  1143. single exception of an all-zero mask which is treated as a
  1144. netmask == /0. If no mask is given, a default of /32 is used.
  1145. Additionally, an integer can be passed, so
  1146. IPv4Network('192.0.2.1') == IPv4Network(3221225985)
  1147. or, more generally
  1148. IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
  1149. IPv4Interface('192.0.2.1')
  1150. Raises:
  1151. AddressValueError: If ipaddress isn't a valid IPv4 address.
  1152. NetmaskValueError: If the netmask isn't valid for
  1153. an IPv4 address.
  1154. ValueError: If strict is True and a network address is not
  1155. supplied.
  1156. """
  1157. _BaseV4.__init__(self, address)
  1158. _BaseNetwork.__init__(self, address)
  1159. # Constructing from a packed address
  1160. if isinstance(address, bytes):
  1161. self.network_address = IPv4Address(address)
  1162. self._prefixlen = self._max_prefixlen
  1163. self.netmask = IPv4Address(self._ALL_ONES)
  1164. #fixme: address/network test here
  1165. return
  1166. # Efficient constructor from integer.
  1167. if isinstance(address, _compat_int_types):
  1168. self.network_address = IPv4Address(address)
  1169. self._prefixlen = self._max_prefixlen
  1170. self.netmask = IPv4Address(self._ALL_ONES)
  1171. #fixme: address/network test here.
  1172. return
  1173. # Assume input argument to be string or any object representation
  1174. # which converts into a formatted IP prefix string.
  1175. addr = _split_optional_netmask(address)
  1176. self.network_address = IPv4Address(self._ip_int_from_string(addr[0]))
  1177. if len(addr) == 2:
  1178. mask = addr[1].split('.')
  1179. if len(mask) == 4:
  1180. # We have dotted decimal netmask.
  1181. if self._is_valid_netmask(addr[1]):
  1182. self.netmask = IPv4Address(self._ip_int_from_string(
  1183. addr[1]))
  1184. elif self._is_hostmask(addr[1]):
  1185. self.netmask = IPv4Address(
  1186. self._ip_int_from_string(addr[1]) ^ self._ALL_ONES)
  1187. else:
  1188. raise NetmaskValueError('%r is not a valid netmask'
  1189. % addr[1])
  1190. self._prefixlen = self._prefix_from_ip_int(int(self.netmask))
  1191. else:
  1192. # We have a netmask in prefix length form.
  1193. if not self._is_valid_netmask(addr[1]):
  1194. raise NetmaskValueError('%r is not a valid netmask'
  1195. % addr[1])
  1196. self._prefixlen = int(addr[1])
  1197. self.netmask = IPv4Address(self._ip_int_from_prefix(
  1198. self._prefixlen))
  1199. else:
  1200. self._prefixlen = self._max_prefixlen
  1201. self.netmask = IPv4Address(self._ip_int_from_prefix(
  1202. self._prefixlen))
  1203. if strict:
  1204. if (IPv4Address(int(self.network_address) & int(self.netmask)) !=
  1205. self.network_address):
  1206. raise ValueError('%s has host bits set' % self)
  1207. self.network_address = IPv4Address(int(self.network_address) &
  1208. int(self.netmask))
  1209. if self._prefixlen == (self._max_prefixlen - 1):
  1210. self.hosts = self.__iter__
  1211. class _BaseV6(object):
  1212. """Base IPv6 object.
  1213. The following methods are used by IPv6 objects in both single IP
  1214. addresses and networks.
  1215. """
  1216. _ALL_ONES = (2 ** IPV6LENGTH) - 1
  1217. _HEXTET_COUNT = 8
  1218. _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
  1219. def __init__(self, address):
  1220. self._version = 6
  1221. self._max_prefixlen = IPV6LENGTH
  1222. def _ip_int_from_string(self, ip_str):
  1223. """Turn an IPv6 ip_str into an integer.
  1224. Args:
  1225. ip_str: A string, the IPv6 ip_str.
  1226. Returns:
  1227. An int, the IPv6 address
  1228. Raises:
  1229. AddressValueError: if ip_str isn't a valid IPv6 Address.
  1230. """
  1231. if not ip_str:
  1232. raise AddressValueError('Address cannot be empty')
  1233. parts = ip_str.split(':')
  1234. # An IPv6 address needs at least 2 colons (3 parts).
  1235. _min_parts = 3
  1236. if len(parts) < _min_parts:
  1237. msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
  1238. raise AddressValueError(msg)
  1239. # If the address has an IPv4-style suffix, convert it to hexadecimal.
  1240. if '.' in parts[-1]:
  1241. try:
  1242. ipv4_int = IPv4Address(parts.pop())._ip
  1243. except AddressValueError as exc:
  1244. raise AddressValueError("%s in %r" % (exc, ip_str))
  1245. parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
  1246. parts.append('%x' % (ipv4_int & 0xFFFF))
  1247. # An IPv6 address can't have more than 8 colons (9 parts).
  1248. # The extra colon comes from using the "::" notation for a single
  1249. # leading or trailing zero part.
  1250. _max_parts = self._HEXTET_COUNT + 1
  1251. if len(parts) > _max_parts:
  1252. msg = ("At most %d colons permitted in %r" %
  1253. (_max_parts - 1, ip_str))
  1254. raise AddressValueError(msg)
  1255. # Disregarding the endpoints, find '::' with nothing in between.
  1256. # This indicates that a run of zeroes has been skipped.
  1257. skip_index = None
  1258. for i in range(1, len(parts) - 1):
  1259. if not parts[i]:
  1260. if skip_index is not None:
  1261. # Can't have more than one '::'
  1262. msg = "At most one '::' permitted in %r" % ip_str
  1263. raise AddressValueError(msg)
  1264. skip_index = i
  1265. # parts_hi is the number of parts to copy from above/before the '::'
  1266. # parts_lo is the number of parts to copy from below/after the '::'
  1267. if skip_index is not None:
  1268. # If we found a '::', then check if it also covers the endpoints.
  1269. parts_hi = skip_index
  1270. parts_lo = len(parts) - skip_index - 1
  1271. if not parts[0]:
  1272. parts_hi -= 1
  1273. if parts_hi:
  1274. msg = "Leading ':' only permitted as part of '::' in %r"
  1275. raise AddressValueError(msg % ip_str) # ^: requires ^::
  1276. if not parts[-1]:
  1277. parts_lo -= 1
  1278. if parts_lo:
  1279. msg = "Trailing ':' only permitted as part of '::' in %r"
  1280. raise AddressValueError(msg % ip_str) # :$ requires ::$
  1281. parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo)
  1282. if parts_skipped < 1:
  1283. msg = "Expected at most %d other parts with '::' in %r"
  1284. raise AddressValueError(msg % (self._HEXTET_COUNT - 1, ip_str))
  1285. else:
  1286. # Otherwise, allocate the entire address to parts_hi. The
  1287. # endpoints could still be empty, but _parse_hextet() will check
  1288. # for that.
  1289. if len(parts) != self._HEXTET_COUNT:
  1290. msg = "Exactly %d parts expected without '::' in %r"
  1291. raise AddressValueError(msg % (self._HEXTET_COUNT, ip_str))
  1292. if not parts[0]:
  1293. msg = "Leading ':' only permitted as part of '::' in %r"
  1294. raise AddressValueError(msg % ip_str) # ^: requires ^::
  1295. if not parts[-1]:
  1296. msg = "Trailing ':' only permitted as part of '::' in %r"
  1297. raise AddressValueError(msg % ip_str) # :$ requires ::$
  1298. parts_hi = len(parts)
  1299. parts_lo = 0
  1300. parts_skipped = 0
  1301. try:
  1302. # Now, parse the hextets into a 128-bit integer.
  1303. ip_int = 0
  1304. for i in range(parts_hi):
  1305. ip_int <<= 16
  1306. ip_int |= self._parse_hextet(parts[i])
  1307. ip_int <<= 16 * parts_skipped
  1308. for i in range(-parts_lo, 0):
  1309. ip_int <<= 16
  1310. ip_int |= self._parse_hextet(parts[i])
  1311. return ip_int
  1312. except ValueError as exc:
  1313. raise AddressValueError("%s in %r" % (exc, ip_str))
  1314. def _parse_hextet(self, hextet_str):
  1315. """Convert an IPv6 hextet string into an integer.
  1316. Args:
  1317. hextet_str: A string, the number to parse.
  1318. Returns:
  1319. The hextet as an integer.
  1320. Raises:
  1321. ValueError: if the input isn't strictly a hex number from
  1322. [0..FFFF].
  1323. """
  1324. # Whitelist the characters, since int() allows a lot of bizarre stuff.
  1325. if not self._HEX_DIGITS.issuperset(hextet_str):
  1326. raise ValueError("Only hex digits permitted in %r" % hextet_str)
  1327. # We do the length check second, since the invalid character error
  1328. # is likely to be more informative for the user
  1329. if len(hextet_str) > 4:
  1330. msg = "At most 4 characters permitted in %r"
  1331. raise ValueError(msg % hextet_str)
  1332. # Length check means we can skip checking the integer value
  1333. return int(hextet_str, 16)
  1334. def _compress_hextets(self, hextets):
  1335. """Compresses a list of hextets.
  1336. Compresses a list of strings, replacing the longest continuous
  1337. sequence of "0" in the list with "" and adding empty strings at
  1338. the beginning or at the end of the string such that subsequently
  1339. calling ":".join(hextets) will produce the compressed version of
  1340. the IPv6 address.
  1341. Args:
  1342. hextets: A list of strings, the hextets to compress.
  1343. Returns:
  1344. A list of strings.
  1345. """
  1346. best_doublecolon_start = -1
  1347. best_doublecolon_len = 0
  1348. doublecolon_start = -1
  1349. doublecolon_len = 0
  1350. for index, hextet in enumerate(hextets):
  1351. if hextet == '0':
  1352. doublecolon_len += 1
  1353. if doublecolon_start == -1:
  1354. # Start of a sequence of zeros.
  1355. doublecolon_start = index
  1356. if doublecolon_len > best_doublecolon_len:
  1357. # This is the longest sequence of zeros so far.
  1358. best_doublecolon_len = doublecolon_len
  1359. best_doublecolon_start = doublecolon_start
  1360. else:
  1361. doublecolon_len = 0
  1362. doublecolon_start = -1
  1363. if best_doublecolon_len > 1:
  1364. best_doublecolon_end = (best_doublecolon_start +
  1365. best_doublecolon_len)
  1366. # For zeros at the end of the address.
  1367. if best_doublecolon_end == len(hextets):
  1368. hextets += ['']
  1369. hextets[best_doublecolon_start:best_doublecolon_end] = ['']
  1370. # For zeros at the beginning of the address.
  1371. if best_doublecolon_start == 0:
  1372. hextets = [''] + hextets
  1373. return hextets
  1374. def _string_from_ip_int(self, ip_int=None):
  1375. """Turns a 128-bit integer into hexadecimal notation.
  1376. Args:
  1377. ip_int: An integer, the IP address.
  1378. Returns:
  1379. A string, the hexadecimal representation of the address.
  1380. Raises:
  1381. ValueError: The address is bigger than 128 bits of all ones.
  1382. """
  1383. if ip_int is None:
  1384. ip_int = int(self._ip)
  1385. if ip_int > self._ALL_ONES:
  1386. raise ValueError('IPv6 address is too large')
  1387. hex_str = '%032x' % ip_int
  1388. hextets = ['%x' % int(hex_str[x:x + 4], 16) for x in range(0, 32, 4)]
  1389. hextets = self._compress_hextets(hextets)
  1390. return ':'.join(hextets)
  1391. def _explode_shorthand_ip_string(self):
  1392. """Expand a shortened IPv6 address.
  1393. Args:
  1394. ip_str: A string, the IPv6 address.
  1395. Returns:
  1396. A string, the expanded IPv6 address.
  1397. """
  1398. if isinstance(self, IPv6Network):
  1399. ip_str = _compat_str(self.network_address)
  1400. elif isinstance(self, IPv6Interface):
  1401. ip_str = _compat_str(self.ip)
  1402. else:
  1403. ip_str = _compat_str(self)
  1404. ip_int = self._ip_int_from_string(ip_str)
  1405. hex_str = '%032x' % ip_int
  1406. parts = [hex_str[x:x + 4] for x in range(0, 32, 4)]
  1407. if isinstance(self, (_BaseNetwork, IPv6Interface)):
  1408. return '%s/%d' % (':'.join(parts), self._prefixlen)
  1409. return ':'.join(parts)
  1410. @property
  1411. def max_prefixlen(self):
  1412. return self._max_prefixlen
  1413. @property
  1414. def version(self):
  1415. return self._version
  1416. class IPv6Address(_BaseV6, _BaseAddress):
  1417. """Represent and manipulate single IPv6 Addresses."""
  1418. def __init__(self, address):
  1419. """Instantiate a new IPv6 address object.
  1420. Args:
  1421. address: A string or integer representing the IP
  1422. Additionally, an integer can be passed, so
  1423. IPv6Address('2001:db8::') ==
  1424. IPv6Address(42540766411282592856903984951653826560)
  1425. or, more generally
  1426. IPv6Address(int(IPv6Address('2001:db8::'))) ==
  1427. IPv6Address('2001:db8::')
  1428. Raises:
  1429. AddressValueError: If address isn't a valid IPv6 address.
  1430. """
  1431. _BaseAddress.__init__(self, address)
  1432. _BaseV6.__init__(self, address)
  1433. # Efficient constructor from integer.
  1434. if isinstance(address, _compat_int_types):
  1435. self._check_int_address(address)
  1436. self._ip = address
  1437. return
  1438. # Constructing from a packed address
  1439. if isinstance(address, bytes):
  1440. self._check_packed_address(address, 16)
  1441. bvs = _compat_bytes_to_byte_vals(address)
  1442. self._ip = _compat_int_from_byte_vals(bvs, 'big')
  1443. return
  1444. # Assume input argument to be string or any object representation
  1445. # which converts into a formatted IP string.
  1446. addr_str = _compat_str(address)
  1447. self._ip = self._ip_int_from_string(addr_str)
  1448. @property
  1449. def packed(self):
  1450. """The binary representation of this address."""
  1451. return v6_int_to_packed(self._ip)
  1452. @property
  1453. def is_multicast(self):
  1454. """Test if the address is reserved for multicast use.
  1455. Returns:
  1456. A boolean, True if the address is a multicast address.
  1457. See RFC 2373 2.7 for details.
  1458. """
  1459. multicast_network = IPv6Network('ff00::/8')
  1460. return self in multicast_network
  1461. @property
  1462. def is_reserved(self):
  1463. """Test if the address is otherwise IETF reserved.
  1464. Returns:
  1465. A boolean, True if the address is within one of the
  1466. reserved IPv6 Network ranges.
  1467. """
  1468. reserved_nets = [IPv6Network('::/8'), IPv6Network('100::/8'),
  1469. IPv6Network('200::/7'), IPv6Network('400::/6'),
  1470. IPv6Network('800::/5'), IPv6Network('1000::/4'),
  1471. IPv6Network('4000::/3'), IPv6Network('6000::/3'),
  1472. IPv6Network('8000::/3'), IPv6Network('A000::/3'),
  1473. IPv6Network('C000::/3'), IPv6Network('E000::/4'),
  1474. IPv6Network('F000::/5'), IPv6Network('F800::/6'),
  1475. IPv6Network('FE00::/9')]
  1476. return any(self in x for x in reserved_nets)
  1477. @property
  1478. def is_link_local(self):
  1479. """Test if the address is reserved for link-local.
  1480. Returns:
  1481. A boolean, True if the address is reserved per RFC 4291.
  1482. """
  1483. linklocal_network = IPv6Network('fe80::/10')
  1484. return self in linklocal_network
  1485. @property
  1486. def is_site_local(self):
  1487. """Test if the address is reserved for site-local.
  1488. Note that the site-local address space has been deprecated by RFC 3879.
  1489. Use is_private to test if this address is in the space of unique local
  1490. addresses as defined by RFC 4193.
  1491. Returns:
  1492. A boolean, True if the address is reserved per RFC 3513 2.5.6.
  1493. """
  1494. sitelocal_network = IPv6Network('fec0::/10')
  1495. return self in sitelocal_network
  1496. @property
  1497. def is_private(self):
  1498. """Test if this address is allocated for private networks.
  1499. Returns:
  1500. A boolean, True if the address is reserved per RFC 4193.
  1501. """
  1502. private_network = IPv6Network('fc00::/7')
  1503. return self in private_network
  1504. @property
  1505. def is_unspecified(self):
  1506. """Test if the address is unspecified.
  1507. Returns:
  1508. A boolean, True if this is the unspecified address as defined in
  1509. RFC 2373 2.5.2.
  1510. """
  1511. return self._ip == 0
  1512. @property
  1513. def is_loopback(self):
  1514. """Test if the address is a loopback address.
  1515. Returns:
  1516. A boolean, True if the address is a loopback address as defined in
  1517. RFC 2373 2.5.3.
  1518. """
  1519. return self._ip == 1
  1520. @property
  1521. def ipv4_mapped(self):
  1522. """Return the IPv4 mapped address.
  1523. Returns:
  1524. If the IPv6 address is a v4 mapped address, return the
  1525. IPv4 mapped address. Return None otherwise.
  1526. """
  1527. if (self._ip >> 32) != 0xFFFF:
  1528. return None
  1529. return IPv4Address(self._ip & 0xFFFFFFFF)
  1530. @property
  1531. def teredo(self):
  1532. """Tuple of embedded teredo IPs.
  1533. Returns:
  1534. Tuple of the (server, client) IPs or None if the address
  1535. doesn't appear to be a teredo address (doesn't start with
  1536. 2001::/32)
  1537. """
  1538. if (self._ip >> 96) != 0x20010000:
  1539. return None
  1540. return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
  1541. IPv4Address(~self._ip & 0xFFFFFFFF))
  1542. @property
  1543. def sixtofour(self):
  1544. """Return the IPv4 6to4 embedded address.
  1545. Returns:
  1546. The IPv4 6to4-embedded address if present or None if the
  1547. address doesn't appear to contain a 6to4 embedded address.
  1548. """
  1549. if (self._ip >> 112) != 0x2002:
  1550. return None
  1551. return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
  1552. class IPv6Interface(IPv6Address):
  1553. def __init__(self, address):
  1554. if isinstance(address, (bytes, _compat_int_types)):
  1555. IPv6Address.__init__(self, address)
  1556. self.network = IPv6Network(self._ip)
  1557. self._prefixlen = self._max_prefixlen
  1558. return
  1559. addr = _split_optional_netmask(address)
  1560. IPv6Address.__init__(self, addr[0])
  1561. self.network = IPv6Network(address, strict=False)
  1562. self.netmask = self.network.netmask
  1563. self._prefixlen = self.network._prefixlen
  1564. self.hostmask = self.network.hostmask
  1565. def __str__(self):
  1566. return '%s/%d' % (self._string_from_ip_int(self._ip),
  1567. self.network.prefixlen)
  1568. def __eq__(self, other):
  1569. address_equal = IPv6Address.__eq__(self, other)
  1570. if not address_equal or address_equal is NotImplemented:
  1571. return address_equal
  1572. try:
  1573. return self.network == other.network
  1574. except AttributeError:
  1575. # An interface with an associated network is NOT the
  1576. # same as an unassociated address. That's why the hash
  1577. # takes the extra info into account.
  1578. return False
  1579. def __lt__(self, other):
  1580. address_less = IPv6Address.__lt__(self, other)
  1581. if address_less is NotImplemented:
  1582. return NotImplemented
  1583. try:
  1584. return self.network < other.network
  1585. except AttributeError:
  1586. # We *do* allow addresses and interfaces to be sorted. The
  1587. # unassociated address is considered less than all interfaces.
  1588. return False
  1589. def __hash__(self):
  1590. return self._ip ^ self._prefixlen ^ int(self.network.network_address)
  1591. @property
  1592. def ip(self):
  1593. return IPv6Address(self._ip)
  1594. @property
  1595. def with_prefixlen(self):
  1596. return '%s/%s' % (self._string_from_ip_int(self._ip),
  1597. self._prefixlen)
  1598. @property
  1599. def with_netmask(self):
  1600. return '%s/%s' % (self._string_from_ip_int(self._ip),
  1601. self.netmask)
  1602. @property
  1603. def with_hostmask(self):
  1604. return '%s/%s' % (self._string_from_ip_int(self._ip),
  1605. self.hostmask)
  1606. @property
  1607. def is_unspecified(self):
  1608. return self._ip == 0 and self.network.is_unspecified
  1609. @property
  1610. def is_loopback(self):
  1611. return self._ip == 1 and self.network.is_loopback
  1612. class IPv6Network(_BaseV6, _BaseNetwork):
  1613. """This class represents and manipulates 128-bit IPv6 networks.
  1614. Attributes: [examples for IPv6('2001:db8::1000/124')]
  1615. .network_address: IPv6Address('2001:db8::1000')
  1616. .hostmask: IPv6Address('::f')
  1617. .broadcast_address: IPv6Address('2001:db8::100f')
  1618. .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
  1619. .prefixlen: 124
  1620. """
  1621. # Class to use when creating address objects
  1622. _address_class = IPv6Address
  1623. def __init__(self, address, strict=True):
  1624. """Instantiate a new IPv6 Network object.
  1625. Args:
  1626. address: A string or integer representing the IPv6 network or the
  1627. IP and prefix/netmask.
  1628. '2001:db8::/128'
  1629. '2001:db8:0000:0000:0000:0000:0000:0000/128'
  1630. '2001:db8::'
  1631. are all functionally the same in IPv6. That is to say,
  1632. failing to provide a subnetmask will create an object with
  1633. a mask of /128.
  1634. Additionally, an integer can be passed, so
  1635. IPv6Network('2001:db8::') ==
  1636. IPv6Network(42540766411282592856903984951653826560)
  1637. or, more generally
  1638. IPv6Network(int(IPv6Network('2001:db8::'))) ==
  1639. IPv6Network('2001:db8::')
  1640. strict: A boolean. If true, ensure that we have been passed
  1641. A true network address, eg, 2001:db8::1000/124 and not an
  1642. IP address on a network, eg, 2001:db8::1/124.
  1643. Raises:
  1644. AddressValueError: If address isn't a valid IPv6 address.
  1645. NetmaskValueError: If the netmask isn't valid for
  1646. an IPv6 address.
  1647. ValueError: If strict was True and a network address was not
  1648. supplied.
  1649. """
  1650. _BaseV6.__init__(self, address)
  1651. _BaseNetwork.__init__(self, address)
  1652. # Efficient constructor from integer.
  1653. if isinstance(address, _compat_int_types):
  1654. self.network_address = IPv6Address(address)
  1655. self._prefixlen = self._max_prefixlen
  1656. self.netmask = IPv6Address(self._ALL_ONES)
  1657. return
  1658. # Constructing from a packed address
  1659. if isinstance(address, bytes):
  1660. self.network_address = IPv6Address(address)
  1661. self._prefixlen = self._max_prefixlen
  1662. self.netmask = IPv6Address(self._ALL_ONES)
  1663. return
  1664. # Assume input argument to be string or any object representation
  1665. # which converts into a formatted IP prefix string.
  1666. addr = _split_optional_netmask(address)
  1667. self.network_address = IPv6Address(self._ip_int_from_string(addr[0]))
  1668. if len(addr) == 2:
  1669. if self._is_valid_netmask(addr[1]):
  1670. self._prefixlen = int(addr[1])
  1671. else:
  1672. raise NetmaskValueError('%r is not a valid netmask'
  1673. % addr[1])
  1674. else:
  1675. self._prefixlen = self._max_prefixlen
  1676. self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen))
  1677. if strict:
  1678. if (IPv6Address(int(self.network_address) & int(self.netmask)) !=
  1679. self.network_address):
  1680. raise ValueError('%s has host bits set' % self)
  1681. self.network_address = IPv6Address(int(self.network_address) &
  1682. int(self.netmask))
  1683. if self._prefixlen == (self._max_prefixlen - 1):
  1684. self.hosts = self.__iter__
  1685. def _is_valid_netmask(self, prefixlen):
  1686. """Verify that the netmask/prefixlen is valid.
  1687. Args:
  1688. prefixlen: A string, the netmask in prefix length format.
  1689. Returns:
  1690. A boolean, True if the prefix represents a valid IPv6
  1691. netmask.
  1692. """
  1693. try:
  1694. prefixlen = int(prefixlen)
  1695. except ValueError:
  1696. return False
  1697. return 0 <= prefixlen <= self._max_prefixlen
  1698. @property
  1699. def is_site_local(self):
  1700. """Test if the address is reserved for site-local.
  1701. Note that the site-local address space has been deprecated by RFC 3879.
  1702. Use is_private to test if this address is in the space of unique local
  1703. addresses as defined by RFC 4193.
  1704. Returns:
  1705. A boolean, True if the address is reserved per RFC 3513 2.5.6.
  1706. """
  1707. return (self.network_address.is_site_local and
  1708. self.broadcast_address.is_site_local)