ipaddress.py 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363
  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 endian
  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 endian
  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 iterable 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 network belongs to a private range.
  846. Returns:
  847. A boolean, True if the network is reserved per
  848. iana-ipv4-special-registry or iana-ipv6-special-registry.
  849. """
  850. return any(self.network_address in priv_network and
  851. self.broadcast_address in priv_network
  852. for priv_network in self._constants._private_networks) and all(
  853. self.network_address not in network and
  854. self.broadcast_address not in network
  855. for network in self._constants._private_networks_exceptions
  856. )
  857. @property
  858. def is_global(self):
  859. """Test if this address is allocated for public networks.
  860. Returns:
  861. A boolean, True if the address is not reserved per
  862. iana-ipv4-special-registry or iana-ipv6-special-registry.
  863. """
  864. return not self.is_private
  865. @property
  866. def is_unspecified(self):
  867. """Test if the address is unspecified.
  868. Returns:
  869. A boolean, True if this is the unspecified address as defined in
  870. RFC 2373 2.5.2.
  871. """
  872. return (self.network_address.is_unspecified and
  873. self.broadcast_address.is_unspecified)
  874. @property
  875. def is_loopback(self):
  876. """Test if the address is a loopback address.
  877. Returns:
  878. A boolean, True if the address is a loopback address as defined in
  879. RFC 2373 2.5.3.
  880. """
  881. return (self.network_address.is_loopback and
  882. self.broadcast_address.is_loopback)
  883. class _BaseConstants:
  884. _private_networks = []
  885. _BaseNetwork._constants = _BaseConstants
  886. class _BaseV4:
  887. """Base IPv4 object.
  888. The following methods are used by IPv4 objects in both single IP
  889. addresses and networks.
  890. """
  891. __slots__ = ()
  892. _version = 4
  893. # Equivalent to 255.255.255.255 or 32 bits of 1's.
  894. _ALL_ONES = (2**IPV4LENGTH) - 1
  895. _max_prefixlen = IPV4LENGTH
  896. # There are only a handful of valid v4 netmasks, so we cache them all
  897. # when constructed (see _make_netmask()).
  898. _netmask_cache = {}
  899. def _explode_shorthand_ip_string(self):
  900. return str(self)
  901. @classmethod
  902. def _make_netmask(cls, arg):
  903. """Make a (netmask, prefix_len) tuple from the given argument.
  904. Argument can be:
  905. - an integer (the prefix length)
  906. - a string representing the prefix length (e.g. "24")
  907. - a string representing the prefix netmask (e.g. "255.255.255.0")
  908. """
  909. if arg not in cls._netmask_cache:
  910. if isinstance(arg, int):
  911. prefixlen = arg
  912. if not (0 <= prefixlen <= cls._max_prefixlen):
  913. cls._report_invalid_netmask(prefixlen)
  914. else:
  915. try:
  916. # Check for a netmask in prefix length form
  917. prefixlen = cls._prefix_from_prefix_string(arg)
  918. except NetmaskValueError:
  919. # Check for a netmask or hostmask in dotted-quad form.
  920. # This may raise NetmaskValueError.
  921. prefixlen = cls._prefix_from_ip_string(arg)
  922. netmask = IPv4Address(cls._ip_int_from_prefix(prefixlen))
  923. cls._netmask_cache[arg] = netmask, prefixlen
  924. return cls._netmask_cache[arg]
  925. @classmethod
  926. def _ip_int_from_string(cls, ip_str):
  927. """Turn the given IP string into an integer for comparison.
  928. Args:
  929. ip_str: A string, the IP ip_str.
  930. Returns:
  931. The IP ip_str as an integer.
  932. Raises:
  933. AddressValueError: if ip_str isn't a valid IPv4 Address.
  934. """
  935. if not ip_str:
  936. raise AddressValueError('Address cannot be empty')
  937. octets = ip_str.split('.')
  938. if len(octets) != 4:
  939. raise AddressValueError("Expected 4 octets in %r" % ip_str)
  940. try:
  941. return int.from_bytes(map(cls._parse_octet, octets), 'big')
  942. except ValueError as exc:
  943. raise AddressValueError("%s in %r" % (exc, ip_str)) from None
  944. @classmethod
  945. def _parse_octet(cls, octet_str):
  946. """Convert a decimal octet into an integer.
  947. Args:
  948. octet_str: A string, the number to parse.
  949. Returns:
  950. The octet as an integer.
  951. Raises:
  952. ValueError: if the octet isn't strictly a decimal from [0..255].
  953. """
  954. if not octet_str:
  955. raise ValueError("Empty octet not permitted")
  956. # Reject non-ASCII digits.
  957. if not (octet_str.isascii() and octet_str.isdigit()):
  958. msg = "Only decimal digits permitted in %r"
  959. raise ValueError(msg % octet_str)
  960. # We do the length check second, since the invalid character error
  961. # is likely to be more informative for the user
  962. if len(octet_str) > 3:
  963. msg = "At most 3 characters permitted in %r"
  964. raise ValueError(msg % octet_str)
  965. # Handle leading zeros as strict as glibc's inet_pton()
  966. # See security bug bpo-36384
  967. if octet_str != '0' and octet_str[0] == '0':
  968. msg = "Leading zeros are not permitted in %r"
  969. raise ValueError(msg % octet_str)
  970. # Convert to integer (we know digits are legal)
  971. octet_int = int(octet_str, 10)
  972. if octet_int > 255:
  973. raise ValueError("Octet %d (> 255) not permitted" % octet_int)
  974. return octet_int
  975. @classmethod
  976. def _string_from_ip_int(cls, ip_int):
  977. """Turns a 32-bit integer into dotted decimal notation.
  978. Args:
  979. ip_int: An integer, the IP address.
  980. Returns:
  981. The IP address as a string in dotted decimal notation.
  982. """
  983. return '.'.join(map(str, ip_int.to_bytes(4, 'big')))
  984. def _reverse_pointer(self):
  985. """Return the reverse DNS pointer name for the IPv4 address.
  986. This implements the method described in RFC1035 3.5.
  987. """
  988. reverse_octets = str(self).split('.')[::-1]
  989. return '.'.join(reverse_octets) + '.in-addr.arpa'
  990. @property
  991. def max_prefixlen(self):
  992. return self._max_prefixlen
  993. @property
  994. def version(self):
  995. return self._version
  996. class IPv4Address(_BaseV4, _BaseAddress):
  997. """Represent and manipulate single IPv4 Addresses."""
  998. __slots__ = ('_ip', '__weakref__')
  999. def __init__(self, address):
  1000. """
  1001. Args:
  1002. address: A string or integer representing the IP
  1003. Additionally, an integer can be passed, so
  1004. IPv4Address('192.0.2.1') == IPv4Address(3221225985).
  1005. or, more generally
  1006. IPv4Address(int(IPv4Address('192.0.2.1'))) ==
  1007. IPv4Address('192.0.2.1')
  1008. Raises:
  1009. AddressValueError: If ipaddress isn't a valid IPv4 address.
  1010. """
  1011. # Efficient constructor from integer.
  1012. if isinstance(address, int):
  1013. self._check_int_address(address)
  1014. self._ip = address
  1015. return
  1016. # Constructing from a packed address
  1017. if isinstance(address, bytes):
  1018. self._check_packed_address(address, 4)
  1019. self._ip = int.from_bytes(address) # big endian
  1020. return
  1021. # Assume input argument to be string or any object representation
  1022. # which converts into a formatted IP string.
  1023. addr_str = str(address)
  1024. if '/' in addr_str:
  1025. raise AddressValueError(f"Unexpected '/' in {address!r}")
  1026. self._ip = self._ip_int_from_string(addr_str)
  1027. @property
  1028. def packed(self):
  1029. """The binary representation of this address."""
  1030. return v4_int_to_packed(self._ip)
  1031. @property
  1032. def is_reserved(self):
  1033. """Test if the address is otherwise IETF reserved.
  1034. Returns:
  1035. A boolean, True if the address is within the
  1036. reserved IPv4 Network range.
  1037. """
  1038. return self in self._constants._reserved_network
  1039. @property
  1040. @functools.lru_cache()
  1041. def is_private(self):
  1042. """``True`` if the address is defined as not globally reachable by
  1043. iana-ipv4-special-registry_ (for IPv4) or iana-ipv6-special-registry_
  1044. (for IPv6) with the following exceptions:
  1045. * ``is_private`` is ``False`` for ``100.64.0.0/10``
  1046. * For IPv4-mapped IPv6-addresses the ``is_private`` value is determined by the
  1047. semantics of the underlying IPv4 addresses and the following condition holds
  1048. (see :attr:`IPv6Address.ipv4_mapped`)::
  1049. address.is_private == address.ipv4_mapped.is_private
  1050. ``is_private`` has value opposite to :attr:`is_global`, except for the ``100.64.0.0/10``
  1051. IPv4 range where they are both ``False``.
  1052. """
  1053. return (
  1054. any(self in net for net in self._constants._private_networks)
  1055. and all(self not in net for net in self._constants._private_networks_exceptions)
  1056. )
  1057. @property
  1058. @functools.lru_cache()
  1059. def is_global(self):
  1060. """``True`` if the address is defined as globally reachable by
  1061. iana-ipv4-special-registry_ (for IPv4) or iana-ipv6-special-registry_
  1062. (for IPv6) with the following exception:
  1063. For IPv4-mapped IPv6-addresses the ``is_private`` value is determined by the
  1064. semantics of the underlying IPv4 addresses and the following condition holds
  1065. (see :attr:`IPv6Address.ipv4_mapped`)::
  1066. address.is_global == address.ipv4_mapped.is_global
  1067. ``is_global`` has value opposite to :attr:`is_private`, except for the ``100.64.0.0/10``
  1068. IPv4 range where they are both ``False``.
  1069. """
  1070. return self not in self._constants._public_network and not self.is_private
  1071. @property
  1072. def is_multicast(self):
  1073. """Test if the address is reserved for multicast use.
  1074. Returns:
  1075. A boolean, True if the address is multicast.
  1076. See RFC 3171 for details.
  1077. """
  1078. return self in self._constants._multicast_network
  1079. @property
  1080. def is_unspecified(self):
  1081. """Test if the address is unspecified.
  1082. Returns:
  1083. A boolean, True if this is the unspecified address as defined in
  1084. RFC 5735 3.
  1085. """
  1086. return self == self._constants._unspecified_address
  1087. @property
  1088. def is_loopback(self):
  1089. """Test if the address is a loopback address.
  1090. Returns:
  1091. A boolean, True if the address is a loopback per RFC 3330.
  1092. """
  1093. return self in self._constants._loopback_network
  1094. @property
  1095. def is_link_local(self):
  1096. """Test if the address is reserved for link-local.
  1097. Returns:
  1098. A boolean, True if the address is link-local per RFC 3927.
  1099. """
  1100. return self in self._constants._linklocal_network
  1101. class IPv4Interface(IPv4Address):
  1102. def __init__(self, address):
  1103. addr, mask = self._split_addr_prefix(address)
  1104. IPv4Address.__init__(self, addr)
  1105. self.network = IPv4Network((addr, mask), strict=False)
  1106. self.netmask = self.network.netmask
  1107. self._prefixlen = self.network._prefixlen
  1108. @functools.cached_property
  1109. def hostmask(self):
  1110. return self.network.hostmask
  1111. def __str__(self):
  1112. return '%s/%d' % (self._string_from_ip_int(self._ip),
  1113. self._prefixlen)
  1114. def __eq__(self, other):
  1115. address_equal = IPv4Address.__eq__(self, other)
  1116. if address_equal is NotImplemented or not address_equal:
  1117. return address_equal
  1118. try:
  1119. return self.network == other.network
  1120. except AttributeError:
  1121. # An interface with an associated network is NOT the
  1122. # same as an unassociated address. That's why the hash
  1123. # takes the extra info into account.
  1124. return False
  1125. def __lt__(self, other):
  1126. address_less = IPv4Address.__lt__(self, other)
  1127. if address_less is NotImplemented:
  1128. return NotImplemented
  1129. try:
  1130. return (self.network < other.network or
  1131. self.network == other.network and address_less)
  1132. except AttributeError:
  1133. # We *do* allow addresses and interfaces to be sorted. The
  1134. # unassociated address is considered less than all interfaces.
  1135. return False
  1136. def __hash__(self):
  1137. return hash((self._ip, self._prefixlen, int(self.network.network_address)))
  1138. __reduce__ = _IPAddressBase.__reduce__
  1139. @property
  1140. def ip(self):
  1141. return IPv4Address(self._ip)
  1142. @property
  1143. def with_prefixlen(self):
  1144. return '%s/%s' % (self._string_from_ip_int(self._ip),
  1145. self._prefixlen)
  1146. @property
  1147. def with_netmask(self):
  1148. return '%s/%s' % (self._string_from_ip_int(self._ip),
  1149. self.netmask)
  1150. @property
  1151. def with_hostmask(self):
  1152. return '%s/%s' % (self._string_from_ip_int(self._ip),
  1153. self.hostmask)
  1154. class IPv4Network(_BaseV4, _BaseNetwork):
  1155. """This class represents and manipulates 32-bit IPv4 network + addresses..
  1156. Attributes: [examples for IPv4Network('192.0.2.0/27')]
  1157. .network_address: IPv4Address('192.0.2.0')
  1158. .hostmask: IPv4Address('0.0.0.31')
  1159. .broadcast_address: IPv4Address('192.0.2.32')
  1160. .netmask: IPv4Address('255.255.255.224')
  1161. .prefixlen: 27
  1162. """
  1163. # Class to use when creating address objects
  1164. _address_class = IPv4Address
  1165. def __init__(self, address, strict=True):
  1166. """Instantiate a new IPv4 network object.
  1167. Args:
  1168. address: A string or integer representing the IP [& network].
  1169. '192.0.2.0/24'
  1170. '192.0.2.0/255.255.255.0'
  1171. '192.0.2.0/0.0.0.255'
  1172. are all functionally the same in IPv4. Similarly,
  1173. '192.0.2.1'
  1174. '192.0.2.1/255.255.255.255'
  1175. '192.0.2.1/32'
  1176. are also functionally equivalent. That is to say, failing to
  1177. provide a subnetmask will create an object with a mask of /32.
  1178. If the mask (portion after the / in the argument) is given in
  1179. dotted quad form, it is treated as a netmask if it starts with a
  1180. non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
  1181. starts with a zero field (e.g. 0.255.255.255 == /8), with the
  1182. single exception of an all-zero mask which is treated as a
  1183. netmask == /0. If no mask is given, a default of /32 is used.
  1184. Additionally, an integer can be passed, so
  1185. IPv4Network('192.0.2.1') == IPv4Network(3221225985)
  1186. or, more generally
  1187. IPv4Interface(int(IPv4Interface('192.0.2.1'))) ==
  1188. IPv4Interface('192.0.2.1')
  1189. Raises:
  1190. AddressValueError: If ipaddress isn't a valid IPv4 address.
  1191. NetmaskValueError: If the netmask isn't valid for
  1192. an IPv4 address.
  1193. ValueError: If strict is True and a network address is not
  1194. supplied.
  1195. """
  1196. addr, mask = self._split_addr_prefix(address)
  1197. self.network_address = IPv4Address(addr)
  1198. self.netmask, self._prefixlen = self._make_netmask(mask)
  1199. packed = int(self.network_address)
  1200. if packed & int(self.netmask) != packed:
  1201. if strict:
  1202. raise ValueError('%s has host bits set' % self)
  1203. else:
  1204. self.network_address = IPv4Address(packed &
  1205. int(self.netmask))
  1206. if self._prefixlen == (self._max_prefixlen - 1):
  1207. self.hosts = self.__iter__
  1208. elif self._prefixlen == (self._max_prefixlen):
  1209. self.hosts = lambda: [IPv4Address(addr)]
  1210. @property
  1211. @functools.lru_cache()
  1212. def is_global(self):
  1213. """Test if this address is allocated for public networks.
  1214. Returns:
  1215. A boolean, True if the address is not reserved per
  1216. iana-ipv4-special-registry.
  1217. """
  1218. return (not (self.network_address in IPv4Network('100.64.0.0/10') and
  1219. self.broadcast_address in IPv4Network('100.64.0.0/10')) and
  1220. not self.is_private)
  1221. class _IPv4Constants:
  1222. _linklocal_network = IPv4Network('169.254.0.0/16')
  1223. _loopback_network = IPv4Network('127.0.0.0/8')
  1224. _multicast_network = IPv4Network('224.0.0.0/4')
  1225. _public_network = IPv4Network('100.64.0.0/10')
  1226. # Not globally reachable address blocks listed on
  1227. # https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
  1228. _private_networks = [
  1229. IPv4Network('0.0.0.0/8'),
  1230. IPv4Network('10.0.0.0/8'),
  1231. IPv4Network('127.0.0.0/8'),
  1232. IPv4Network('169.254.0.0/16'),
  1233. IPv4Network('172.16.0.0/12'),
  1234. IPv4Network('192.0.0.0/24'),
  1235. IPv4Network('192.0.0.170/31'),
  1236. IPv4Network('192.0.2.0/24'),
  1237. IPv4Network('192.168.0.0/16'),
  1238. IPv4Network('198.18.0.0/15'),
  1239. IPv4Network('198.51.100.0/24'),
  1240. IPv4Network('203.0.113.0/24'),
  1241. IPv4Network('240.0.0.0/4'),
  1242. IPv4Network('255.255.255.255/32'),
  1243. ]
  1244. _private_networks_exceptions = [
  1245. IPv4Network('192.0.0.9/32'),
  1246. IPv4Network('192.0.0.10/32'),
  1247. ]
  1248. _reserved_network = IPv4Network('240.0.0.0/4')
  1249. _unspecified_address = IPv4Address('0.0.0.0')
  1250. IPv4Address._constants = _IPv4Constants
  1251. IPv4Network._constants = _IPv4Constants
  1252. class _BaseV6:
  1253. """Base IPv6 object.
  1254. The following methods are used by IPv6 objects in both single IP
  1255. addresses and networks.
  1256. """
  1257. __slots__ = ()
  1258. _version = 6
  1259. _ALL_ONES = (2**IPV6LENGTH) - 1
  1260. _HEXTET_COUNT = 8
  1261. _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
  1262. _max_prefixlen = IPV6LENGTH
  1263. # There are only a bunch of valid v6 netmasks, so we cache them all
  1264. # when constructed (see _make_netmask()).
  1265. _netmask_cache = {}
  1266. @classmethod
  1267. def _make_netmask(cls, arg):
  1268. """Make a (netmask, prefix_len) tuple from the given argument.
  1269. Argument can be:
  1270. - an integer (the prefix length)
  1271. - a string representing the prefix length (e.g. "24")
  1272. - a string representing the prefix netmask (e.g. "255.255.255.0")
  1273. """
  1274. if arg not in cls._netmask_cache:
  1275. if isinstance(arg, int):
  1276. prefixlen = arg
  1277. if not (0 <= prefixlen <= cls._max_prefixlen):
  1278. cls._report_invalid_netmask(prefixlen)
  1279. else:
  1280. prefixlen = cls._prefix_from_prefix_string(arg)
  1281. netmask = IPv6Address(cls._ip_int_from_prefix(prefixlen))
  1282. cls._netmask_cache[arg] = netmask, prefixlen
  1283. return cls._netmask_cache[arg]
  1284. @classmethod
  1285. def _ip_int_from_string(cls, ip_str):
  1286. """Turn an IPv6 ip_str into an integer.
  1287. Args:
  1288. ip_str: A string, the IPv6 ip_str.
  1289. Returns:
  1290. An int, the IPv6 address
  1291. Raises:
  1292. AddressValueError: if ip_str isn't a valid IPv6 Address.
  1293. """
  1294. if not ip_str:
  1295. raise AddressValueError('Address cannot be empty')
  1296. parts = ip_str.split(':')
  1297. # An IPv6 address needs at least 2 colons (3 parts).
  1298. _min_parts = 3
  1299. if len(parts) < _min_parts:
  1300. msg = "At least %d parts expected in %r" % (_min_parts, ip_str)
  1301. raise AddressValueError(msg)
  1302. # If the address has an IPv4-style suffix, convert it to hexadecimal.
  1303. if '.' in parts[-1]:
  1304. try:
  1305. ipv4_int = IPv4Address(parts.pop())._ip
  1306. except AddressValueError as exc:
  1307. raise AddressValueError("%s in %r" % (exc, ip_str)) from None
  1308. parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
  1309. parts.append('%x' % (ipv4_int & 0xFFFF))
  1310. # An IPv6 address can't have more than 8 colons (9 parts).
  1311. # The extra colon comes from using the "::" notation for a single
  1312. # leading or trailing zero part.
  1313. _max_parts = cls._HEXTET_COUNT + 1
  1314. if len(parts) > _max_parts:
  1315. msg = "At most %d colons permitted in %r" % (_max_parts-1, ip_str)
  1316. raise AddressValueError(msg)
  1317. # Disregarding the endpoints, find '::' with nothing in between.
  1318. # This indicates that a run of zeroes has been skipped.
  1319. skip_index = None
  1320. for i in range(1, len(parts) - 1):
  1321. if not parts[i]:
  1322. if skip_index is not None:
  1323. # Can't have more than one '::'
  1324. msg = "At most one '::' permitted in %r" % ip_str
  1325. raise AddressValueError(msg)
  1326. skip_index = i
  1327. # parts_hi is the number of parts to copy from above/before the '::'
  1328. # parts_lo is the number of parts to copy from below/after the '::'
  1329. if skip_index is not None:
  1330. # If we found a '::', then check if it also covers the endpoints.
  1331. parts_hi = skip_index
  1332. parts_lo = len(parts) - skip_index - 1
  1333. if not parts[0]:
  1334. parts_hi -= 1
  1335. if parts_hi:
  1336. msg = "Leading ':' only permitted as part of '::' in %r"
  1337. raise AddressValueError(msg % ip_str) # ^: requires ^::
  1338. if not parts[-1]:
  1339. parts_lo -= 1
  1340. if parts_lo:
  1341. msg = "Trailing ':' only permitted as part of '::' in %r"
  1342. raise AddressValueError(msg % ip_str) # :$ requires ::$
  1343. parts_skipped = cls._HEXTET_COUNT - (parts_hi + parts_lo)
  1344. if parts_skipped < 1:
  1345. msg = "Expected at most %d other parts with '::' in %r"
  1346. raise AddressValueError(msg % (cls._HEXTET_COUNT-1, ip_str))
  1347. else:
  1348. # Otherwise, allocate the entire address to parts_hi. The
  1349. # endpoints could still be empty, but _parse_hextet() will check
  1350. # for that.
  1351. if len(parts) != cls._HEXTET_COUNT:
  1352. msg = "Exactly %d parts expected without '::' in %r"
  1353. raise AddressValueError(msg % (cls._HEXTET_COUNT, ip_str))
  1354. if not parts[0]:
  1355. msg = "Leading ':' only permitted as part of '::' in %r"
  1356. raise AddressValueError(msg % ip_str) # ^: requires ^::
  1357. if not parts[-1]:
  1358. msg = "Trailing ':' only permitted as part of '::' in %r"
  1359. raise AddressValueError(msg % ip_str) # :$ requires ::$
  1360. parts_hi = len(parts)
  1361. parts_lo = 0
  1362. parts_skipped = 0
  1363. try:
  1364. # Now, parse the hextets into a 128-bit integer.
  1365. ip_int = 0
  1366. for i in range(parts_hi):
  1367. ip_int <<= 16
  1368. ip_int |= cls._parse_hextet(parts[i])
  1369. ip_int <<= 16 * parts_skipped
  1370. for i in range(-parts_lo, 0):
  1371. ip_int <<= 16
  1372. ip_int |= cls._parse_hextet(parts[i])
  1373. return ip_int
  1374. except ValueError as exc:
  1375. raise AddressValueError("%s in %r" % (exc, ip_str)) from None
  1376. @classmethod
  1377. def _parse_hextet(cls, hextet_str):
  1378. """Convert an IPv6 hextet string into an integer.
  1379. Args:
  1380. hextet_str: A string, the number to parse.
  1381. Returns:
  1382. The hextet as an integer.
  1383. Raises:
  1384. ValueError: if the input isn't strictly a hex number from
  1385. [0..FFFF].
  1386. """
  1387. # Reject non-ASCII digits.
  1388. if not cls._HEX_DIGITS.issuperset(hextet_str):
  1389. raise ValueError("Only hex digits permitted in %r" % hextet_str)
  1390. # We do the length check second, since the invalid character error
  1391. # is likely to be more informative for the user
  1392. if len(hextet_str) > 4:
  1393. msg = "At most 4 characters permitted in %r"
  1394. raise ValueError(msg % hextet_str)
  1395. # Length check means we can skip checking the integer value
  1396. return int(hextet_str, 16)
  1397. @classmethod
  1398. def _compress_hextets(cls, hextets):
  1399. """Compresses a list of hextets.
  1400. Compresses a list of strings, replacing the longest continuous
  1401. sequence of "0" in the list with "" and adding empty strings at
  1402. the beginning or at the end of the string such that subsequently
  1403. calling ":".join(hextets) will produce the compressed version of
  1404. the IPv6 address.
  1405. Args:
  1406. hextets: A list of strings, the hextets to compress.
  1407. Returns:
  1408. A list of strings.
  1409. """
  1410. best_doublecolon_start = -1
  1411. best_doublecolon_len = 0
  1412. doublecolon_start = -1
  1413. doublecolon_len = 0
  1414. for index, hextet in enumerate(hextets):
  1415. if hextet == '0':
  1416. doublecolon_len += 1
  1417. if doublecolon_start == -1:
  1418. # Start of a sequence of zeros.
  1419. doublecolon_start = index
  1420. if doublecolon_len > best_doublecolon_len:
  1421. # This is the longest sequence of zeros so far.
  1422. best_doublecolon_len = doublecolon_len
  1423. best_doublecolon_start = doublecolon_start
  1424. else:
  1425. doublecolon_len = 0
  1426. doublecolon_start = -1
  1427. if best_doublecolon_len > 1:
  1428. best_doublecolon_end = (best_doublecolon_start +
  1429. best_doublecolon_len)
  1430. # For zeros at the end of the address.
  1431. if best_doublecolon_end == len(hextets):
  1432. hextets += ['']
  1433. hextets[best_doublecolon_start:best_doublecolon_end] = ['']
  1434. # For zeros at the beginning of the address.
  1435. if best_doublecolon_start == 0:
  1436. hextets = [''] + hextets
  1437. return hextets
  1438. @classmethod
  1439. def _string_from_ip_int(cls, ip_int=None):
  1440. """Turns a 128-bit integer into hexadecimal notation.
  1441. Args:
  1442. ip_int: An integer, the IP address.
  1443. Returns:
  1444. A string, the hexadecimal representation of the address.
  1445. Raises:
  1446. ValueError: The address is bigger than 128 bits of all ones.
  1447. """
  1448. if ip_int is None:
  1449. ip_int = int(cls._ip)
  1450. if ip_int > cls._ALL_ONES:
  1451. raise ValueError('IPv6 address is too large')
  1452. hex_str = '%032x' % ip_int
  1453. hextets = ['%x' % int(hex_str[x:x+4], 16) for x in range(0, 32, 4)]
  1454. hextets = cls._compress_hextets(hextets)
  1455. return ':'.join(hextets)
  1456. def _explode_shorthand_ip_string(self):
  1457. """Expand a shortened IPv6 address.
  1458. Returns:
  1459. A string, the expanded IPv6 address.
  1460. """
  1461. if isinstance(self, IPv6Network):
  1462. ip_str = str(self.network_address)
  1463. elif isinstance(self, IPv6Interface):
  1464. ip_str = str(self.ip)
  1465. else:
  1466. ip_str = str(self)
  1467. ip_int = self._ip_int_from_string(ip_str)
  1468. hex_str = '%032x' % ip_int
  1469. parts = [hex_str[x:x+4] for x in range(0, 32, 4)]
  1470. if isinstance(self, (_BaseNetwork, IPv6Interface)):
  1471. return '%s/%d' % (':'.join(parts), self._prefixlen)
  1472. return ':'.join(parts)
  1473. def _reverse_pointer(self):
  1474. """Return the reverse DNS pointer name for the IPv6 address.
  1475. This implements the method described in RFC3596 2.5.
  1476. """
  1477. reverse_chars = self.exploded[::-1].replace(':', '')
  1478. return '.'.join(reverse_chars) + '.ip6.arpa'
  1479. @staticmethod
  1480. def _split_scope_id(ip_str):
  1481. """Helper function to parse IPv6 string address with scope id.
  1482. See RFC 4007 for details.
  1483. Args:
  1484. ip_str: A string, the IPv6 address.
  1485. Returns:
  1486. (addr, scope_id) tuple.
  1487. """
  1488. addr, sep, scope_id = ip_str.partition('%')
  1489. if not sep:
  1490. scope_id = None
  1491. elif not scope_id or '%' in scope_id:
  1492. raise AddressValueError('Invalid IPv6 address: "%r"' % ip_str)
  1493. return addr, scope_id
  1494. @property
  1495. def max_prefixlen(self):
  1496. return self._max_prefixlen
  1497. @property
  1498. def version(self):
  1499. return self._version
  1500. class IPv6Address(_BaseV6, _BaseAddress):
  1501. """Represent and manipulate single IPv6 Addresses."""
  1502. __slots__ = ('_ip', '_scope_id', '__weakref__')
  1503. def __init__(self, address):
  1504. """Instantiate a new IPv6 address object.
  1505. Args:
  1506. address: A string or integer representing the IP
  1507. Additionally, an integer can be passed, so
  1508. IPv6Address('2001:db8::') ==
  1509. IPv6Address(42540766411282592856903984951653826560)
  1510. or, more generally
  1511. IPv6Address(int(IPv6Address('2001:db8::'))) ==
  1512. IPv6Address('2001:db8::')
  1513. Raises:
  1514. AddressValueError: If address isn't a valid IPv6 address.
  1515. """
  1516. # Efficient constructor from integer.
  1517. if isinstance(address, int):
  1518. self._check_int_address(address)
  1519. self._ip = address
  1520. self._scope_id = None
  1521. return
  1522. # Constructing from a packed address
  1523. if isinstance(address, bytes):
  1524. self._check_packed_address(address, 16)
  1525. self._ip = int.from_bytes(address, 'big')
  1526. self._scope_id = None
  1527. return
  1528. # Assume input argument to be string or any object representation
  1529. # which converts into a formatted IP string.
  1530. addr_str = str(address)
  1531. if '/' in addr_str:
  1532. raise AddressValueError(f"Unexpected '/' in {address!r}")
  1533. addr_str, self._scope_id = self._split_scope_id(addr_str)
  1534. self._ip = self._ip_int_from_string(addr_str)
  1535. def __str__(self):
  1536. ip_str = super().__str__()
  1537. return ip_str + '%' + self._scope_id if self._scope_id else ip_str
  1538. def __hash__(self):
  1539. return hash((self._ip, self._scope_id))
  1540. def __eq__(self, other):
  1541. address_equal = super().__eq__(other)
  1542. if address_equal is NotImplemented:
  1543. return NotImplemented
  1544. if not address_equal:
  1545. return False
  1546. return self._scope_id == getattr(other, '_scope_id', None)
  1547. def __reduce__(self):
  1548. return (self.__class__, (str(self),))
  1549. @property
  1550. def scope_id(self):
  1551. """Identifier of a particular zone of the address's scope.
  1552. See RFC 4007 for details.
  1553. Returns:
  1554. A string identifying the zone of the address if specified, else None.
  1555. """
  1556. return self._scope_id
  1557. @property
  1558. def packed(self):
  1559. """The binary representation of this address."""
  1560. return v6_int_to_packed(self._ip)
  1561. @property
  1562. def is_multicast(self):
  1563. """Test if the address is reserved for multicast use.
  1564. Returns:
  1565. A boolean, True if the address is a multicast address.
  1566. See RFC 2373 2.7 for details.
  1567. """
  1568. return self in self._constants._multicast_network
  1569. @property
  1570. def is_reserved(self):
  1571. """Test if the address is otherwise IETF reserved.
  1572. Returns:
  1573. A boolean, True if the address is within one of the
  1574. reserved IPv6 Network ranges.
  1575. """
  1576. return any(self in x for x in self._constants._reserved_networks)
  1577. @property
  1578. def is_link_local(self):
  1579. """Test if the address is reserved for link-local.
  1580. Returns:
  1581. A boolean, True if the address is reserved per RFC 4291.
  1582. """
  1583. return self in self._constants._linklocal_network
  1584. @property
  1585. def is_site_local(self):
  1586. """Test if the address is reserved for site-local.
  1587. Note that the site-local address space has been deprecated by RFC 3879.
  1588. Use is_private to test if this address is in the space of unique local
  1589. addresses as defined by RFC 4193.
  1590. Returns:
  1591. A boolean, True if the address is reserved per RFC 3513 2.5.6.
  1592. """
  1593. return self in self._constants._sitelocal_network
  1594. @property
  1595. @functools.lru_cache()
  1596. def is_private(self):
  1597. """``True`` if the address is defined as not globally reachable by
  1598. iana-ipv4-special-registry_ (for IPv4) or iana-ipv6-special-registry_
  1599. (for IPv6) with the following exceptions:
  1600. * ``is_private`` is ``False`` for ``100.64.0.0/10``
  1601. * For IPv4-mapped IPv6-addresses the ``is_private`` value is determined by the
  1602. semantics of the underlying IPv4 addresses and the following condition holds
  1603. (see :attr:`IPv6Address.ipv4_mapped`)::
  1604. address.is_private == address.ipv4_mapped.is_private
  1605. ``is_private`` has value opposite to :attr:`is_global`, except for the ``100.64.0.0/10``
  1606. IPv4 range where they are both ``False``.
  1607. """
  1608. ipv4_mapped = self.ipv4_mapped
  1609. if ipv4_mapped is not None:
  1610. return ipv4_mapped.is_private
  1611. return (
  1612. any(self in net for net in self._constants._private_networks)
  1613. and all(self not in net for net in self._constants._private_networks_exceptions)
  1614. )
  1615. @property
  1616. def is_global(self):
  1617. """``True`` if the address is defined as globally reachable by
  1618. iana-ipv4-special-registry_ (for IPv4) or iana-ipv6-special-registry_
  1619. (for IPv6) with the following exception:
  1620. For IPv4-mapped IPv6-addresses the ``is_private`` value is determined by the
  1621. semantics of the underlying IPv4 addresses and the following condition holds
  1622. (see :attr:`IPv6Address.ipv4_mapped`)::
  1623. address.is_global == address.ipv4_mapped.is_global
  1624. ``is_global`` has value opposite to :attr:`is_private`, except for the ``100.64.0.0/10``
  1625. IPv4 range where they are both ``False``.
  1626. """
  1627. return not self.is_private
  1628. @property
  1629. def is_unspecified(self):
  1630. """Test if the address is unspecified.
  1631. Returns:
  1632. A boolean, True if this is the unspecified address as defined in
  1633. RFC 2373 2.5.2.
  1634. """
  1635. return self._ip == 0
  1636. @property
  1637. def is_loopback(self):
  1638. """Test if the address is a loopback address.
  1639. Returns:
  1640. A boolean, True if the address is a loopback address as defined in
  1641. RFC 2373 2.5.3.
  1642. """
  1643. ipv4_mapped = self.ipv4_mapped
  1644. if ipv4_mapped is not None:
  1645. return ipv4_mapped.is_loopback
  1646. return self._ip == 1
  1647. @property
  1648. def ipv4_mapped(self):
  1649. """Return the IPv4 mapped address.
  1650. Returns:
  1651. If the IPv6 address is a v4 mapped address, return the
  1652. IPv4 mapped address. Return None otherwise.
  1653. """
  1654. if (self._ip >> 32) != 0xFFFF:
  1655. return None
  1656. return IPv4Address(self._ip & 0xFFFFFFFF)
  1657. @property
  1658. def teredo(self):
  1659. """Tuple of embedded teredo IPs.
  1660. Returns:
  1661. Tuple of the (server, client) IPs or None if the address
  1662. doesn't appear to be a teredo address (doesn't start with
  1663. 2001::/32)
  1664. """
  1665. if (self._ip >> 96) != 0x20010000:
  1666. return None
  1667. return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
  1668. IPv4Address(~self._ip & 0xFFFFFFFF))
  1669. @property
  1670. def sixtofour(self):
  1671. """Return the IPv4 6to4 embedded address.
  1672. Returns:
  1673. The IPv4 6to4-embedded address if present or None if the
  1674. address doesn't appear to contain a 6to4 embedded address.
  1675. """
  1676. if (self._ip >> 112) != 0x2002:
  1677. return None
  1678. return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
  1679. class IPv6Interface(IPv6Address):
  1680. def __init__(self, address):
  1681. addr, mask = self._split_addr_prefix(address)
  1682. IPv6Address.__init__(self, addr)
  1683. self.network = IPv6Network((addr, mask), strict=False)
  1684. self.netmask = self.network.netmask
  1685. self._prefixlen = self.network._prefixlen
  1686. @functools.cached_property
  1687. def hostmask(self):
  1688. return self.network.hostmask
  1689. def __str__(self):
  1690. return '%s/%d' % (super().__str__(),
  1691. self._prefixlen)
  1692. def __eq__(self, other):
  1693. address_equal = IPv6Address.__eq__(self, other)
  1694. if address_equal is NotImplemented or not address_equal:
  1695. return address_equal
  1696. try:
  1697. return self.network == other.network
  1698. except AttributeError:
  1699. # An interface with an associated network is NOT the
  1700. # same as an unassociated address. That's why the hash
  1701. # takes the extra info into account.
  1702. return False
  1703. def __lt__(self, other):
  1704. address_less = IPv6Address.__lt__(self, other)
  1705. if address_less is NotImplemented:
  1706. return address_less
  1707. try:
  1708. return (self.network < other.network or
  1709. self.network == other.network and address_less)
  1710. except AttributeError:
  1711. # We *do* allow addresses and interfaces to be sorted. The
  1712. # unassociated address is considered less than all interfaces.
  1713. return False
  1714. def __hash__(self):
  1715. return hash((self._ip, self._prefixlen, int(self.network.network_address)))
  1716. __reduce__ = _IPAddressBase.__reduce__
  1717. @property
  1718. def ip(self):
  1719. return IPv6Address(self._ip)
  1720. @property
  1721. def with_prefixlen(self):
  1722. return '%s/%s' % (self._string_from_ip_int(self._ip),
  1723. self._prefixlen)
  1724. @property
  1725. def with_netmask(self):
  1726. return '%s/%s' % (self._string_from_ip_int(self._ip),
  1727. self.netmask)
  1728. @property
  1729. def with_hostmask(self):
  1730. return '%s/%s' % (self._string_from_ip_int(self._ip),
  1731. self.hostmask)
  1732. @property
  1733. def is_unspecified(self):
  1734. return self._ip == 0 and self.network.is_unspecified
  1735. @property
  1736. def is_loopback(self):
  1737. return super().is_loopback and self.network.is_loopback
  1738. class IPv6Network(_BaseV6, _BaseNetwork):
  1739. """This class represents and manipulates 128-bit IPv6 networks.
  1740. Attributes: [examples for IPv6('2001:db8::1000/124')]
  1741. .network_address: IPv6Address('2001:db8::1000')
  1742. .hostmask: IPv6Address('::f')
  1743. .broadcast_address: IPv6Address('2001:db8::100f')
  1744. .netmask: IPv6Address('ffff:ffff:ffff:ffff:ffff:ffff:ffff:fff0')
  1745. .prefixlen: 124
  1746. """
  1747. # Class to use when creating address objects
  1748. _address_class = IPv6Address
  1749. def __init__(self, address, strict=True):
  1750. """Instantiate a new IPv6 Network object.
  1751. Args:
  1752. address: A string or integer representing the IPv6 network or the
  1753. IP and prefix/netmask.
  1754. '2001:db8::/128'
  1755. '2001:db8:0000:0000:0000:0000:0000:0000/128'
  1756. '2001:db8::'
  1757. are all functionally the same in IPv6. That is to say,
  1758. failing to provide a subnetmask will create an object with
  1759. a mask of /128.
  1760. Additionally, an integer can be passed, so
  1761. IPv6Network('2001:db8::') ==
  1762. IPv6Network(42540766411282592856903984951653826560)
  1763. or, more generally
  1764. IPv6Network(int(IPv6Network('2001:db8::'))) ==
  1765. IPv6Network('2001:db8::')
  1766. strict: A boolean. If true, ensure that we have been passed
  1767. A true network address, eg, 2001:db8::1000/124 and not an
  1768. IP address on a network, eg, 2001:db8::1/124.
  1769. Raises:
  1770. AddressValueError: If address isn't a valid IPv6 address.
  1771. NetmaskValueError: If the netmask isn't valid for
  1772. an IPv6 address.
  1773. ValueError: If strict was True and a network address was not
  1774. supplied.
  1775. """
  1776. addr, mask = self._split_addr_prefix(address)
  1777. self.network_address = IPv6Address(addr)
  1778. self.netmask, self._prefixlen = self._make_netmask(mask)
  1779. packed = int(self.network_address)
  1780. if packed & int(self.netmask) != packed:
  1781. if strict:
  1782. raise ValueError('%s has host bits set' % self)
  1783. else:
  1784. self.network_address = IPv6Address(packed &
  1785. int(self.netmask))
  1786. if self._prefixlen == (self._max_prefixlen - 1):
  1787. self.hosts = self.__iter__
  1788. elif self._prefixlen == self._max_prefixlen:
  1789. self.hosts = lambda: [IPv6Address(addr)]
  1790. def hosts(self):
  1791. """Generate Iterator over usable hosts in a network.
  1792. This is like __iter__ except it doesn't return the
  1793. Subnet-Router anycast address.
  1794. """
  1795. network = int(self.network_address)
  1796. broadcast = int(self.broadcast_address)
  1797. for x in range(network + 1, broadcast + 1):
  1798. yield self._address_class(x)
  1799. @property
  1800. def is_site_local(self):
  1801. """Test if the address is reserved for site-local.
  1802. Note that the site-local address space has been deprecated by RFC 3879.
  1803. Use is_private to test if this address is in the space of unique local
  1804. addresses as defined by RFC 4193.
  1805. Returns:
  1806. A boolean, True if the address is reserved per RFC 3513 2.5.6.
  1807. """
  1808. return (self.network_address.is_site_local and
  1809. self.broadcast_address.is_site_local)
  1810. class _IPv6Constants:
  1811. _linklocal_network = IPv6Network('fe80::/10')
  1812. _multicast_network = IPv6Network('ff00::/8')
  1813. # Not globally reachable address blocks listed on
  1814. # https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml
  1815. _private_networks = [
  1816. IPv6Network('::1/128'),
  1817. IPv6Network('::/128'),
  1818. IPv6Network('::ffff:0:0/96'),
  1819. IPv6Network('64:ff9b:1::/48'),
  1820. IPv6Network('100::/64'),
  1821. IPv6Network('2001::/23'),
  1822. IPv6Network('2001:db8::/32'),
  1823. # IANA says N/A, let's consider it not globally reachable to be safe
  1824. IPv6Network('2002::/16'),
  1825. IPv6Network('fc00::/7'),
  1826. IPv6Network('fe80::/10'),
  1827. ]
  1828. _private_networks_exceptions = [
  1829. IPv6Network('2001:1::1/128'),
  1830. IPv6Network('2001:1::2/128'),
  1831. IPv6Network('2001:3::/32'),
  1832. IPv6Network('2001:4:112::/48'),
  1833. IPv6Network('2001:20::/28'),
  1834. IPv6Network('2001:30::/28'),
  1835. ]
  1836. _reserved_networks = [
  1837. IPv6Network('::/8'), IPv6Network('100::/8'),
  1838. IPv6Network('200::/7'), IPv6Network('400::/6'),
  1839. IPv6Network('800::/5'), IPv6Network('1000::/4'),
  1840. IPv6Network('4000::/3'), IPv6Network('6000::/3'),
  1841. IPv6Network('8000::/3'), IPv6Network('A000::/3'),
  1842. IPv6Network('C000::/3'), IPv6Network('E000::/4'),
  1843. IPv6Network('F000::/5'), IPv6Network('F800::/6'),
  1844. IPv6Network('FE00::/9'),
  1845. ]
  1846. _sitelocal_network = IPv6Network('fec0::/10')
  1847. IPv6Address._constants = _IPv6Constants
  1848. IPv6Network._constants = _IPv6Constants