ipaddress.py 78 KB

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