ipaddress.py 81 KB

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