1
0

ipaddress.py 78 KB

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