ipaddress.py 70 KB

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