1
0

ipaddr.py 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897
  1. #!/usr/bin/python
  2. #
  3. # Copyright 2007 Google Inc.
  4. # Licensed to PSF under a Contributor Agreement.
  5. #
  6. # Licensed under the Apache License, Version 2.0 (the "License");
  7. # you may not use this file except in compliance with the License.
  8. # You may obtain a copy of the License at
  9. #
  10. # http://www.apache.org/licenses/LICENSE-2.0
  11. #
  12. # Unless required by applicable law or agreed to in writing, software
  13. # distributed under the License is distributed on an "AS IS" BASIS,
  14. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
  15. # implied. See the License for the specific language governing
  16. # permissions and limitations under the License.
  17. """A fast, lightweight IPv4/IPv6 manipulation library in Python.
  18. This library is used to create/poke/manipulate IPv4 and IPv6 addresses
  19. and networks.
  20. """
  21. __version__ = '2.1.10'
  22. import struct
  23. IPV4LENGTH = 32
  24. IPV6LENGTH = 128
  25. class AddressValueError(ValueError):
  26. """A Value Error related to the address."""
  27. class NetmaskValueError(ValueError):
  28. """A Value Error related to the netmask."""
  29. def IPAddress(address, version=None):
  30. """Take an IP string/int and return an object of the correct type.
  31. Args:
  32. address: A string or integer, the IP address. Either IPv4 or
  33. IPv6 addresses may be supplied; integers less than 2**32 will
  34. be considered to be IPv4 by default.
  35. version: An Integer, 4 or 6. If set, don't try to automatically
  36. determine what the IP address type is. important for things
  37. like IPAddress(1), which could be IPv4, '0.0.0.1', or IPv6,
  38. '::1'.
  39. Returns:
  40. An IPv4Address or IPv6Address object.
  41. Raises:
  42. ValueError: if the string passed isn't either a v4 or a v6
  43. address.
  44. """
  45. if version:
  46. if version == 4:
  47. return IPv4Address(address)
  48. elif version == 6:
  49. return IPv6Address(address)
  50. try:
  51. return IPv4Address(address)
  52. except (AddressValueError, NetmaskValueError):
  53. pass
  54. try:
  55. return IPv6Address(address)
  56. except (AddressValueError, NetmaskValueError):
  57. pass
  58. raise ValueError('%r does not appear to be an IPv4 or IPv6 address' %
  59. address)
  60. def IPNetwork(address, version=None, strict=False):
  61. """Take an IP string/int and return an object of the correct type.
  62. Args:
  63. address: A string or integer, the IP address. Either IPv4 or
  64. IPv6 addresses may be supplied; integers less than 2**32 will
  65. be considered to be IPv4 by default.
  66. version: An Integer, if set, don't try to automatically
  67. determine what the IP address type is. important for things
  68. like IPNetwork(1), which could be IPv4, '0.0.0.1/32', or IPv6,
  69. '::1/128'.
  70. Returns:
  71. An IPv4Network or IPv6Network object.
  72. Raises:
  73. ValueError: if the string passed isn't either a v4 or a v6
  74. address. Or if a strict network was requested and a strict
  75. network wasn't given.
  76. """
  77. if version:
  78. if version == 4:
  79. return IPv4Network(address, strict)
  80. elif version == 6:
  81. return IPv6Network(address, strict)
  82. try:
  83. return IPv4Network(address, strict)
  84. except (AddressValueError, NetmaskValueError):
  85. pass
  86. try:
  87. return IPv6Network(address, strict)
  88. except (AddressValueError, NetmaskValueError):
  89. pass
  90. raise ValueError('%r does not appear to be an IPv4 or IPv6 network' %
  91. address)
  92. def v4_int_to_packed(address):
  93. """The binary representation of this address.
  94. Args:
  95. address: An integer representation of an IPv4 IP address.
  96. Returns:
  97. The binary representation of this address.
  98. Raises:
  99. ValueError: If the integer is too large to be an IPv4 IP
  100. address.
  101. """
  102. if address > _BaseV4._ALL_ONES:
  103. raise ValueError('Address too large for IPv4')
  104. return Bytes(struct.pack('!I', address))
  105. def v6_int_to_packed(address):
  106. """The binary representation of this address.
  107. Args:
  108. address: An integer representation of an IPv4 IP address.
  109. Returns:
  110. The binary representation of this address.
  111. """
  112. return Bytes(struct.pack('!QQ', address >> 64, address & (2**64 - 1)))
  113. def _find_address_range(addresses):
  114. """Find a sequence of addresses.
  115. Args:
  116. addresses: a list of IPv4 or IPv6 addresses.
  117. Returns:
  118. A tuple containing the first and last IP addresses in the sequence.
  119. """
  120. first = last = addresses[0]
  121. for ip in addresses[1:]:
  122. if ip._ip == last._ip + 1:
  123. last = ip
  124. else:
  125. break
  126. return (first, last)
  127. def _get_prefix_length(number1, number2, bits):
  128. """Get the number of leading bits that are same for two numbers.
  129. Args:
  130. number1: an integer.
  131. number2: another integer.
  132. bits: the maximum number of bits to compare.
  133. Returns:
  134. The number of leading bits that are the same for two numbers.
  135. """
  136. for i in range(bits):
  137. if number1 >> i == number2 >> i:
  138. return bits - i
  139. return 0
  140. def _count_righthand_zero_bits(number, bits):
  141. """Count the number of zero bits on the right hand side.
  142. Args:
  143. number: an integer.
  144. bits: maximum number of bits to count.
  145. Returns:
  146. The number of zero bits on the right hand side of the number.
  147. """
  148. if number == 0:
  149. return bits
  150. for i in range(bits):
  151. if (number >> i) % 2:
  152. return i
  153. def summarize_address_range(first, last):
  154. """Summarize a network range given the first and last IP addresses.
  155. Example:
  156. >>> summarize_address_range(IPv4Address('1.1.1.0'),
  157. IPv4Address('1.1.1.130'))
  158. [IPv4Network('1.1.1.0/25'), IPv4Network('1.1.1.128/31'),
  159. IPv4Network('1.1.1.130/32')]
  160. Args:
  161. first: the first IPv4Address or IPv6Address in the range.
  162. last: the last IPv4Address or IPv6Address in the range.
  163. Returns:
  164. The address range collapsed to a list of IPv4Network's or
  165. IPv6Network's.
  166. Raise:
  167. TypeError:
  168. If the first and last objects are not IP addresses.
  169. If the first and last objects are not the same version.
  170. ValueError:
  171. If the last object is not greater than the first.
  172. If the version is not 4 or 6.
  173. """
  174. if not (isinstance(first, _BaseIP) and isinstance(last, _BaseIP)):
  175. raise TypeError('first and last must be IP addresses, not networks')
  176. if first.version != last.version:
  177. raise TypeError("%s and %s are not of the same version" % (
  178. str(first), str(last)))
  179. if first > last:
  180. raise ValueError('last IP address must be greater than first')
  181. networks = []
  182. if first.version == 4:
  183. ip = IPv4Network
  184. elif first.version == 6:
  185. ip = IPv6Network
  186. else:
  187. raise ValueError('unknown IP version')
  188. ip_bits = first._max_prefixlen
  189. first_int = first._ip
  190. last_int = last._ip
  191. while first_int <= last_int:
  192. nbits = _count_righthand_zero_bits(first_int, ip_bits)
  193. current = None
  194. while nbits >= 0:
  195. addend = 2**nbits - 1
  196. current = first_int + addend
  197. nbits -= 1
  198. if current <= last_int:
  199. break
  200. prefix = _get_prefix_length(first_int, current, ip_bits)
  201. net = ip('%s/%d' % (str(first), prefix))
  202. networks.append(net)
  203. if current == ip._ALL_ONES:
  204. break
  205. first_int = current + 1
  206. first = IPAddress(first_int, version=first._version)
  207. return networks
  208. def _collapse_address_list_recursive(addresses):
  209. """Loops through the addresses, collapsing concurrent netblocks.
  210. Example:
  211. ip1 = IPv4Network('1.1.0.0/24')
  212. ip2 = IPv4Network('1.1.1.0/24')
  213. ip3 = IPv4Network('1.1.2.0/24')
  214. ip4 = IPv4Network('1.1.3.0/24')
  215. ip5 = IPv4Network('1.1.4.0/24')
  216. ip6 = IPv4Network('1.1.0.1/22')
  217. _collapse_address_list_recursive([ip1, ip2, ip3, ip4, ip5, ip6]) ->
  218. [IPv4Network('1.1.0.0/22'), IPv4Network('1.1.4.0/24')]
  219. This shouldn't be called directly; it is called via
  220. collapse_address_list([]).
  221. Args:
  222. addresses: A list of IPv4Network's or IPv6Network's
  223. Returns:
  224. A list of IPv4Network's or IPv6Network's depending on what we were
  225. passed.
  226. """
  227. ret_array = []
  228. optimized = False
  229. for cur_addr in addresses:
  230. if not ret_array:
  231. ret_array.append(cur_addr)
  232. continue
  233. if cur_addr in ret_array[-1]:
  234. optimized = True
  235. elif cur_addr == ret_array[-1].supernet().subnet()[1]:
  236. ret_array.append(ret_array.pop().supernet())
  237. optimized = True
  238. else:
  239. ret_array.append(cur_addr)
  240. if optimized:
  241. return _collapse_address_list_recursive(ret_array)
  242. return ret_array
  243. def collapse_address_list(addresses):
  244. """Collapse a list of IP objects.
  245. Example:
  246. collapse_address_list([IPv4('1.1.0.0/24'), IPv4('1.1.1.0/24')]) ->
  247. [IPv4('1.1.0.0/23')]
  248. Args:
  249. addresses: A list of IPv4Network or IPv6Network objects.
  250. Returns:
  251. A list of IPv4Network or IPv6Network objects depending on what we
  252. were passed.
  253. Raises:
  254. TypeError: If passed a list of mixed version objects.
  255. """
  256. i = 0
  257. addrs = []
  258. ips = []
  259. nets = []
  260. # split IP addresses and networks
  261. for ip in addresses:
  262. if isinstance(ip, _BaseIP):
  263. if ips and ips[-1]._version != ip._version:
  264. raise TypeError("%s and %s are not of the same version" % (
  265. str(ip), str(ips[-1])))
  266. ips.append(ip)
  267. elif ip._prefixlen == ip._max_prefixlen:
  268. if ips and ips[-1]._version != ip._version:
  269. raise TypeError("%s and %s are not of the same version" % (
  270. str(ip), str(ips[-1])))
  271. ips.append(ip.ip)
  272. else:
  273. if nets and nets[-1]._version != ip._version:
  274. raise TypeError("%s and %s are not of the same version" % (
  275. str(ip), str(ips[-1])))
  276. nets.append(ip)
  277. # sort and dedup
  278. ips = sorted(set(ips))
  279. nets = sorted(set(nets))
  280. while i < len(ips):
  281. (first, last) = _find_address_range(ips[i:])
  282. i = ips.index(last) + 1
  283. addrs.extend(summarize_address_range(first, last))
  284. return _collapse_address_list_recursive(sorted(
  285. addrs + nets, key=_BaseNet._get_networks_key))
  286. # backwards compatibility
  287. CollapseAddrList = collapse_address_list
  288. # We need to distinguish between the string and packed-bytes representations
  289. # of an IP address. For example, b'0::1' is the IPv4 address 48.58.58.49,
  290. # while '0::1' is an IPv6 address.
  291. #
  292. # In Python 3, the native 'bytes' type already provides this functionality,
  293. # so we use it directly. For earlier implementations where bytes is not a
  294. # distinct type, we create a subclass of str to serve as a tag.
  295. #
  296. # Usage example (Python 2):
  297. # ip = ipaddr.IPAddress(ipaddr.Bytes('xxxx'))
  298. #
  299. # Usage example (Python 3):
  300. # ip = ipaddr.IPAddress(b'xxxx')
  301. try:
  302. if bytes is str:
  303. raise TypeError("bytes is not a distinct type")
  304. Bytes = bytes
  305. except (NameError, TypeError):
  306. class Bytes(str):
  307. def __repr__(self):
  308. return 'Bytes(%s)' % str.__repr__(self)
  309. def get_mixed_type_key(obj):
  310. """Return a key suitable for sorting between networks and addresses.
  311. Address and Network objects are not sortable by default; they're
  312. fundamentally different so the expression
  313. IPv4Address('1.1.1.1') <= IPv4Network('1.1.1.1/24')
  314. doesn't make any sense. There are some times however, where you may wish
  315. to have ipaddr sort these for you anyway. If you need to do this, you
  316. can use this function as the key= argument to sorted().
  317. Args:
  318. obj: either a Network or Address object.
  319. Returns:
  320. appropriate key.
  321. """
  322. if isinstance(obj, _BaseNet):
  323. return obj._get_networks_key()
  324. elif isinstance(obj, _BaseIP):
  325. return obj._get_address_key()
  326. return NotImplemented
  327. class _IPAddrBase(object):
  328. """The mother class."""
  329. def __index__(self):
  330. return self._ip
  331. def __int__(self):
  332. return self._ip
  333. def __hex__(self):
  334. return hex(self._ip)
  335. @property
  336. def exploded(self):
  337. """Return the longhand version of the IP address as a string."""
  338. return self._explode_shorthand_ip_string()
  339. @property
  340. def compressed(self):
  341. """Return the shorthand version of the IP address as a string."""
  342. return str(self)
  343. class _BaseIP(_IPAddrBase):
  344. """A generic IP object.
  345. This IP class contains the version independent methods which are
  346. used by single IP addresses.
  347. """
  348. def __eq__(self, other):
  349. try:
  350. return (self._ip == other._ip
  351. and self._version == other._version)
  352. except AttributeError:
  353. return NotImplemented
  354. def __ne__(self, other):
  355. eq = self.__eq__(other)
  356. if eq is NotImplemented:
  357. return NotImplemented
  358. return not eq
  359. def __le__(self, other):
  360. gt = self.__gt__(other)
  361. if gt is NotImplemented:
  362. return NotImplemented
  363. return not gt
  364. def __ge__(self, other):
  365. lt = self.__lt__(other)
  366. if lt is NotImplemented:
  367. return NotImplemented
  368. return not lt
  369. def __lt__(self, other):
  370. if self._version != other._version:
  371. raise TypeError('%s and %s are not of the same version' % (
  372. str(self), str(other)))
  373. if not isinstance(other, _BaseIP):
  374. raise TypeError('%s and %s are not of the same type' % (
  375. str(self), str(other)))
  376. if self._ip != other._ip:
  377. return self._ip < other._ip
  378. return False
  379. def __gt__(self, other):
  380. if self._version != other._version:
  381. raise TypeError('%s and %s are not of the same version' % (
  382. str(self), str(other)))
  383. if not isinstance(other, _BaseIP):
  384. raise TypeError('%s and %s are not of the same type' % (
  385. str(self), str(other)))
  386. if self._ip != other._ip:
  387. return self._ip > other._ip
  388. return False
  389. # Shorthand for Integer addition and subtraction. This is not
  390. # meant to ever support addition/subtraction of addresses.
  391. def __add__(self, other):
  392. if not isinstance(other, int):
  393. return NotImplemented
  394. return IPAddress(int(self) + other, version=self._version)
  395. def __sub__(self, other):
  396. if not isinstance(other, int):
  397. return NotImplemented
  398. return IPAddress(int(self) - other, version=self._version)
  399. def __repr__(self):
  400. return '%s(%r)' % (self.__class__.__name__, str(self))
  401. def __str__(self):
  402. return '%s' % self._string_from_ip_int(self._ip)
  403. def __hash__(self):
  404. return hash(hex(long(self._ip)))
  405. def _get_address_key(self):
  406. return (self._version, self)
  407. @property
  408. def version(self):
  409. raise NotImplementedError('BaseIP has no version')
  410. class _BaseNet(_IPAddrBase):
  411. """A generic IP object.
  412. This IP class contains the version independent methods which are
  413. used by networks.
  414. """
  415. def __init__(self, address):
  416. self._cache = {}
  417. def __repr__(self):
  418. return '%s(%r)' % (self.__class__.__name__, str(self))
  419. def iterhosts(self):
  420. """Generate Iterator over usable hosts in a network.
  421. This is like __iter__ except it doesn't return the network
  422. or broadcast addresses.
  423. """
  424. cur = int(self.network) + 1
  425. bcast = int(self.broadcast) - 1
  426. while cur <= bcast:
  427. cur += 1
  428. yield IPAddress(cur - 1, version=self._version)
  429. def __iter__(self):
  430. cur = int(self.network)
  431. bcast = int(self.broadcast)
  432. while cur <= bcast:
  433. cur += 1
  434. yield IPAddress(cur - 1, version=self._version)
  435. def __getitem__(self, n):
  436. network = int(self.network)
  437. broadcast = int(self.broadcast)
  438. if n >= 0:
  439. if network + n > broadcast:
  440. raise IndexError
  441. return IPAddress(network + n, version=self._version)
  442. else:
  443. n += 1
  444. if broadcast + n < network:
  445. raise IndexError
  446. return IPAddress(broadcast + n, version=self._version)
  447. def __lt__(self, other):
  448. if self._version != other._version:
  449. raise TypeError('%s and %s are not of the same version' % (
  450. str(self), str(other)))
  451. if not isinstance(other, _BaseNet):
  452. raise TypeError('%s and %s are not of the same type' % (
  453. str(self), str(other)))
  454. if self.network != other.network:
  455. return self.network < other.network
  456. if self.netmask != other.netmask:
  457. return self.netmask < other.netmask
  458. return False
  459. def __gt__(self, other):
  460. if self._version != other._version:
  461. raise TypeError('%s and %s are not of the same version' % (
  462. str(self), str(other)))
  463. if not isinstance(other, _BaseNet):
  464. raise TypeError('%s and %s are not of the same type' % (
  465. str(self), str(other)))
  466. if self.network != other.network:
  467. return self.network > other.network
  468. if self.netmask != other.netmask:
  469. return self.netmask > other.netmask
  470. return False
  471. def __le__(self, other):
  472. gt = self.__gt__(other)
  473. if gt is NotImplemented:
  474. return NotImplemented
  475. return not gt
  476. def __ge__(self, other):
  477. lt = self.__lt__(other)
  478. if lt is NotImplemented:
  479. return NotImplemented
  480. return not lt
  481. def __eq__(self, other):
  482. try:
  483. return (self._version == other._version
  484. and self.network == other.network
  485. and int(self.netmask) == int(other.netmask))
  486. except AttributeError:
  487. if isinstance(other, _BaseIP):
  488. return (self._version == other._version
  489. and self._ip == other._ip)
  490. def __ne__(self, other):
  491. eq = self.__eq__(other)
  492. if eq is NotImplemented:
  493. return NotImplemented
  494. return not eq
  495. def __str__(self):
  496. return '%s/%s' % (str(self.ip),
  497. str(self._prefixlen))
  498. def __hash__(self):
  499. return hash(int(self.network) ^ int(self.netmask))
  500. def __contains__(self, other):
  501. # always false if one is v4 and the other is v6.
  502. if self._version != other._version:
  503. return False
  504. # dealing with another network.
  505. if isinstance(other, _BaseNet):
  506. return (self.network <= other.network and
  507. self.broadcast >= other.broadcast)
  508. # dealing with another address
  509. else:
  510. return (int(self.network) <= int(other._ip) <=
  511. int(self.broadcast))
  512. def overlaps(self, other):
  513. """Tell if self is partly contained in other."""
  514. return self.network in other or self.broadcast in other or (
  515. other.network in self or other.broadcast in self)
  516. @property
  517. def network(self):
  518. x = self._cache.get('network')
  519. if x is None:
  520. x = IPAddress(self._ip & int(self.netmask), version=self._version)
  521. self._cache['network'] = x
  522. return x
  523. @property
  524. def broadcast(self):
  525. x = self._cache.get('broadcast')
  526. if x is None:
  527. x = IPAddress(self._ip | int(self.hostmask), version=self._version)
  528. self._cache['broadcast'] = x
  529. return x
  530. @property
  531. def hostmask(self):
  532. x = self._cache.get('hostmask')
  533. if x is None:
  534. x = IPAddress(int(self.netmask) ^ self._ALL_ONES,
  535. version=self._version)
  536. self._cache['hostmask'] = x
  537. return x
  538. @property
  539. def with_prefixlen(self):
  540. return '%s/%d' % (str(self.ip), self._prefixlen)
  541. @property
  542. def with_netmask(self):
  543. return '%s/%s' % (str(self.ip), str(self.netmask))
  544. @property
  545. def with_hostmask(self):
  546. return '%s/%s' % (str(self.ip), str(self.hostmask))
  547. @property
  548. def numhosts(self):
  549. """Number of hosts in the current subnet."""
  550. return int(self.broadcast) - int(self.network) + 1
  551. @property
  552. def version(self):
  553. raise NotImplementedError('BaseNet has no version')
  554. @property
  555. def prefixlen(self):
  556. return self._prefixlen
  557. def address_exclude(self, other):
  558. """Remove an address from a larger block.
  559. For example:
  560. addr1 = IPNetwork('10.1.1.0/24')
  561. addr2 = IPNetwork('10.1.1.0/26')
  562. addr1.address_exclude(addr2) =
  563. [IPNetwork('10.1.1.64/26'), IPNetwork('10.1.1.128/25')]
  564. or IPv6:
  565. addr1 = IPNetwork('::1/32')
  566. addr2 = IPNetwork('::1/128')
  567. addr1.address_exclude(addr2) = [IPNetwork('::0/128'),
  568. IPNetwork('::2/127'),
  569. IPNetwork('::4/126'),
  570. IPNetwork('::8/125'),
  571. ...
  572. IPNetwork('0:0:8000::/33')]
  573. Args:
  574. other: An IPvXNetwork object of the same type.
  575. Returns:
  576. A sorted list of IPvXNetwork objects addresses which is self
  577. minus other.
  578. Raises:
  579. TypeError: If self and other are of difffering address
  580. versions, or if other is not a network object.
  581. ValueError: If other is not completely contained by self.
  582. """
  583. if not self._version == other._version:
  584. raise TypeError("%s and %s are not of the same version" % (
  585. str(self), str(other)))
  586. if not isinstance(other, _BaseNet):
  587. raise TypeError("%s is not a network object" % str(other))
  588. if other not in self:
  589. raise ValueError('%s not contained in %s' % (str(other),
  590. str(self)))
  591. if other == self:
  592. return []
  593. ret_addrs = []
  594. # Make sure we're comparing the network of other.
  595. other = IPNetwork('%s/%s' % (str(other.network), str(other.prefixlen)),
  596. version=other._version)
  597. s1, s2 = self.subnet()
  598. while s1 != other and s2 != other:
  599. if other in s1:
  600. ret_addrs.append(s2)
  601. s1, s2 = s1.subnet()
  602. elif other in s2:
  603. ret_addrs.append(s1)
  604. s1, s2 = s2.subnet()
  605. else:
  606. # If we got here, there's a bug somewhere.
  607. assert True == False, ('Error performing exclusion: '
  608. 's1: %s s2: %s other: %s' %
  609. (str(s1), str(s2), str(other)))
  610. if s1 == other:
  611. ret_addrs.append(s2)
  612. elif s2 == other:
  613. ret_addrs.append(s1)
  614. else:
  615. # If we got here, there's a bug somewhere.
  616. assert True == False, ('Error performing exclusion: '
  617. 's1: %s s2: %s other: %s' %
  618. (str(s1), str(s2), str(other)))
  619. return sorted(ret_addrs, key=_BaseNet._get_networks_key)
  620. def compare_networks(self, other):
  621. """Compare two IP objects.
  622. This is only concerned about the comparison of the integer
  623. representation of the network addresses. This means that the
  624. host bits aren't considered at all in this method. If you want
  625. to compare host bits, you can easily enough do a
  626. 'HostA._ip < HostB._ip'
  627. Args:
  628. other: An IP object.
  629. Returns:
  630. If the IP versions of self and other are the same, returns:
  631. -1 if self < other:
  632. eg: IPv4('1.1.1.0/24') < IPv4('1.1.2.0/24')
  633. IPv6('1080::200C:417A') < IPv6('1080::200B:417B')
  634. 0 if self == other
  635. eg: IPv4('1.1.1.1/24') == IPv4('1.1.1.2/24')
  636. IPv6('1080::200C:417A/96') == IPv6('1080::200C:417B/96')
  637. 1 if self > other
  638. eg: IPv4('1.1.1.0/24') > IPv4('1.1.0.0/24')
  639. IPv6('1080::1:200C:417A/112') >
  640. IPv6('1080::0:200C:417A/112')
  641. If the IP versions of self and other are different, returns:
  642. -1 if self._version < other._version
  643. eg: IPv4('10.0.0.1/24') < IPv6('::1/128')
  644. 1 if self._version > other._version
  645. eg: IPv6('::1/128') > IPv4('255.255.255.0/24')
  646. """
  647. if self._version < other._version:
  648. return -1
  649. if self._version > other._version:
  650. return 1
  651. # self._version == other._version below here:
  652. if self.network < other.network:
  653. return -1
  654. if self.network > other.network:
  655. return 1
  656. # self.network == other.network below here:
  657. if self.netmask < other.netmask:
  658. return -1
  659. if self.netmask > other.netmask:
  660. return 1
  661. # self.network == other.network and self.netmask == other.netmask
  662. return 0
  663. def _get_networks_key(self):
  664. """Network-only key function.
  665. Returns an object that identifies this address' network and
  666. netmask. This function is a suitable "key" argument for sorted()
  667. and list.sort().
  668. """
  669. return (self._version, self.network, self.netmask)
  670. def _ip_int_from_prefix(self, prefixlen=None):
  671. """Turn the prefix length netmask into a int for comparison.
  672. Args:
  673. prefixlen: An integer, the prefix length.
  674. Returns:
  675. An integer.
  676. """
  677. if not prefixlen and prefixlen != 0:
  678. prefixlen = self._prefixlen
  679. return self._ALL_ONES ^ (self._ALL_ONES >> prefixlen)
  680. def _prefix_from_ip_int(self, ip_int, mask=32):
  681. """Return prefix length from the decimal netmask.
  682. Args:
  683. ip_int: An integer, the IP address.
  684. mask: The netmask. Defaults to 32.
  685. Returns:
  686. An integer, the prefix length.
  687. """
  688. while mask:
  689. if ip_int & 1 == 1:
  690. break
  691. ip_int >>= 1
  692. mask -= 1
  693. return mask
  694. def _ip_string_from_prefix(self, prefixlen=None):
  695. """Turn a prefix length into a dotted decimal string.
  696. Args:
  697. prefixlen: An integer, the netmask prefix length.
  698. Returns:
  699. A string, the dotted decimal netmask string.
  700. """
  701. if not prefixlen:
  702. prefixlen = self._prefixlen
  703. return self._string_from_ip_int(self._ip_int_from_prefix(prefixlen))
  704. def iter_subnets(self, prefixlen_diff=1, new_prefix=None):
  705. """The subnets which join to make the current subnet.
  706. In the case that self contains only one IP
  707. (self._prefixlen == 32 for IPv4 or self._prefixlen == 128
  708. for IPv6), return a list with just ourself.
  709. Args:
  710. prefixlen_diff: An integer, the amount the prefix length
  711. should be increased by. This should not be set if
  712. new_prefix is also set.
  713. new_prefix: The desired new prefix length. This must be a
  714. larger number (smaller prefix) than the existing prefix.
  715. This should not be set if prefixlen_diff is also set.
  716. Returns:
  717. An iterator of IPv(4|6) objects.
  718. Raises:
  719. ValueError: The prefixlen_diff is too small or too large.
  720. OR
  721. prefixlen_diff and new_prefix are both set or new_prefix
  722. is a smaller number than the current prefix (smaller
  723. number means a larger network)
  724. """
  725. if self._prefixlen == self._max_prefixlen:
  726. yield self
  727. return
  728. if new_prefix is not None:
  729. if new_prefix < self._prefixlen:
  730. raise ValueError('new prefix must be longer')
  731. if prefixlen_diff != 1:
  732. raise ValueError('cannot set prefixlen_diff and new_prefix')
  733. prefixlen_diff = new_prefix - self._prefixlen
  734. if prefixlen_diff < 0:
  735. raise ValueError('prefix length diff must be > 0')
  736. new_prefixlen = self._prefixlen + prefixlen_diff
  737. if not self._is_valid_netmask(str(new_prefixlen)):
  738. raise ValueError(
  739. 'prefix length diff %d is invalid for netblock %s' % (
  740. new_prefixlen, str(self)))
  741. first = IPNetwork('%s/%s' % (str(self.network),
  742. str(self._prefixlen + prefixlen_diff)),
  743. version=self._version)
  744. yield first
  745. current = first
  746. while True:
  747. broadcast = current.broadcast
  748. if broadcast == self.broadcast:
  749. return
  750. new_addr = IPAddress(int(broadcast) + 1, version=self._version)
  751. current = IPNetwork('%s/%s' % (str(new_addr), str(new_prefixlen)),
  752. version=self._version)
  753. yield current
  754. def masked(self):
  755. """Return the network object with the host bits masked out."""
  756. return IPNetwork('%s/%d' % (self.network, self._prefixlen),
  757. version=self._version)
  758. def subnet(self, prefixlen_diff=1, new_prefix=None):
  759. """Return a list of subnets, rather than an iterator."""
  760. return list(self.iter_subnets(prefixlen_diff, new_prefix))
  761. def supernet(self, prefixlen_diff=1, new_prefix=None):
  762. """The supernet containing the current network.
  763. Args:
  764. prefixlen_diff: An integer, the amount the prefix length of
  765. the network should be decreased by. For example, given a
  766. /24 network and a prefixlen_diff of 3, a supernet with a
  767. /21 netmask is returned.
  768. Returns:
  769. An IPv4 network object.
  770. Raises:
  771. ValueError: If self.prefixlen - prefixlen_diff < 0. I.e., you have a
  772. negative prefix length.
  773. OR
  774. If prefixlen_diff and new_prefix are both set or new_prefix is a
  775. larger number than the current prefix (larger number means a
  776. smaller network)
  777. """
  778. if self._prefixlen == 0:
  779. return self
  780. if new_prefix is not None:
  781. if new_prefix > self._prefixlen:
  782. raise ValueError('new prefix must be shorter')
  783. if prefixlen_diff != 1:
  784. raise ValueError('cannot set prefixlen_diff and new_prefix')
  785. prefixlen_diff = self._prefixlen - new_prefix
  786. if self.prefixlen - prefixlen_diff < 0:
  787. raise ValueError(
  788. 'current prefixlen is %d, cannot have a prefixlen_diff of %d' %
  789. (self.prefixlen, prefixlen_diff))
  790. return IPNetwork('%s/%s' % (str(self.network),
  791. str(self.prefixlen - prefixlen_diff)),
  792. version=self._version)
  793. # backwards compatibility
  794. Subnet = subnet
  795. Supernet = supernet
  796. AddressExclude = address_exclude
  797. CompareNetworks = compare_networks
  798. Contains = __contains__
  799. class _BaseV4(object):
  800. """Base IPv4 object.
  801. The following methods are used by IPv4 objects in both single IP
  802. addresses and networks.
  803. """
  804. # Equivalent to 255.255.255.255 or 32 bits of 1's.
  805. _ALL_ONES = (2**IPV4LENGTH) - 1
  806. _DECIMAL_DIGITS = frozenset('0123456789')
  807. def __init__(self, address):
  808. self._version = 4
  809. self._max_prefixlen = IPV4LENGTH
  810. def _explode_shorthand_ip_string(self):
  811. return str(self)
  812. def _ip_int_from_string(self, ip_str):
  813. """Turn the given IP string into an integer for comparison.
  814. Args:
  815. ip_str: A string, the IP ip_str.
  816. Returns:
  817. The IP ip_str as an integer.
  818. Raises:
  819. AddressValueError: if ip_str isn't a valid IPv4 Address.
  820. """
  821. octets = ip_str.split('.')
  822. if len(octets) != 4:
  823. raise AddressValueError(ip_str)
  824. packed_ip = 0
  825. for oc in octets:
  826. try:
  827. packed_ip = (packed_ip << 8) | self._parse_octet(oc)
  828. except ValueError:
  829. raise AddressValueError(ip_str)
  830. return packed_ip
  831. def _parse_octet(self, octet_str):
  832. """Convert a decimal octet into an integer.
  833. Args:
  834. octet_str: A string, the number to parse.
  835. Returns:
  836. The octet as an integer.
  837. Raises:
  838. ValueError: if the octet isn't strictly a decimal from [0..255].
  839. """
  840. # Whitelist the characters, since int() allows a lot of bizarre stuff.
  841. if not self._DECIMAL_DIGITS.issuperset(octet_str):
  842. raise ValueError
  843. octet_int = int(octet_str, 10)
  844. # Disallow leading zeroes, because no clear standard exists on
  845. # whether these should be interpreted as decimal or octal.
  846. if octet_int > 255 or (octet_str[0] == '0' and len(octet_str) > 1):
  847. raise ValueError
  848. return octet_int
  849. def _string_from_ip_int(self, ip_int):
  850. """Turns a 32-bit integer into dotted decimal notation.
  851. Args:
  852. ip_int: An integer, the IP address.
  853. Returns:
  854. The IP address as a string in dotted decimal notation.
  855. """
  856. octets = []
  857. for _ in xrange(4):
  858. octets.insert(0, str(ip_int & 0xFF))
  859. ip_int >>= 8
  860. return '.'.join(octets)
  861. @property
  862. def max_prefixlen(self):
  863. return self._max_prefixlen
  864. @property
  865. def packed(self):
  866. """The binary representation of this address."""
  867. return v4_int_to_packed(self._ip)
  868. @property
  869. def version(self):
  870. return self._version
  871. @property
  872. def is_reserved(self):
  873. """Test if the address is otherwise IETF reserved.
  874. Returns:
  875. A boolean, True if the address is within the
  876. reserved IPv4 Network range.
  877. """
  878. return self in IPv4Network('240.0.0.0/4')
  879. @property
  880. def is_private(self):
  881. """Test if this address is allocated for private networks.
  882. Returns:
  883. A boolean, True if the address is reserved per RFC 1918.
  884. """
  885. return (self in IPv4Network('10.0.0.0/8') or
  886. self in IPv4Network('172.16.0.0/12') or
  887. self in IPv4Network('192.168.0.0/16'))
  888. @property
  889. def is_multicast(self):
  890. """Test if the address is reserved for multicast use.
  891. Returns:
  892. A boolean, True if the address is multicast.
  893. See RFC 3171 for details.
  894. """
  895. return self in IPv4Network('224.0.0.0/4')
  896. @property
  897. def is_unspecified(self):
  898. """Test if the address is unspecified.
  899. Returns:
  900. A boolean, True if this is the unspecified address as defined in
  901. RFC 5735 3.
  902. """
  903. return self in IPv4Network('0.0.0.0')
  904. @property
  905. def is_loopback(self):
  906. """Test if the address is a loopback address.
  907. Returns:
  908. A boolean, True if the address is a loopback per RFC 3330.
  909. """
  910. return self in IPv4Network('127.0.0.0/8')
  911. @property
  912. def is_link_local(self):
  913. """Test if the address is reserved for link-local.
  914. Returns:
  915. A boolean, True if the address is link-local per RFC 3927.
  916. """
  917. return self in IPv4Network('169.254.0.0/16')
  918. class IPv4Address(_BaseV4, _BaseIP):
  919. """Represent and manipulate single IPv4 Addresses."""
  920. def __init__(self, address):
  921. """
  922. Args:
  923. address: A string or integer representing the IP
  924. '192.168.1.1'
  925. Additionally, an integer can be passed, so
  926. IPv4Address('192.168.1.1') == IPv4Address(3232235777).
  927. or, more generally
  928. IPv4Address(int(IPv4Address('192.168.1.1'))) ==
  929. IPv4Address('192.168.1.1')
  930. Raises:
  931. AddressValueError: If ipaddr isn't a valid IPv4 address.
  932. """
  933. _BaseV4.__init__(self, address)
  934. # Efficient constructor from integer.
  935. if isinstance(address, (int, long)):
  936. self._ip = address
  937. if address < 0 or address > self._ALL_ONES:
  938. raise AddressValueError(address)
  939. return
  940. # Constructing from a packed address
  941. if isinstance(address, Bytes):
  942. try:
  943. self._ip, = struct.unpack('!I', address)
  944. except struct.error:
  945. raise AddressValueError(address) # Wrong length.
  946. return
  947. # Assume input argument to be string or any object representation
  948. # which converts into a formatted IP string.
  949. addr_str = str(address)
  950. self._ip = self._ip_int_from_string(addr_str)
  951. class IPv4Network(_BaseV4, _BaseNet):
  952. """This class represents and manipulates 32-bit IPv4 networks.
  953. Attributes: [examples for IPv4Network('1.2.3.4/27')]
  954. ._ip: 16909060
  955. .ip: IPv4Address('1.2.3.4')
  956. .network: IPv4Address('1.2.3.0')
  957. .hostmask: IPv4Address('0.0.0.31')
  958. .broadcast: IPv4Address('1.2.3.31')
  959. .netmask: IPv4Address('255.255.255.224')
  960. .prefixlen: 27
  961. """
  962. # the valid octets for host and netmasks. only useful for IPv4.
  963. _valid_mask_octets = set((255, 254, 252, 248, 240, 224, 192, 128, 0))
  964. def __init__(self, address, strict=False):
  965. """Instantiate a new IPv4 network object.
  966. Args:
  967. address: A string or integer representing the IP [& network].
  968. '192.168.1.1/24'
  969. '192.168.1.1/255.255.255.0'
  970. '192.168.1.1/0.0.0.255'
  971. are all functionally the same in IPv4. Similarly,
  972. '192.168.1.1'
  973. '192.168.1.1/255.255.255.255'
  974. '192.168.1.1/32'
  975. are also functionaly equivalent. That is to say, failing to
  976. provide a subnetmask will create an object with a mask of /32.
  977. If the mask (portion after the / in the argument) is given in
  978. dotted quad form, it is treated as a netmask if it starts with a
  979. non-zero field (e.g. /255.0.0.0 == /8) and as a hostmask if it
  980. starts with a zero field (e.g. 0.255.255.255 == /8), with the
  981. single exception of an all-zero mask which is treated as a
  982. netmask == /0. If no mask is given, a default of /32 is used.
  983. Additionally, an integer can be passed, so
  984. IPv4Network('192.168.1.1') == IPv4Network(3232235777).
  985. or, more generally
  986. IPv4Network(int(IPv4Network('192.168.1.1'))) ==
  987. IPv4Network('192.168.1.1')
  988. strict: A boolean. If true, ensure that we have been passed
  989. A true network address, eg, 192.168.1.0/24 and not an
  990. IP address on a network, eg, 192.168.1.1/24.
  991. Raises:
  992. AddressValueError: If ipaddr isn't a valid IPv4 address.
  993. NetmaskValueError: If the netmask isn't valid for
  994. an IPv4 address.
  995. ValueError: If strict was True and a network address was not
  996. supplied.
  997. """
  998. _BaseNet.__init__(self, address)
  999. _BaseV4.__init__(self, address)
  1000. # Constructing from an integer or packed bytes.
  1001. if isinstance(address, (int, long, Bytes)):
  1002. self.ip = IPv4Address(address)
  1003. self._ip = self.ip._ip
  1004. self._prefixlen = self._max_prefixlen
  1005. self.netmask = IPv4Address(self._ALL_ONES)
  1006. return
  1007. # Assume input argument to be string or any object representation
  1008. # which converts into a formatted IP prefix string.
  1009. addr = str(address).split('/')
  1010. if len(addr) > 2:
  1011. raise AddressValueError(address)
  1012. self._ip = self._ip_int_from_string(addr[0])
  1013. self.ip = IPv4Address(self._ip)
  1014. if len(addr) == 2:
  1015. mask = addr[1].split('.')
  1016. if len(mask) == 4:
  1017. # We have dotted decimal netmask.
  1018. if self._is_valid_netmask(addr[1]):
  1019. self.netmask = IPv4Address(self._ip_int_from_string(
  1020. addr[1]))
  1021. elif self._is_hostmask(addr[1]):
  1022. self.netmask = IPv4Address(
  1023. self._ip_int_from_string(addr[1]) ^ self._ALL_ONES)
  1024. else:
  1025. raise NetmaskValueError('%s is not a valid netmask'
  1026. % addr[1])
  1027. self._prefixlen = self._prefix_from_ip_int(int(self.netmask))
  1028. else:
  1029. # We have a netmask in prefix length form.
  1030. if not self._is_valid_netmask(addr[1]):
  1031. raise NetmaskValueError(addr[1])
  1032. self._prefixlen = int(addr[1])
  1033. self.netmask = IPv4Address(self._ip_int_from_prefix(
  1034. self._prefixlen))
  1035. else:
  1036. self._prefixlen = self._max_prefixlen
  1037. self.netmask = IPv4Address(self._ip_int_from_prefix(
  1038. self._prefixlen))
  1039. if strict:
  1040. if self.ip != self.network:
  1041. raise ValueError('%s has host bits set' %
  1042. self.ip)
  1043. if self._prefixlen == (self._max_prefixlen - 1):
  1044. self.iterhosts = self.__iter__
  1045. def _is_hostmask(self, ip_str):
  1046. """Test if the IP string is a hostmask (rather than a netmask).
  1047. Args:
  1048. ip_str: A string, the potential hostmask.
  1049. Returns:
  1050. A boolean, True if the IP string is a hostmask.
  1051. """
  1052. bits = ip_str.split('.')
  1053. try:
  1054. parts = [int(x) for x in bits if int(x) in self._valid_mask_octets]
  1055. except ValueError:
  1056. return False
  1057. if len(parts) != len(bits):
  1058. return False
  1059. if parts[0] < parts[-1]:
  1060. return True
  1061. return False
  1062. def _is_valid_netmask(self, netmask):
  1063. """Verify that the netmask is valid.
  1064. Args:
  1065. netmask: A string, either a prefix or dotted decimal
  1066. netmask.
  1067. Returns:
  1068. A boolean, True if the prefix represents a valid IPv4
  1069. netmask.
  1070. """
  1071. mask = netmask.split('.')
  1072. if len(mask) == 4:
  1073. if [x for x in mask if int(x) not in self._valid_mask_octets]:
  1074. return False
  1075. if [y for idx, y in enumerate(mask) if idx > 0 and
  1076. y > mask[idx - 1]]:
  1077. return False
  1078. return True
  1079. try:
  1080. netmask = int(netmask)
  1081. except ValueError:
  1082. return False
  1083. return 0 <= netmask <= self._max_prefixlen
  1084. # backwards compatibility
  1085. IsRFC1918 = lambda self: self.is_private
  1086. IsMulticast = lambda self: self.is_multicast
  1087. IsLoopback = lambda self: self.is_loopback
  1088. IsLinkLocal = lambda self: self.is_link_local
  1089. class _BaseV6(object):
  1090. """Base IPv6 object.
  1091. The following methods are used by IPv6 objects in both single IP
  1092. addresses and networks.
  1093. """
  1094. _ALL_ONES = (2**IPV6LENGTH) - 1
  1095. _HEXTET_COUNT = 8
  1096. _HEX_DIGITS = frozenset('0123456789ABCDEFabcdef')
  1097. def __init__(self, address):
  1098. self._version = 6
  1099. self._max_prefixlen = IPV6LENGTH
  1100. def _ip_int_from_string(self, ip_str):
  1101. """Turn an IPv6 ip_str into an integer.
  1102. Args:
  1103. ip_str: A string, the IPv6 ip_str.
  1104. Returns:
  1105. A long, the IPv6 ip_str.
  1106. Raises:
  1107. AddressValueError: if ip_str isn't a valid IPv6 Address.
  1108. """
  1109. parts = ip_str.split(':')
  1110. # An IPv6 address needs at least 2 colons (3 parts).
  1111. if len(parts) < 3:
  1112. raise AddressValueError(ip_str)
  1113. # If the address has an IPv4-style suffix, convert it to hexadecimal.
  1114. if '.' in parts[-1]:
  1115. ipv4_int = IPv4Address(parts.pop())._ip
  1116. parts.append('%x' % ((ipv4_int >> 16) & 0xFFFF))
  1117. parts.append('%x' % (ipv4_int & 0xFFFF))
  1118. # An IPv6 address can't have more than 8 colons (9 parts).
  1119. if len(parts) > self._HEXTET_COUNT + 1:
  1120. raise AddressValueError(ip_str)
  1121. # Disregarding the endpoints, find '::' with nothing in between.
  1122. # This indicates that a run of zeroes has been skipped.
  1123. try:
  1124. skip_index, = (
  1125. [i for i in xrange(1, len(parts) - 1) if not parts[i]] or
  1126. [None])
  1127. except ValueError:
  1128. # Can't have more than one '::'
  1129. raise AddressValueError(ip_str)
  1130. # parts_hi is the number of parts to copy from above/before the '::'
  1131. # parts_lo is the number of parts to copy from below/after the '::'
  1132. if skip_index is not None:
  1133. # If we found a '::', then check if it also covers the endpoints.
  1134. parts_hi = skip_index
  1135. parts_lo = len(parts) - skip_index - 1
  1136. if not parts[0]:
  1137. parts_hi -= 1
  1138. if parts_hi:
  1139. raise AddressValueError(ip_str) # ^: requires ^::
  1140. if not parts[-1]:
  1141. parts_lo -= 1
  1142. if parts_lo:
  1143. raise AddressValueError(ip_str) # :$ requires ::$
  1144. parts_skipped = self._HEXTET_COUNT - (parts_hi + parts_lo)
  1145. if parts_skipped < 1:
  1146. raise AddressValueError(ip_str)
  1147. else:
  1148. # Otherwise, allocate the entire address to parts_hi. The endpoints
  1149. # could still be empty, but _parse_hextet() will check for that.
  1150. if len(parts) != self._HEXTET_COUNT:
  1151. raise AddressValueError(ip_str)
  1152. parts_hi = len(parts)
  1153. parts_lo = 0
  1154. parts_skipped = 0
  1155. try:
  1156. # Now, parse the hextets into a 128-bit integer.
  1157. ip_int = 0L
  1158. for i in xrange(parts_hi):
  1159. ip_int <<= 16
  1160. ip_int |= self._parse_hextet(parts[i])
  1161. ip_int <<= 16 * parts_skipped
  1162. for i in xrange(-parts_lo, 0):
  1163. ip_int <<= 16
  1164. ip_int |= self._parse_hextet(parts[i])
  1165. return ip_int
  1166. except ValueError:
  1167. raise AddressValueError(ip_str)
  1168. def _parse_hextet(self, hextet_str):
  1169. """Convert an IPv6 hextet string into an integer.
  1170. Args:
  1171. hextet_str: A string, the number to parse.
  1172. Returns:
  1173. The hextet as an integer.
  1174. Raises:
  1175. ValueError: if the input isn't strictly a hex number from [0..FFFF].
  1176. """
  1177. # Whitelist the characters, since int() allows a lot of bizarre stuff.
  1178. if not self._HEX_DIGITS.issuperset(hextet_str):
  1179. raise ValueError
  1180. hextet_int = int(hextet_str, 16)
  1181. if hextet_int > 0xFFFF:
  1182. raise ValueError
  1183. return hextet_int
  1184. def _compress_hextets(self, hextets):
  1185. """Compresses a list of hextets.
  1186. Compresses a list of strings, replacing the longest continuous
  1187. sequence of "0" in the list with "" and adding empty strings at
  1188. the beginning or at the end of the string such that subsequently
  1189. calling ":".join(hextets) will produce the compressed version of
  1190. the IPv6 address.
  1191. Args:
  1192. hextets: A list of strings, the hextets to compress.
  1193. Returns:
  1194. A list of strings.
  1195. """
  1196. best_doublecolon_start = -1
  1197. best_doublecolon_len = 0
  1198. doublecolon_start = -1
  1199. doublecolon_len = 0
  1200. for index in range(len(hextets)):
  1201. if hextets[index] == '0':
  1202. doublecolon_len += 1
  1203. if doublecolon_start == -1:
  1204. # Start of a sequence of zeros.
  1205. doublecolon_start = index
  1206. if doublecolon_len > best_doublecolon_len:
  1207. # This is the longest sequence of zeros so far.
  1208. best_doublecolon_len = doublecolon_len
  1209. best_doublecolon_start = doublecolon_start
  1210. else:
  1211. doublecolon_len = 0
  1212. doublecolon_start = -1
  1213. if best_doublecolon_len > 1:
  1214. best_doublecolon_end = (best_doublecolon_start +
  1215. best_doublecolon_len)
  1216. # For zeros at the end of the address.
  1217. if best_doublecolon_end == len(hextets):
  1218. hextets += ['']
  1219. hextets[best_doublecolon_start:best_doublecolon_end] = ['']
  1220. # For zeros at the beginning of the address.
  1221. if best_doublecolon_start == 0:
  1222. hextets = [''] + hextets
  1223. return hextets
  1224. def _string_from_ip_int(self, ip_int=None):
  1225. """Turns a 128-bit integer into hexadecimal notation.
  1226. Args:
  1227. ip_int: An integer, the IP address.
  1228. Returns:
  1229. A string, the hexadecimal representation of the address.
  1230. Raises:
  1231. ValueError: The address is bigger than 128 bits of all ones.
  1232. """
  1233. if not ip_int and ip_int != 0:
  1234. ip_int = int(self._ip)
  1235. if ip_int > self._ALL_ONES:
  1236. raise ValueError('IPv6 address is too large')
  1237. hex_str = '%032x' % ip_int
  1238. hextets = []
  1239. for x in range(0, 32, 4):
  1240. hextets.append('%x' % int(hex_str[x:x+4], 16))
  1241. hextets = self._compress_hextets(hextets)
  1242. return ':'.join(hextets)
  1243. def _explode_shorthand_ip_string(self):
  1244. """Expand a shortened IPv6 address.
  1245. Args:
  1246. ip_str: A string, the IPv6 address.
  1247. Returns:
  1248. A string, the expanded IPv6 address.
  1249. """
  1250. if isinstance(self, _BaseNet):
  1251. ip_str = str(self.ip)
  1252. else:
  1253. ip_str = str(self)
  1254. ip_int = self._ip_int_from_string(ip_str)
  1255. parts = []
  1256. for i in xrange(self._HEXTET_COUNT):
  1257. parts.append('%04x' % (ip_int & 0xFFFF))
  1258. ip_int >>= 16
  1259. parts.reverse()
  1260. if isinstance(self, _BaseNet):
  1261. return '%s/%d' % (':'.join(parts), self.prefixlen)
  1262. return ':'.join(parts)
  1263. @property
  1264. def max_prefixlen(self):
  1265. return self._max_prefixlen
  1266. @property
  1267. def packed(self):
  1268. """The binary representation of this address."""
  1269. return v6_int_to_packed(self._ip)
  1270. @property
  1271. def version(self):
  1272. return self._version
  1273. @property
  1274. def is_multicast(self):
  1275. """Test if the address is reserved for multicast use.
  1276. Returns:
  1277. A boolean, True if the address is a multicast address.
  1278. See RFC 2373 2.7 for details.
  1279. """
  1280. return self in IPv6Network('ff00::/8')
  1281. @property
  1282. def is_reserved(self):
  1283. """Test if the address is otherwise IETF reserved.
  1284. Returns:
  1285. A boolean, True if the address is within one of the
  1286. reserved IPv6 Network ranges.
  1287. """
  1288. return (self in IPv6Network('::/8') or
  1289. self in IPv6Network('100::/8') or
  1290. self in IPv6Network('200::/7') or
  1291. self in IPv6Network('400::/6') or
  1292. self in IPv6Network('800::/5') or
  1293. self in IPv6Network('1000::/4') or
  1294. self in IPv6Network('4000::/3') or
  1295. self in IPv6Network('6000::/3') or
  1296. self in IPv6Network('8000::/3') or
  1297. self in IPv6Network('A000::/3') or
  1298. self in IPv6Network('C000::/3') or
  1299. self in IPv6Network('E000::/4') or
  1300. self in IPv6Network('F000::/5') or
  1301. self in IPv6Network('F800::/6') or
  1302. self in IPv6Network('FE00::/9'))
  1303. @property
  1304. def is_unspecified(self):
  1305. """Test if the address is unspecified.
  1306. Returns:
  1307. A boolean, True if this is the unspecified address as defined in
  1308. RFC 2373 2.5.2.
  1309. """
  1310. return self._ip == 0 and getattr(self, '_prefixlen', 128) == 128
  1311. @property
  1312. def is_loopback(self):
  1313. """Test if the address is a loopback address.
  1314. Returns:
  1315. A boolean, True if the address is a loopback address as defined in
  1316. RFC 2373 2.5.3.
  1317. """
  1318. return self._ip == 1 and getattr(self, '_prefixlen', 128) == 128
  1319. @property
  1320. def is_link_local(self):
  1321. """Test if the address is reserved for link-local.
  1322. Returns:
  1323. A boolean, True if the address is reserved per RFC 4291.
  1324. """
  1325. return self in IPv6Network('fe80::/10')
  1326. @property
  1327. def is_site_local(self):
  1328. """Test if the address is reserved for site-local.
  1329. Note that the site-local address space has been deprecated by RFC 3879.
  1330. Use is_private to test if this address is in the space of unique local
  1331. addresses as defined by RFC 4193.
  1332. Returns:
  1333. A boolean, True if the address is reserved per RFC 3513 2.5.6.
  1334. """
  1335. return self in IPv6Network('fec0::/10')
  1336. @property
  1337. def is_private(self):
  1338. """Test if this address is allocated for private networks.
  1339. Returns:
  1340. A boolean, True if the address is reserved per RFC 4193.
  1341. """
  1342. return self in IPv6Network('fc00::/7')
  1343. @property
  1344. def ipv4_mapped(self):
  1345. """Return the IPv4 mapped address.
  1346. Returns:
  1347. If the IPv6 address is a v4 mapped address, return the
  1348. IPv4 mapped address. Return None otherwise.
  1349. """
  1350. if (self._ip >> 32) != 0xFFFF:
  1351. return None
  1352. return IPv4Address(self._ip & 0xFFFFFFFF)
  1353. @property
  1354. def teredo(self):
  1355. """Tuple of embedded teredo IPs.
  1356. Returns:
  1357. Tuple of the (server, client) IPs or None if the address
  1358. doesn't appear to be a teredo address (doesn't start with
  1359. 2001::/32)
  1360. """
  1361. if (self._ip >> 96) != 0x20010000:
  1362. return None
  1363. return (IPv4Address((self._ip >> 64) & 0xFFFFFFFF),
  1364. IPv4Address(~self._ip & 0xFFFFFFFF))
  1365. @property
  1366. def sixtofour(self):
  1367. """Return the IPv4 6to4 embedded address.
  1368. Returns:
  1369. The IPv4 6to4-embedded address if present or None if the
  1370. address doesn't appear to contain a 6to4 embedded address.
  1371. """
  1372. if (self._ip >> 112) != 0x2002:
  1373. return None
  1374. return IPv4Address((self._ip >> 80) & 0xFFFFFFFF)
  1375. class IPv6Address(_BaseV6, _BaseIP):
  1376. """Represent and manipulate single IPv6 Addresses.
  1377. """
  1378. def __init__(self, address):
  1379. """Instantiate a new IPv6 address object.
  1380. Args:
  1381. address: A string or integer representing the IP
  1382. Additionally, an integer can be passed, so
  1383. IPv6Address('2001:4860::') ==
  1384. IPv6Address(42541956101370907050197289607612071936L).
  1385. or, more generally
  1386. IPv6Address(IPv6Address('2001:4860::')._ip) ==
  1387. IPv6Address('2001:4860::')
  1388. Raises:
  1389. AddressValueError: If address isn't a valid IPv6 address.
  1390. """
  1391. _BaseV6.__init__(self, address)
  1392. # Efficient constructor from integer.
  1393. if isinstance(address, (int, long)):
  1394. self._ip = address
  1395. if address < 0 or address > self._ALL_ONES:
  1396. raise AddressValueError(address)
  1397. return
  1398. # Constructing from a packed address
  1399. if isinstance(address, Bytes):
  1400. try:
  1401. hi, lo = struct.unpack('!QQ', address)
  1402. except struct.error:
  1403. raise AddressValueError(address) # Wrong length.
  1404. self._ip = (hi << 64) | lo
  1405. return
  1406. # Assume input argument to be string or any object representation
  1407. # which converts into a formatted IP string.
  1408. addr_str = str(address)
  1409. if not addr_str:
  1410. raise AddressValueError('')
  1411. self._ip = self._ip_int_from_string(addr_str)
  1412. class IPv6Network(_BaseV6, _BaseNet):
  1413. """This class represents and manipulates 128-bit IPv6 networks.
  1414. Attributes: [examples for IPv6('2001:658:22A:CAFE:200::1/64')]
  1415. .ip: IPv6Address('2001:658:22a:cafe:200::1')
  1416. .network: IPv6Address('2001:658:22a:cafe::')
  1417. .hostmask: IPv6Address('::ffff:ffff:ffff:ffff')
  1418. .broadcast: IPv6Address('2001:658:22a:cafe:ffff:ffff:ffff:ffff')
  1419. .netmask: IPv6Address('ffff:ffff:ffff:ffff::')
  1420. .prefixlen: 64
  1421. """
  1422. def __init__(self, address, strict=False):
  1423. """Instantiate a new IPv6 Network object.
  1424. Args:
  1425. address: A string or integer representing the IPv6 network or the IP
  1426. and prefix/netmask.
  1427. '2001:4860::/128'
  1428. '2001:4860:0000:0000:0000:0000:0000:0000/128'
  1429. '2001:4860::'
  1430. are all functionally the same in IPv6. That is to say,
  1431. failing to provide a subnetmask will create an object with
  1432. a mask of /128.
  1433. Additionally, an integer can be passed, so
  1434. IPv6Network('2001:4860::') ==
  1435. IPv6Network(42541956101370907050197289607612071936L).
  1436. or, more generally
  1437. IPv6Network(IPv6Network('2001:4860::')._ip) ==
  1438. IPv6Network('2001:4860::')
  1439. strict: A boolean. If true, ensure that we have been passed
  1440. A true network address, eg, 192.168.1.0/24 and not an
  1441. IP address on a network, eg, 192.168.1.1/24.
  1442. Raises:
  1443. AddressValueError: If address isn't a valid IPv6 address.
  1444. NetmaskValueError: If the netmask isn't valid for
  1445. an IPv6 address.
  1446. ValueError: If strict was True and a network address was not
  1447. supplied.
  1448. """
  1449. _BaseNet.__init__(self, address)
  1450. _BaseV6.__init__(self, address)
  1451. # Constructing from an integer or packed bytes.
  1452. if isinstance(address, (int, long, Bytes)):
  1453. self.ip = IPv6Address(address)
  1454. self._ip = self.ip._ip
  1455. self._prefixlen = self._max_prefixlen
  1456. self.netmask = IPv6Address(self._ALL_ONES)
  1457. return
  1458. # Assume input argument to be string or any object representation
  1459. # which converts into a formatted IP prefix string.
  1460. addr = str(address).split('/')
  1461. if len(addr) > 2:
  1462. raise AddressValueError(address)
  1463. self._ip = self._ip_int_from_string(addr[0])
  1464. self.ip = IPv6Address(self._ip)
  1465. if len(addr) == 2:
  1466. if self._is_valid_netmask(addr[1]):
  1467. self._prefixlen = int(addr[1])
  1468. else:
  1469. raise NetmaskValueError(addr[1])
  1470. else:
  1471. self._prefixlen = self._max_prefixlen
  1472. self.netmask = IPv6Address(self._ip_int_from_prefix(self._prefixlen))
  1473. if strict:
  1474. if self.ip != self.network:
  1475. raise ValueError('%s has host bits set' %
  1476. self.ip)
  1477. if self._prefixlen == (self._max_prefixlen - 1):
  1478. self.iterhosts = self.__iter__
  1479. def _is_valid_netmask(self, prefixlen):
  1480. """Verify that the netmask/prefixlen is valid.
  1481. Args:
  1482. prefixlen: A string, the netmask in prefix length format.
  1483. Returns:
  1484. A boolean, True if the prefix represents a valid IPv6
  1485. netmask.
  1486. """
  1487. try:
  1488. prefixlen = int(prefixlen)
  1489. except ValueError:
  1490. return False
  1491. return 0 <= prefixlen <= self._max_prefixlen
  1492. @property
  1493. def with_netmask(self):
  1494. return self.with_prefixlen