ipaddress.py 74 KB

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