ipaddress.py 73 KB

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