ipaddress.py 72 KB

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