1
0

test_ipaddress.py 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751
  1. '''
  2. Python 2.[67] port of Python 3.4's test_ipaddress.
  3. Almost verbatim copy of core lib w/compatibility fixes
  4. '''
  5. # pylint: skip-file
  6. # List of compatibility changes:
  7. # This backport uses bytearray instead of bytes, as bytes is the same
  8. # as str in Python 2.7.
  9. #bytes = bytearray
  10. # s/\(b'[^']\+'\)/bytearray(\1)/g
  11. # plus manual fixes for implicit string concatenation.
  12. # Python 3.4 has assertRaisesRegex where Python 2.7 only has assertRaisesRegexp.
  13. # s/\.assertRaisesRegexp(/.assertRaisesRegexp(/
  14. # Python 2.6 carries assertRaisesRegexp and others in unittest2
  15. # Python 2.6 wants unicode into bytes.fromhex
  16. # s/bytes.fromhex\("/bytes.fromhex(u"/g
  17. # Further compatibility changes are marked "Compatibility", below.
  18. # ----------------------------------------------------------------------------
  19. # Copyright 2007 Google Inc.
  20. # Licensed to PSF under a Contributor Agreement.
  21. """Unittest for ipaddress module."""
  22. # Import python libs
  23. import re
  24. import sys
  25. import contextlib
  26. import operator
  27. import sys
  28. # Import salt libs
  29. from salt._compat import ipaddress
  30. # Import salt test libs
  31. from tests.support.unit import TestCase, skipIf
  32. if sys.version_info < (3,):
  33. bytes = bytearray
  34. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  35. class BaseTestCase(TestCase):
  36. # One big change in ipaddress over the original ipaddr module is
  37. # error reporting that tries to assume users *don't know the rules*
  38. # for what constitutes an RFC compliant IP address
  39. # Ensuring these errors are emitted correctly in all relevant cases
  40. # meant moving to a more systematic test structure that allows the
  41. # test structure to map more directly to the module structure
  42. # Note that if the constructors are refactored so that addresses with
  43. # multiple problems get classified differently, that's OK - just
  44. # move the affected examples to the newly appropriate test case.
  45. # There is some duplication between the original relatively ad hoc
  46. # test suite and the new systematic tests. While some redundancy in
  47. # testing is considered preferable to accidentally deleting a valid
  48. # test, the original test suite will likely be reduced over time as
  49. # redundant tests are identified.
  50. @property
  51. def factory(self):
  52. raise NotImplementedError
  53. @contextlib.contextmanager
  54. def assertCleanError(self, exc_type, details, *args):
  55. """
  56. Ensure exception does not display a context by default
  57. Wraps TestCase.assertRaisesRegex
  58. """
  59. if args:
  60. details = details % args
  61. cm = self.assertRaisesRegex(exc_type, details)
  62. with cm as exc:
  63. yield exc
  64. # Compatibility: Python 2.7 does not support exception chaining
  65. ## Ensure we produce clean tracebacks on failure
  66. #if exc.exception.__context__ is not None:
  67. # self.assertTrue(exc.exception.__suppress_context__)
  68. def assertAddressError(self, details, *args):
  69. """Ensure a clean AddressValueError"""
  70. return self.assertCleanError(ipaddress.AddressValueError,
  71. details, *args)
  72. def assertNetmaskError(self, details, *args):
  73. """Ensure a clean NetmaskValueError"""
  74. return self.assertCleanError(ipaddress.NetmaskValueError,
  75. details, *args)
  76. def assertInstancesEqual(self, lhs, rhs):
  77. """Check constructor arguments produce equivalent instances"""
  78. self.assertEqual(self.factory(lhs), self.factory(rhs))
  79. class CommonTestMixin:
  80. def test_empty_address(self):
  81. with self.assertAddressError("Address cannot be empty"):
  82. self.factory("")
  83. def test_floats_rejected(self):
  84. with self.assertAddressError(re.escape(repr("1.0"))):
  85. self.factory(1.0)
  86. def test_not_an_index_issue15559(self):
  87. # Implementing __index__ makes for a very nasty interaction with the
  88. # bytes constructor. Thus, we disallow implicit use as an integer
  89. self.assertRaises(TypeError, operator.index, self.factory(1))
  90. self.assertRaises(TypeError, hex, self.factory(1))
  91. self.assertRaises(TypeError, bytes, self.factory(1))
  92. class CommonTestMixin_v4(CommonTestMixin):
  93. def test_leading_zeros(self):
  94. self.assertInstancesEqual("000.000.000.000", "0.0.0.0")
  95. self.assertInstancesEqual("192.168.000.001", "192.168.0.1")
  96. def test_int(self):
  97. self.assertInstancesEqual(0, "0.0.0.0")
  98. self.assertInstancesEqual(3232235521, "192.168.0.1")
  99. def test_packed(self):
  100. self.assertInstancesEqual(bytes.fromhex(u"00000000"), "0.0.0.0")
  101. self.assertInstancesEqual(bytes.fromhex(u"c0a80001"), "192.168.0.1")
  102. def test_negative_ints_rejected(self):
  103. msg = "-1 (< 0) is not permitted as an IPv4 address"
  104. with self.assertAddressError(re.escape(msg)):
  105. self.factory(-1)
  106. def test_large_ints_rejected(self):
  107. msg = "%d (>= 2**32) is not permitted as an IPv4 address"
  108. with self.assertAddressError(re.escape(msg % 2**32)):
  109. self.factory(2**32)
  110. def test_bad_packed_length(self):
  111. def assertBadLength(length):
  112. addr = bytes(length)
  113. msg = "%r (len %d != 4) is not permitted as an IPv4 address"
  114. with self.assertAddressError(re.escape(msg % (addr, length))):
  115. self.factory(addr)
  116. assertBadLength(3)
  117. assertBadLength(5)
  118. class CommonTestMixin_v6(CommonTestMixin):
  119. def test_leading_zeros(self):
  120. self.assertInstancesEqual("0000::0000", "::")
  121. self.assertInstancesEqual("000::c0a8:0001", "::c0a8:1")
  122. def test_int(self):
  123. self.assertInstancesEqual(0, "::")
  124. self.assertInstancesEqual(3232235521, "::c0a8:1")
  125. def test_packed(self):
  126. addr = bytes(12) + bytes.fromhex(u"00000000")
  127. self.assertInstancesEqual(addr, "::")
  128. addr = bytes(12) + bytes.fromhex(u"c0a80001")
  129. self.assertInstancesEqual(addr, "::c0a8:1")
  130. addr = bytes.fromhex(u"c0a80001") + bytes(12)
  131. self.assertInstancesEqual(addr, "c0a8:1::")
  132. def test_negative_ints_rejected(self):
  133. msg = "-1 (< 0) is not permitted as an IPv6 address"
  134. with self.assertAddressError(re.escape(msg)):
  135. self.factory(-1)
  136. def test_large_ints_rejected(self):
  137. msg = "%d (>= 2**128) is not permitted as an IPv6 address"
  138. with self.assertAddressError(re.escape(msg % 2**128)):
  139. self.factory(2**128)
  140. def test_bad_packed_length(self):
  141. def assertBadLength(length):
  142. addr = bytes(length)
  143. msg = "%r (len %d != 16) is not permitted as an IPv6 address"
  144. with self.assertAddressError(re.escape(msg % (addr, length))):
  145. self.factory(addr)
  146. self.factory(addr)
  147. assertBadLength(15)
  148. assertBadLength(17)
  149. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  150. class AddressTestCase_v4(BaseTestCase, CommonTestMixin_v4):
  151. factory = ipaddress.IPv4Address
  152. def test_network_passed_as_address(self):
  153. addr = "127.0.0.1/24"
  154. with self.assertAddressError("Unexpected '/' in %r", addr):
  155. ipaddress.IPv4Address(addr)
  156. def test_bad_address_split(self):
  157. def assertBadSplit(addr):
  158. with self.assertAddressError("Expected 4 octets in %r", addr):
  159. ipaddress.IPv4Address(addr)
  160. assertBadSplit("127.0.1")
  161. assertBadSplit("42.42.42.42.42")
  162. assertBadSplit("42.42.42")
  163. assertBadSplit("42.42")
  164. assertBadSplit("42")
  165. assertBadSplit("42..42.42.42")
  166. assertBadSplit("42.42.42.42.")
  167. assertBadSplit("42.42.42.42...")
  168. assertBadSplit(".42.42.42.42")
  169. assertBadSplit("...42.42.42.42")
  170. assertBadSplit("016.016.016")
  171. assertBadSplit("016.016")
  172. assertBadSplit("016")
  173. assertBadSplit("000")
  174. assertBadSplit("0x0a.0x0a.0x0a")
  175. assertBadSplit("0x0a.0x0a")
  176. assertBadSplit("0x0a")
  177. assertBadSplit(".")
  178. assertBadSplit("bogus")
  179. assertBadSplit("bogus.com")
  180. assertBadSplit("1000")
  181. assertBadSplit("1000000000000000")
  182. assertBadSplit("192.168.0.1.com")
  183. def test_empty_octet(self):
  184. def assertBadOctet(addr):
  185. with self.assertAddressError("Empty octet not permitted in %r",
  186. addr):
  187. ipaddress.IPv4Address(addr)
  188. assertBadOctet("42..42.42")
  189. assertBadOctet("...")
  190. def test_invalid_characters(self):
  191. def assertBadOctet(addr, octet):
  192. msg = "Only decimal digits permitted in %r in %r" % (octet, addr)
  193. with self.assertAddressError(re.escape(msg)):
  194. ipaddress.IPv4Address(addr)
  195. assertBadOctet("0x0a.0x0a.0x0a.0x0a", "0x0a")
  196. assertBadOctet("0xa.0x0a.0x0a.0x0a", "0xa")
  197. assertBadOctet("42.42.42.-0", "-0")
  198. assertBadOctet("42.42.42.+0", "+0")
  199. assertBadOctet("42.42.42.-42", "-42")
  200. assertBadOctet("+1.+2.+3.4", "+1")
  201. assertBadOctet("1.2.3.4e0", "4e0")
  202. assertBadOctet("1.2.3.4::", "4::")
  203. assertBadOctet("1.a.2.3", "a")
  204. def test_octal_decimal_ambiguity(self):
  205. def assertBadOctet(addr, octet):
  206. msg = "Ambiguous (octal/decimal) value in %r not permitted in %r"
  207. with self.assertAddressError(re.escape(msg % (octet, addr))):
  208. ipaddress.IPv4Address(addr)
  209. assertBadOctet("016.016.016.016", "016")
  210. assertBadOctet("001.000.008.016", "008")
  211. def test_octet_length(self):
  212. def assertBadOctet(addr, octet):
  213. msg = "At most 3 characters permitted in %r in %r"
  214. with self.assertAddressError(re.escape(msg % (octet, addr))):
  215. ipaddress.IPv4Address(addr)
  216. assertBadOctet("0000.000.000.000", "0000")
  217. assertBadOctet("12345.67899.-54321.-98765", "12345")
  218. def test_octet_limit(self):
  219. def assertBadOctet(addr, octet):
  220. msg = "Octet %d (> 255) not permitted in %r" % (octet, addr)
  221. with self.assertAddressError(re.escape(msg)):
  222. ipaddress.IPv4Address(addr)
  223. assertBadOctet("257.0.0.0", 257)
  224. assertBadOctet("192.168.0.999", 999)
  225. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  226. class AddressTestCase_v6(BaseTestCase, CommonTestMixin_v6):
  227. factory = ipaddress.IPv6Address
  228. def test_network_passed_as_address(self):
  229. addr = "::1/24"
  230. with self.assertAddressError("Unexpected '/' in %r", addr):
  231. ipaddress.IPv6Address(addr)
  232. def test_bad_address_split_v6_not_enough_parts(self):
  233. def assertBadSplit(addr):
  234. msg = "At least 3 parts expected in %r"
  235. with self.assertAddressError(msg, addr):
  236. ipaddress.IPv6Address(addr)
  237. assertBadSplit(":")
  238. assertBadSplit(":1")
  239. assertBadSplit("FEDC:9878")
  240. def test_bad_address_split_v6_too_many_colons(self):
  241. def assertBadSplit(addr):
  242. msg = "At most 8 colons permitted in %r"
  243. with self.assertAddressError(msg, addr):
  244. ipaddress.IPv6Address(addr)
  245. assertBadSplit("9:8:7:6:5:4:3::2:1")
  246. assertBadSplit("10:9:8:7:6:5:4:3:2:1")
  247. assertBadSplit("::8:7:6:5:4:3:2:1")
  248. assertBadSplit("8:7:6:5:4:3:2:1::")
  249. # A trailing IPv4 address is two parts
  250. assertBadSplit("10:9:8:7:6:5:4:3:42.42.42.42")
  251. def test_bad_address_split_v6_too_many_parts(self):
  252. def assertBadSplit(addr):
  253. msg = "Exactly 8 parts expected without '::' in %r"
  254. with self.assertAddressError(msg, addr):
  255. ipaddress.IPv6Address(addr)
  256. assertBadSplit("3ffe:0:0:0:0:0:0:0:1")
  257. assertBadSplit("9:8:7:6:5:4:3:2:1")
  258. assertBadSplit("7:6:5:4:3:2:1")
  259. # A trailing IPv4 address is two parts
  260. assertBadSplit("9:8:7:6:5:4:3:42.42.42.42")
  261. assertBadSplit("7:6:5:4:3:42.42.42.42")
  262. def test_bad_address_split_v6_too_many_parts_with_double_colon(self):
  263. def assertBadSplit(addr):
  264. msg = "Expected at most 7 other parts with '::' in %r"
  265. with self.assertAddressError(msg, addr):
  266. ipaddress.IPv6Address(addr)
  267. assertBadSplit("1:2:3:4::5:6:7:8")
  268. def test_bad_address_split_v6_repeated_double_colon(self):
  269. def assertBadSplit(addr):
  270. msg = "At most one '::' permitted in %r"
  271. with self.assertAddressError(msg, addr):
  272. ipaddress.IPv6Address(addr)
  273. assertBadSplit("3ffe::1::1")
  274. assertBadSplit("1::2::3::4:5")
  275. assertBadSplit("2001::db:::1")
  276. assertBadSplit("3ffe::1::")
  277. assertBadSplit("::3ffe::1")
  278. assertBadSplit(":3ffe::1::1")
  279. assertBadSplit("3ffe::1::1:")
  280. assertBadSplit(":3ffe::1::1:")
  281. assertBadSplit(":::")
  282. assertBadSplit('2001:db8:::1')
  283. def test_bad_address_split_v6_leading_colon(self):
  284. def assertBadSplit(addr):
  285. msg = "Leading ':' only permitted as part of '::' in %r"
  286. with self.assertAddressError(msg, addr):
  287. ipaddress.IPv6Address(addr)
  288. assertBadSplit(":2001:db8::1")
  289. assertBadSplit(":1:2:3:4:5:6:7")
  290. assertBadSplit(":1:2:3:4:5:6:")
  291. assertBadSplit(":6:5:4:3:2:1::")
  292. def test_bad_address_split_v6_trailing_colon(self):
  293. def assertBadSplit(addr):
  294. msg = "Trailing ':' only permitted as part of '::' in %r"
  295. with self.assertAddressError(msg, addr):
  296. ipaddress.IPv6Address(addr)
  297. assertBadSplit("2001:db8::1:")
  298. assertBadSplit("1:2:3:4:5:6:7:")
  299. assertBadSplit("::1.2.3.4:")
  300. assertBadSplit("::7:6:5:4:3:2:")
  301. def test_bad_v4_part_in(self):
  302. def assertBadAddressPart(addr, v4_error):
  303. with self.assertAddressError("%s in %r", v4_error, addr):
  304. ipaddress.IPv6Address(addr)
  305. assertBadAddressPart("3ffe::1.net", "Expected 4 octets in '1.net'")
  306. assertBadAddressPart("3ffe::127.0.1",
  307. "Expected 4 octets in '127.0.1'")
  308. assertBadAddressPart("::1.2.3",
  309. "Expected 4 octets in '1.2.3'")
  310. assertBadAddressPart("::1.2.3.4.5",
  311. "Expected 4 octets in '1.2.3.4.5'")
  312. assertBadAddressPart("3ffe::1.1.1.net",
  313. "Only decimal digits permitted in 'net' "
  314. "in '1.1.1.net'")
  315. def test_invalid_characters(self):
  316. def assertBadPart(addr, part):
  317. msg = "Only hex digits permitted in %r in %r" % (part, addr)
  318. with self.assertAddressError(re.escape(msg)):
  319. ipaddress.IPv6Address(addr)
  320. assertBadPart("3ffe::goog", "goog")
  321. assertBadPart("3ffe::-0", "-0")
  322. assertBadPart("3ffe::+0", "+0")
  323. assertBadPart("3ffe::-1", "-1")
  324. assertBadPart("1.2.3.4::", "1.2.3.4")
  325. assertBadPart('1234:axy::b', "axy")
  326. def test_part_length(self):
  327. def assertBadPart(addr, part):
  328. msg = "At most 4 characters permitted in %r in %r"
  329. with self.assertAddressError(msg, part, addr):
  330. ipaddress.IPv6Address(addr)
  331. assertBadPart("::00000", "00000")
  332. assertBadPart("3ffe::10000", "10000")
  333. assertBadPart("02001:db8::", "02001")
  334. assertBadPart('2001:888888::1', "888888")
  335. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  336. class NetmaskTestMixin_v4(CommonTestMixin_v4):
  337. """Input validation on interfaces and networks is very similar"""
  338. def test_split_netmask(self):
  339. addr = "1.2.3.4/32/24"
  340. with self.assertAddressError("Only one '/' permitted in %r" % addr):
  341. self.factory(addr)
  342. def test_address_errors(self):
  343. def assertBadAddress(addr, details):
  344. with self.assertAddressError(details):
  345. self.factory(addr)
  346. assertBadAddress("/", "Address cannot be empty")
  347. assertBadAddress("/8", "Address cannot be empty")
  348. assertBadAddress("bogus", "Expected 4 octets")
  349. assertBadAddress("google.com", "Expected 4 octets")
  350. assertBadAddress("10/8", "Expected 4 octets")
  351. assertBadAddress("::1.2.3.4", "Only decimal digits")
  352. assertBadAddress("1.2.3.256", re.escape("256 (> 255)"))
  353. def test_valid_netmask(self):
  354. self.assertEqual(str(self.factory('192.0.2.0/255.255.255.0')),
  355. '192.0.2.0/24')
  356. for i in range(0, 33):
  357. # Generate and re-parse the CIDR format (trivial).
  358. net_str = '0.0.0.0/%d' % i
  359. net = self.factory(net_str)
  360. self.assertEqual(str(net), net_str)
  361. # Generate and re-parse the expanded netmask.
  362. self.assertEqual(
  363. str(self.factory('0.0.0.0/%s' % net.netmask)), net_str)
  364. # Zero prefix is treated as decimal.
  365. self.assertEqual(str(self.factory('0.0.0.0/0%d' % i)), net_str)
  366. # Generate and re-parse the expanded hostmask. The ambiguous
  367. # cases (/0 and /32) are treated as netmasks.
  368. if i in (32, 0):
  369. net_str = '0.0.0.0/%d' % (32 - i)
  370. self.assertEqual(
  371. str(self.factory('0.0.0.0/%s' % net.hostmask)), net_str)
  372. def test_netmask_errors(self):
  373. def assertBadNetmask(addr, netmask):
  374. msg = "%r is not a valid netmask" % netmask
  375. with self.assertNetmaskError(re.escape(msg)):
  376. self.factory("%s/%s" % (addr, netmask))
  377. assertBadNetmask("1.2.3.4", "")
  378. assertBadNetmask("1.2.3.4", "-1")
  379. assertBadNetmask("1.2.3.4", "+1")
  380. assertBadNetmask("1.2.3.4", " 1 ")
  381. assertBadNetmask("1.2.3.4", "0x1")
  382. assertBadNetmask("1.2.3.4", "33")
  383. assertBadNetmask("1.2.3.4", "254.254.255.256")
  384. assertBadNetmask("1.2.3.4", "1.a.2.3")
  385. assertBadNetmask("1.1.1.1", "254.xyz.2.3")
  386. assertBadNetmask("1.1.1.1", "240.255.0.0")
  387. assertBadNetmask("1.1.1.1", "255.254.128.0")
  388. assertBadNetmask("1.1.1.1", "0.1.127.255")
  389. assertBadNetmask("1.1.1.1", "pudding")
  390. assertBadNetmask("1.1.1.1", "::")
  391. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  392. class InterfaceTestCase_v4(BaseTestCase, NetmaskTestMixin_v4):
  393. factory = ipaddress.IPv4Interface
  394. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  395. class NetworkTestCase_v4(BaseTestCase, NetmaskTestMixin_v4):
  396. factory = ipaddress.IPv4Network
  397. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  398. class NetmaskTestMixin_v6(CommonTestMixin_v6):
  399. """Input validation on interfaces and networks is very similar"""
  400. def test_split_netmask(self):
  401. addr = "cafe:cafe::/128/190"
  402. with self.assertAddressError("Only one '/' permitted in %r" % addr):
  403. self.factory(addr)
  404. def test_address_errors(self):
  405. def assertBadAddress(addr, details):
  406. with self.assertAddressError(details):
  407. self.factory(addr)
  408. assertBadAddress("/", "Address cannot be empty")
  409. assertBadAddress("/8", "Address cannot be empty")
  410. assertBadAddress("google.com", "At least 3 parts")
  411. assertBadAddress("1.2.3.4", "At least 3 parts")
  412. assertBadAddress("10/8", "At least 3 parts")
  413. assertBadAddress("1234:axy::b", "Only hex digits")
  414. def test_valid_netmask(self):
  415. # We only support CIDR for IPv6, because expanded netmasks are not
  416. # standard notation.
  417. self.assertEqual(str(self.factory('2001:db8::/32')), '2001:db8::/32')
  418. for i in range(0, 129):
  419. # Generate and re-parse the CIDR format (trivial).
  420. net_str = '::/%d' % i
  421. self.assertEqual(str(self.factory(net_str)), net_str)
  422. # Zero prefix is treated as decimal.
  423. self.assertEqual(str(self.factory('::/0%d' % i)), net_str)
  424. def test_netmask_errors(self):
  425. def assertBadNetmask(addr, netmask):
  426. msg = "%r is not a valid netmask" % netmask
  427. with self.assertNetmaskError(re.escape(msg)):
  428. self.factory("%s/%s" % (addr, netmask))
  429. assertBadNetmask("::1", "")
  430. assertBadNetmask("::1", "::1")
  431. assertBadNetmask("::1", "1::")
  432. assertBadNetmask("::1", "-1")
  433. assertBadNetmask("::1", "+1")
  434. assertBadNetmask("::1", " 1 ")
  435. assertBadNetmask("::1", "0x1")
  436. assertBadNetmask("::1", "129")
  437. assertBadNetmask("::1", "1.2.3.4")
  438. assertBadNetmask("::1", "pudding")
  439. assertBadNetmask("::", "::")
  440. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  441. class InterfaceTestCase_v6(BaseTestCase, NetmaskTestMixin_v6):
  442. factory = ipaddress.IPv6Interface
  443. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  444. class NetworkTestCase_v6(BaseTestCase, NetmaskTestMixin_v6):
  445. factory = ipaddress.IPv6Network
  446. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  447. class FactoryFunctionErrors(BaseTestCase):
  448. def assertFactoryError(self, factory, kind):
  449. """Ensure a clean ValueError with the expected message"""
  450. addr = "camelot"
  451. msg = '%r does not appear to be an IPv4 or IPv6 %s'
  452. with self.assertCleanError(ValueError, msg, addr, kind):
  453. factory(addr)
  454. def test_ip_address(self):
  455. self.assertFactoryError(ipaddress.ip_address, "address")
  456. def test_ip_interface(self):
  457. self.assertFactoryError(ipaddress.ip_interface, "interface")
  458. def test_ip_network(self):
  459. self.assertFactoryError(ipaddress.ip_network, "network")
  460. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  461. class ComparisonTests(TestCase):
  462. v4addr = ipaddress.IPv4Address(1)
  463. v4net = ipaddress.IPv4Network(1)
  464. v4intf = ipaddress.IPv4Interface(1)
  465. v6addr = ipaddress.IPv6Address(1)
  466. v6net = ipaddress.IPv6Network(1)
  467. v6intf = ipaddress.IPv6Interface(1)
  468. v4_addresses = [v4addr, v4intf]
  469. v4_objects = v4_addresses + [v4net]
  470. v6_addresses = [v6addr, v6intf]
  471. v6_objects = v6_addresses + [v6net]
  472. objects = v4_objects + v6_objects
  473. def test_foreign_type_equality(self):
  474. # __eq__ should never raise TypeError directly
  475. other = object()
  476. for obj in self.objects:
  477. self.assertNotEqual(obj, other)
  478. self.assertFalse(obj == other)
  479. self.assertEqual(obj.__eq__(other), NotImplemented)
  480. self.assertEqual(obj.__ne__(other), NotImplemented)
  481. def test_mixed_type_equality(self):
  482. # Ensure none of the internal objects accidentally
  483. # expose the right set of attributes to become "equal"
  484. for lhs in self.objects:
  485. for rhs in self.objects:
  486. if lhs is rhs:
  487. continue
  488. self.assertNotEqual(lhs, rhs)
  489. def test_containment(self):
  490. for obj in self.v4_addresses:
  491. self.assertIn(obj, self.v4net)
  492. for obj in self.v6_addresses:
  493. self.assertIn(obj, self.v6net)
  494. for obj in self.v4_objects + [self.v6net]:
  495. self.assertNotIn(obj, self.v6net)
  496. for obj in self.v6_objects + [self.v4net]:
  497. self.assertNotIn(obj, self.v4net)
  498. def test_mixed_type_ordering(self):
  499. for lhs in self.objects:
  500. for rhs in self.objects:
  501. if isinstance(lhs, type(rhs)) or isinstance(rhs, type(lhs)):
  502. continue
  503. self.assertRaises(TypeError, lambda: lhs < rhs)
  504. self.assertRaises(TypeError, lambda: lhs > rhs)
  505. self.assertRaises(TypeError, lambda: lhs <= rhs)
  506. self.assertRaises(TypeError, lambda: lhs >= rhs)
  507. def test_mixed_type_key(self):
  508. # with get_mixed_type_key, you can sort addresses and network.
  509. v4_ordered = [self.v4addr, self.v4net, self.v4intf]
  510. v6_ordered = [self.v6addr, self.v6net, self.v6intf]
  511. self.assertEqual(v4_ordered,
  512. sorted(self.v4_objects,
  513. key=ipaddress.get_mixed_type_key))
  514. self.assertEqual(v6_ordered,
  515. sorted(self.v6_objects,
  516. key=ipaddress.get_mixed_type_key))
  517. self.assertEqual(v4_ordered + v6_ordered,
  518. sorted(self.objects,
  519. key=ipaddress.get_mixed_type_key))
  520. self.assertEqual(NotImplemented, ipaddress.get_mixed_type_key(object))
  521. def test_incompatible_versions(self):
  522. # These should always raise TypeError
  523. v4addr = ipaddress.ip_address('1.1.1.1')
  524. v4net = ipaddress.ip_network('1.1.1.1')
  525. v6addr = ipaddress.ip_address('::1')
  526. v6net = ipaddress.ip_address('::1')
  527. self.assertRaises(TypeError, v4addr.__lt__, v6addr)
  528. self.assertRaises(TypeError, v4addr.__gt__, v6addr)
  529. self.assertRaises(TypeError, v4net.__lt__, v6net)
  530. self.assertRaises(TypeError, v4net.__gt__, v6net)
  531. self.assertRaises(TypeError, v6addr.__lt__, v4addr)
  532. self.assertRaises(TypeError, v6addr.__gt__, v4addr)
  533. self.assertRaises(TypeError, v6net.__lt__, v4net)
  534. self.assertRaises(TypeError, v6net.__gt__, v4net)
  535. @skipIf(sys.version_info > (3,), 'These are tested by the python test suite under Py3')
  536. class IpaddrUnitTest(TestCase):
  537. def setUp(self):
  538. self.ipv4_address = ipaddress.IPv4Address('1.2.3.4')
  539. self.ipv4_interface = ipaddress.IPv4Interface('1.2.3.4/24')
  540. self.ipv4_network = ipaddress.IPv4Network('1.2.3.0/24')
  541. #self.ipv4_hostmask = ipaddress.IPv4Interface('10.0.0.1/0.255.255.255')
  542. self.ipv6_address = ipaddress.IPv6Interface(
  543. '2001:658:22a:cafe:200:0:0:1')
  544. self.ipv6_interface = ipaddress.IPv6Interface(
  545. '2001:658:22a:cafe:200:0:0:1/64')
  546. self.ipv6_network = ipaddress.IPv6Network('2001:658:22a:cafe::/64')
  547. def tearDown(self):
  548. for attrname in ('ipv4_network', 'ipv4_interface', 'ipv4_address',
  549. 'ipv6_network', 'ipv6_interface', 'ipv6_address'):
  550. try:
  551. delattr(self, attrname)
  552. except AttributeError:
  553. continue
  554. def testRepr(self):
  555. self.assertEqual("IPv4Interface('1.2.3.4/32')",
  556. repr(ipaddress.IPv4Interface('1.2.3.4')))
  557. self.assertEqual("IPv6Interface('::1/128')",
  558. repr(ipaddress.IPv6Interface('::1')))
  559. # issue57
  560. def testAddressIntMath(self):
  561. self.assertEqual(ipaddress.IPv4Address('1.1.1.1') + 255,
  562. ipaddress.IPv4Address('1.1.2.0'))
  563. self.assertEqual(ipaddress.IPv4Address('1.1.1.1') - 256,
  564. ipaddress.IPv4Address('1.1.0.1'))
  565. self.assertEqual(ipaddress.IPv6Address('::1') + (2**16 - 2),
  566. ipaddress.IPv6Address('::ffff'))
  567. self.assertEqual(ipaddress.IPv6Address('::ffff') - (2**16 - 2),
  568. ipaddress.IPv6Address('::1'))
  569. def testInvalidIntToBytes(self):
  570. self.assertRaises(ValueError, ipaddress.v4_int_to_packed, -1)
  571. self.assertRaises(ValueError, ipaddress.v4_int_to_packed,
  572. 2 ** ipaddress.IPV4LENGTH)
  573. self.assertRaises(ValueError, ipaddress.v6_int_to_packed, -1)
  574. self.assertRaises(ValueError, ipaddress.v6_int_to_packed,
  575. 2 ** ipaddress.IPV6LENGTH)
  576. def testInternals(self):
  577. first, last = ipaddress._find_address_range([
  578. ipaddress.IPv4Address('10.10.10.10'),
  579. ipaddress.IPv4Address('10.10.10.12')])
  580. self.assertEqual(first, last)
  581. self.assertEqual(128, ipaddress._count_righthand_zero_bits(0, 128))
  582. self.assertEqual("IPv4Network('1.2.3.0/24')", repr(self.ipv4_network))
  583. def testMissingAddressVersion(self):
  584. class Broken(ipaddress._BaseAddress):
  585. pass
  586. broken = Broken('127.0.0.1')
  587. with self.assertRaisesRegex(NotImplementedError, "Broken.*version"):
  588. broken.version
  589. def testMissingNetworkVersion(self):
  590. class Broken(ipaddress._BaseNetwork):
  591. pass
  592. broken = Broken('127.0.0.1')
  593. with self.assertRaisesRegex(NotImplementedError, "Broken.*version"):
  594. broken.version
  595. def testMissingAddressClass(self):
  596. class Broken(ipaddress._BaseNetwork):
  597. pass
  598. broken = Broken('127.0.0.1')
  599. with self.assertRaisesRegex(NotImplementedError, "Broken.*address"):
  600. broken._address_class
  601. def testGetNetwork(self):
  602. self.assertEqual(int(self.ipv4_network.network_address), 16909056)
  603. self.assertEqual(str(self.ipv4_network.network_address), '1.2.3.0')
  604. self.assertEqual(int(self.ipv6_network.network_address),
  605. 42540616829182469433403647294022090752)
  606. self.assertEqual(str(self.ipv6_network.network_address),
  607. '2001:658:22a:cafe::')
  608. self.assertEqual(str(self.ipv6_network.hostmask),
  609. '::ffff:ffff:ffff:ffff')
  610. def testIpFromInt(self):
  611. self.assertEqual(self.ipv4_interface._ip,
  612. ipaddress.IPv4Interface(16909060)._ip)
  613. ipv4 = ipaddress.ip_network('1.2.3.4')
  614. ipv6 = ipaddress.ip_network('2001:658:22a:cafe:200:0:0:1')
  615. self.assertEqual(ipv4, ipaddress.ip_network(int(ipv4.network_address)))
  616. self.assertEqual(ipv6, ipaddress.ip_network(int(ipv6.network_address)))
  617. v6_int = 42540616829182469433547762482097946625
  618. self.assertEqual(self.ipv6_interface._ip,
  619. ipaddress.IPv6Interface(v6_int)._ip)
  620. self.assertEqual(ipaddress.ip_network(self.ipv4_address._ip).version,
  621. 4)
  622. self.assertEqual(ipaddress.ip_network(self.ipv6_address._ip).version,
  623. 6)
  624. def testIpFromPacked(self):
  625. address = ipaddress.ip_address
  626. self.assertEqual(self.ipv4_interface._ip,
  627. ipaddress.ip_interface(bytearray(b'\x01\x02\x03\x04'))._ip)
  628. self.assertEqual(address('255.254.253.252'),
  629. address(bytearray(b'\xff\xfe\xfd\xfc')))
  630. self.assertEqual(self.ipv6_interface.ip,
  631. ipaddress.ip_interface(
  632. bytearray(b'\x20\x01\x06\x58\x02\x2a\xca\xfe'
  633. b'\x02\x00\x00\x00\x00\x00\x00\x01')).ip)
  634. self.assertEqual(address('ffff:2:3:4:ffff::'),
  635. address(bytearray(b'\xff\xff\x00\x02\x00\x03\x00\x04') +
  636. bytearray(b'\xff\xff') + bytearray(b'\x00') * 6))
  637. self.assertEqual(address('::'),
  638. address(bytearray(b'\x00') * 16))
  639. def testGetIp(self):
  640. self.assertEqual(int(self.ipv4_interface.ip), 16909060)
  641. self.assertEqual(str(self.ipv4_interface.ip), '1.2.3.4')
  642. self.assertEqual(int(self.ipv6_interface.ip),
  643. 42540616829182469433547762482097946625)
  644. self.assertEqual(str(self.ipv6_interface.ip),
  645. '2001:658:22a:cafe:200::1')
  646. def testGetNetmask(self):
  647. self.assertEqual(int(self.ipv4_network.netmask), 4294967040)
  648. self.assertEqual(str(self.ipv4_network.netmask), '255.255.255.0')
  649. self.assertEqual(int(self.ipv6_network.netmask),
  650. 340282366920938463444927863358058659840)
  651. self.assertEqual(self.ipv6_network.prefixlen, 64)
  652. def testZeroNetmask(self):
  653. ipv4_zero_netmask = ipaddress.IPv4Interface('1.2.3.4/0')
  654. self.assertEqual(int(ipv4_zero_netmask.network.netmask), 0)
  655. self.assertEqual(ipv4_zero_netmask._prefix_from_prefix_string('0'), 0)
  656. self.assertTrue(ipv4_zero_netmask._is_valid_netmask('0'))
  657. self.assertTrue(ipv4_zero_netmask._is_valid_netmask('0.0.0.0'))
  658. self.assertFalse(ipv4_zero_netmask._is_valid_netmask('invalid'))
  659. ipv6_zero_netmask = ipaddress.IPv6Interface('::1/0')
  660. self.assertEqual(int(ipv6_zero_netmask.network.netmask), 0)
  661. self.assertEqual(ipv6_zero_netmask._prefix_from_prefix_string('0'), 0)
  662. def testIPv4NetAndHostmasks(self):
  663. net = self.ipv4_network
  664. self.assertFalse(net._is_valid_netmask('invalid'))
  665. self.assertTrue(net._is_valid_netmask('128.128.128.128'))
  666. self.assertFalse(net._is_valid_netmask('128.128.128.127'))
  667. self.assertFalse(net._is_valid_netmask('128.128.128.255'))
  668. self.assertTrue(net._is_valid_netmask('255.128.128.128'))
  669. self.assertFalse(net._is_hostmask('invalid'))
  670. self.assertTrue(net._is_hostmask('128.255.255.255'))
  671. self.assertFalse(net._is_hostmask('255.255.255.255'))
  672. self.assertFalse(net._is_hostmask('1.2.3.4'))
  673. net = ipaddress.IPv4Network('127.0.0.0/0.0.0.255')
  674. self.assertEqual(net.prefixlen, 24)
  675. def testGetBroadcast(self):
  676. self.assertEqual(int(self.ipv4_network.broadcast_address), 16909311)
  677. self.assertEqual(str(self.ipv4_network.broadcast_address), '1.2.3.255')
  678. self.assertEqual(int(self.ipv6_network.broadcast_address),
  679. 42540616829182469451850391367731642367)
  680. self.assertEqual(str(self.ipv6_network.broadcast_address),
  681. '2001:658:22a:cafe:ffff:ffff:ffff:ffff')
  682. def testGetPrefixlen(self):
  683. self.assertEqual(self.ipv4_interface.network.prefixlen, 24)
  684. self.assertEqual(self.ipv6_interface.network.prefixlen, 64)
  685. def testGetSupernet(self):
  686. self.assertEqual(self.ipv4_network.supernet().prefixlen, 23)
  687. self.assertEqual(str(self.ipv4_network.supernet().network_address),
  688. '1.2.2.0')
  689. self.assertEqual(
  690. ipaddress.IPv4Interface('0.0.0.0/0').network.supernet(),
  691. ipaddress.IPv4Network('0.0.0.0/0'))
  692. self.assertEqual(self.ipv6_network.supernet().prefixlen, 63)
  693. self.assertEqual(str(self.ipv6_network.supernet().network_address),
  694. '2001:658:22a:cafe::')
  695. self.assertEqual(ipaddress.IPv6Interface('::0/0').network.supernet(),
  696. ipaddress.IPv6Network('::0/0'))
  697. def testGetSupernet3(self):
  698. self.assertEqual(self.ipv4_network.supernet(3).prefixlen, 21)
  699. self.assertEqual(str(self.ipv4_network.supernet(3).network_address),
  700. '1.2.0.0')
  701. self.assertEqual(self.ipv6_network.supernet(3).prefixlen, 61)
  702. self.assertEqual(str(self.ipv6_network.supernet(3).network_address),
  703. '2001:658:22a:caf8::')
  704. def testGetSupernet4(self):
  705. self.assertRaises(ValueError, self.ipv4_network.supernet,
  706. prefixlen_diff=2, new_prefix=1)
  707. self.assertRaises(ValueError, self.ipv4_network.supernet,
  708. new_prefix=25)
  709. self.assertEqual(self.ipv4_network.supernet(prefixlen_diff=2),
  710. self.ipv4_network.supernet(new_prefix=22))
  711. self.assertRaises(ValueError, self.ipv6_network.supernet,
  712. prefixlen_diff=2, new_prefix=1)
  713. self.assertRaises(ValueError, self.ipv6_network.supernet,
  714. new_prefix=65)
  715. self.assertEqual(self.ipv6_network.supernet(prefixlen_diff=2),
  716. self.ipv6_network.supernet(new_prefix=62))
  717. def testHosts(self):
  718. hosts = list(self.ipv4_network.hosts())
  719. self.assertEqual(254, len(hosts))
  720. self.assertEqual(ipaddress.IPv4Address('1.2.3.1'), hosts[0])
  721. self.assertEqual(ipaddress.IPv4Address('1.2.3.254'), hosts[-1])
  722. # special case where only 1 bit is left for address
  723. self.assertEqual([ipaddress.IPv4Address('2.0.0.0'),
  724. ipaddress.IPv4Address('2.0.0.1')],
  725. list(ipaddress.ip_network('2.0.0.0/31').hosts()))
  726. def testFancySubnetting(self):
  727. self.assertEqual(sorted(self.ipv4_network.subnets(prefixlen_diff=3)),
  728. sorted(self.ipv4_network.subnets(new_prefix=27)))
  729. self.assertRaises(ValueError, list,
  730. self.ipv4_network.subnets(new_prefix=23))
  731. self.assertRaises(ValueError, list,
  732. self.ipv4_network.subnets(prefixlen_diff=3,
  733. new_prefix=27))
  734. self.assertEqual(sorted(self.ipv6_network.subnets(prefixlen_diff=4)),
  735. sorted(self.ipv6_network.subnets(new_prefix=68)))
  736. self.assertRaises(ValueError, list,
  737. self.ipv6_network.subnets(new_prefix=63))
  738. self.assertRaises(ValueError, list,
  739. self.ipv6_network.subnets(prefixlen_diff=4,
  740. new_prefix=68))
  741. def testGetSubnets(self):
  742. self.assertEqual(list(self.ipv4_network.subnets())[0].prefixlen, 25)
  743. self.assertEqual(str(list(
  744. self.ipv4_network.subnets())[0].network_address),
  745. '1.2.3.0')
  746. self.assertEqual(str(list(
  747. self.ipv4_network.subnets())[1].network_address),
  748. '1.2.3.128')
  749. self.assertEqual(list(self.ipv6_network.subnets())[0].prefixlen, 65)
  750. def testGetSubnetForSingle32(self):
  751. ip = ipaddress.IPv4Network('1.2.3.4/32')
  752. subnets1 = [str(x) for x in ip.subnets()]
  753. subnets2 = [str(x) for x in ip.subnets(2)]
  754. self.assertEqual(subnets1, ['1.2.3.4/32'])
  755. self.assertEqual(subnets1, subnets2)
  756. def testGetSubnetForSingle128(self):
  757. ip = ipaddress.IPv6Network('::1/128')
  758. subnets1 = [str(x) for x in ip.subnets()]
  759. subnets2 = [str(x) for x in ip.subnets(2)]
  760. self.assertEqual(subnets1, ['::1/128'])
  761. self.assertEqual(subnets1, subnets2)
  762. def testSubnet2(self):
  763. ips = [str(x) for x in self.ipv4_network.subnets(2)]
  764. self.assertEqual(
  765. ips,
  766. ['1.2.3.0/26', '1.2.3.64/26', '1.2.3.128/26', '1.2.3.192/26'])
  767. ipsv6 = [str(x) for x in self.ipv6_network.subnets(2)]
  768. self.assertEqual(
  769. ipsv6,
  770. ['2001:658:22a:cafe::/66',
  771. '2001:658:22a:cafe:4000::/66',
  772. '2001:658:22a:cafe:8000::/66',
  773. '2001:658:22a:cafe:c000::/66'])
  774. def testSubnetFailsForLargeCidrDiff(self):
  775. self.assertRaises(ValueError, list,
  776. self.ipv4_interface.network.subnets(9))
  777. self.assertRaises(ValueError, list,
  778. self.ipv4_network.subnets(9))
  779. self.assertRaises(ValueError, list,
  780. self.ipv6_interface.network.subnets(65))
  781. self.assertRaises(ValueError, list,
  782. self.ipv6_network.subnets(65))
  783. def testSupernetFailsForLargeCidrDiff(self):
  784. self.assertRaises(ValueError,
  785. self.ipv4_interface.network.supernet, 25)
  786. self.assertRaises(ValueError,
  787. self.ipv6_interface.network.supernet, 65)
  788. def testSubnetFailsForNegativeCidrDiff(self):
  789. self.assertRaises(ValueError, list,
  790. self.ipv4_interface.network.subnets(-1))
  791. self.assertRaises(ValueError, list,
  792. self.ipv4_network.subnets(-1))
  793. self.assertRaises(ValueError, list,
  794. self.ipv6_interface.network.subnets(-1))
  795. self.assertRaises(ValueError, list,
  796. self.ipv6_network.subnets(-1))
  797. def testGetNum_Addresses(self):
  798. self.assertEqual(self.ipv4_network.num_addresses, 256)
  799. self.assertEqual(list(self.ipv4_network.subnets())[0].num_addresses,
  800. 128)
  801. self.assertEqual(self.ipv4_network.supernet().num_addresses, 512)
  802. self.assertEqual(self.ipv6_network.num_addresses, 18446744073709551616)
  803. self.assertEqual(list(self.ipv6_network.subnets())[0].num_addresses,
  804. 9223372036854775808)
  805. self.assertEqual(self.ipv6_network.supernet().num_addresses,
  806. 36893488147419103232)
  807. def testContains(self):
  808. self.assertIn(ipaddress.IPv4Interface('1.2.3.128/25'),
  809. self.ipv4_network)
  810. self.assertNotIn(ipaddress.IPv4Interface('1.2.4.1/24'),
  811. self.ipv4_network)
  812. # We can test addresses and string as well.
  813. addr1 = ipaddress.IPv4Address('1.2.3.37')
  814. self.assertIn(addr1, self.ipv4_network)
  815. # issue 61, bad network comparison on like-ip'd network objects
  816. # with identical broadcast addresses.
  817. self.assertFalse(ipaddress.IPv4Network('1.1.0.0/16').__contains__(
  818. ipaddress.IPv4Network('1.0.0.0/15')))
  819. def testNth(self):
  820. self.assertEqual(str(self.ipv4_network[5]), '1.2.3.5')
  821. self.assertRaises(IndexError, self.ipv4_network.__getitem__, 256)
  822. self.assertEqual(str(self.ipv6_network[5]),
  823. '2001:658:22a:cafe::5')
  824. def testGetitem(self):
  825. # http://code.google.com/p/ipaddr-py/issues/detail?id=15
  826. addr = ipaddress.IPv4Network('172.31.255.128/255.255.255.240')
  827. self.assertEqual(28, addr.prefixlen)
  828. addr_list = list(addr)
  829. self.assertEqual('172.31.255.128', str(addr_list[0]))
  830. self.assertEqual('172.31.255.128', str(addr[0]))
  831. self.assertEqual('172.31.255.143', str(addr_list[-1]))
  832. self.assertEqual('172.31.255.143', str(addr[-1]))
  833. self.assertEqual(addr_list[-1], addr[-1])
  834. def testEqual(self):
  835. self.assertTrue(self.ipv4_interface ==
  836. ipaddress.IPv4Interface('1.2.3.4/24'))
  837. self.assertFalse(self.ipv4_interface ==
  838. ipaddress.IPv4Interface('1.2.3.4/23'))
  839. self.assertFalse(self.ipv4_interface ==
  840. ipaddress.IPv6Interface('::1.2.3.4/24'))
  841. self.assertFalse(self.ipv4_interface == '')
  842. self.assertFalse(self.ipv4_interface == [])
  843. self.assertFalse(self.ipv4_interface == 2)
  844. self.assertTrue(self.ipv6_interface ==
  845. ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/64'))
  846. self.assertFalse(self.ipv6_interface ==
  847. ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/63'))
  848. self.assertFalse(self.ipv6_interface ==
  849. ipaddress.IPv4Interface('1.2.3.4/23'))
  850. self.assertFalse(self.ipv6_interface == '')
  851. self.assertFalse(self.ipv6_interface == [])
  852. self.assertFalse(self.ipv6_interface == 2)
  853. def testNotEqual(self):
  854. self.assertFalse(self.ipv4_interface !=
  855. ipaddress.IPv4Interface('1.2.3.4/24'))
  856. self.assertTrue(self.ipv4_interface !=
  857. ipaddress.IPv4Interface('1.2.3.4/23'))
  858. self.assertTrue(self.ipv4_interface !=
  859. ipaddress.IPv6Interface('::1.2.3.4/24'))
  860. self.assertTrue(self.ipv4_interface != '')
  861. self.assertTrue(self.ipv4_interface != [])
  862. self.assertTrue(self.ipv4_interface != 2)
  863. self.assertTrue(self.ipv4_address !=
  864. ipaddress.IPv4Address('1.2.3.5'))
  865. self.assertTrue(self.ipv4_address != '')
  866. self.assertTrue(self.ipv4_address != [])
  867. self.assertTrue(self.ipv4_address != 2)
  868. self.assertFalse(self.ipv6_interface !=
  869. ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/64'))
  870. self.assertTrue(self.ipv6_interface !=
  871. ipaddress.IPv6Interface('2001:658:22a:cafe:200::1/63'))
  872. self.assertTrue(self.ipv6_interface !=
  873. ipaddress.IPv4Interface('1.2.3.4/23'))
  874. self.assertTrue(self.ipv6_interface != '')
  875. self.assertTrue(self.ipv6_interface != [])
  876. self.assertTrue(self.ipv6_interface != 2)
  877. self.assertTrue(self.ipv6_address !=
  878. ipaddress.IPv4Address('1.2.3.4'))
  879. self.assertTrue(self.ipv6_address != '')
  880. self.assertTrue(self.ipv6_address != [])
  881. self.assertTrue(self.ipv6_address != 2)
  882. def testSlash32Constructor(self):
  883. self.assertEqual(str(ipaddress.IPv4Interface(
  884. '1.2.3.4/255.255.255.255')), '1.2.3.4/32')
  885. def testSlash128Constructor(self):
  886. self.assertEqual(str(ipaddress.IPv6Interface('::1/128')),
  887. '::1/128')
  888. def testSlash0Constructor(self):
  889. self.assertEqual(str(ipaddress.IPv4Interface('1.2.3.4/0.0.0.0')),
  890. '1.2.3.4/0')
  891. def testCollapsing(self):
  892. # test only IP addresses including some duplicates
  893. ip1 = ipaddress.IPv4Address('1.1.1.0')
  894. ip2 = ipaddress.IPv4Address('1.1.1.1')
  895. ip3 = ipaddress.IPv4Address('1.1.1.2')
  896. ip4 = ipaddress.IPv4Address('1.1.1.3')
  897. ip5 = ipaddress.IPv4Address('1.1.1.4')
  898. ip6 = ipaddress.IPv4Address('1.1.1.0')
  899. # check that addreses are subsumed properly.
  900. collapsed = ipaddress.collapse_addresses(
  901. [ip1, ip2, ip3, ip4, ip5, ip6])
  902. self.assertEqual(list(collapsed),
  903. [ipaddress.IPv4Network('1.1.1.0/30'),
  904. ipaddress.IPv4Network('1.1.1.4/32')])
  905. # test a mix of IP addresses and networks including some duplicates
  906. ip1 = ipaddress.IPv4Address('1.1.1.0')
  907. ip2 = ipaddress.IPv4Address('1.1.1.1')
  908. ip3 = ipaddress.IPv4Address('1.1.1.2')
  909. ip4 = ipaddress.IPv4Address('1.1.1.3')
  910. #ip5 = ipaddress.IPv4Interface('1.1.1.4/30')
  911. #ip6 = ipaddress.IPv4Interface('1.1.1.4/30')
  912. # check that addreses are subsumed properly.
  913. collapsed = ipaddress.collapse_addresses([ip1, ip2, ip3, ip4])
  914. self.assertEqual(list(collapsed),
  915. [ipaddress.IPv4Network('1.1.1.0/30')])
  916. # test only IP networks
  917. ip1 = ipaddress.IPv4Network('1.1.0.0/24')
  918. ip2 = ipaddress.IPv4Network('1.1.1.0/24')
  919. ip3 = ipaddress.IPv4Network('1.1.2.0/24')
  920. ip4 = ipaddress.IPv4Network('1.1.3.0/24')
  921. ip5 = ipaddress.IPv4Network('1.1.4.0/24')
  922. # stored in no particular order b/c we want CollapseAddr to call
  923. # [].sort
  924. ip6 = ipaddress.IPv4Network('1.1.0.0/22')
  925. # check that addreses are subsumed properly.
  926. collapsed = ipaddress.collapse_addresses([ip1, ip2, ip3, ip4, ip5,
  927. ip6])
  928. self.assertEqual(list(collapsed),
  929. [ipaddress.IPv4Network('1.1.0.0/22'),
  930. ipaddress.IPv4Network('1.1.4.0/24')])
  931. # test that two addresses are supernet'ed properly
  932. collapsed = ipaddress.collapse_addresses([ip1, ip2])
  933. self.assertEqual(list(collapsed),
  934. [ipaddress.IPv4Network('1.1.0.0/23')])
  935. # test same IP networks
  936. ip_same1 = ip_same2 = ipaddress.IPv4Network('1.1.1.1/32')
  937. self.assertEqual(list(ipaddress.collapse_addresses(
  938. [ip_same1, ip_same2])),
  939. [ip_same1])
  940. # test same IP addresses
  941. ip_same1 = ip_same2 = ipaddress.IPv4Address('1.1.1.1')
  942. self.assertEqual(list(ipaddress.collapse_addresses(
  943. [ip_same1, ip_same2])),
  944. [ipaddress.ip_network('1.1.1.1/32')])
  945. ip1 = ipaddress.IPv6Network('2001::/100')
  946. ip2 = ipaddress.IPv6Network('2001::/120')
  947. ip3 = ipaddress.IPv6Network('2001::/96')
  948. # test that ipv6 addresses are subsumed properly.
  949. collapsed = ipaddress.collapse_addresses([ip1, ip2, ip3])
  950. self.assertEqual(list(collapsed), [ip3])
  951. # the toejam test
  952. addr_tuples = [
  953. (ipaddress.ip_address('1.1.1.1'),
  954. ipaddress.ip_address('::1')),
  955. (ipaddress.IPv4Network('1.1.0.0/24'),
  956. ipaddress.IPv6Network('2001::/120')),
  957. (ipaddress.IPv4Network('1.1.0.0/32'),
  958. ipaddress.IPv6Network('2001::/128')),
  959. ]
  960. for ip1, ip2 in addr_tuples:
  961. self.assertRaises(TypeError, ipaddress.collapse_addresses,
  962. [ip1, ip2])
  963. def testSummarizing(self):
  964. #ip = ipaddress.ip_address
  965. #ipnet = ipaddress.ip_network
  966. summarize = ipaddress.summarize_address_range
  967. ip1 = ipaddress.ip_address('1.1.1.0')
  968. ip2 = ipaddress.ip_address('1.1.1.255')
  969. # summarize works only for IPv4 & IPv6
  970. class IPv7Address(ipaddress.IPv6Address):
  971. @property
  972. def version(self):
  973. return 7
  974. ip_invalid1 = IPv7Address('::1')
  975. ip_invalid2 = IPv7Address('::1')
  976. self.assertRaises(ValueError, list,
  977. summarize(ip_invalid1, ip_invalid2))
  978. # test that a summary over ip4 & ip6 fails
  979. self.assertRaises(TypeError, list,
  980. summarize(ip1, ipaddress.IPv6Address('::1')))
  981. # test a /24 is summarized properly
  982. self.assertEqual(list(summarize(ip1, ip2))[0],
  983. ipaddress.ip_network('1.1.1.0/24'))
  984. # test an IPv4 range that isn't on a network byte boundary
  985. ip2 = ipaddress.ip_address('1.1.1.8')
  986. self.assertEqual(list(summarize(ip1, ip2)),
  987. [ipaddress.ip_network('1.1.1.0/29'),
  988. ipaddress.ip_network('1.1.1.8')])
  989. # all!
  990. ip1 = ipaddress.IPv4Address(0)
  991. ip2 = ipaddress.IPv4Address(ipaddress.IPv4Address._ALL_ONES)
  992. self.assertEqual([ipaddress.IPv4Network('0.0.0.0/0')],
  993. list(summarize(ip1, ip2)))
  994. ip1 = ipaddress.ip_address('1::')
  995. ip2 = ipaddress.ip_address('1:ffff:ffff:ffff:ffff:ffff:ffff:ffff')
  996. # test a IPv6 is sumamrized properly
  997. self.assertEqual(list(summarize(ip1, ip2))[0],
  998. ipaddress.ip_network('1::/16'))
  999. # test an IPv6 range that isn't on a network byte boundary
  1000. ip2 = ipaddress.ip_address('2::')
  1001. self.assertEqual(list(summarize(ip1, ip2)),
  1002. [ipaddress.ip_network('1::/16'),
  1003. ipaddress.ip_network('2::/128')])
  1004. # test exception raised when first is greater than last
  1005. self.assertRaises(ValueError, list,
  1006. summarize(ipaddress.ip_address('1.1.1.0'),
  1007. ipaddress.ip_address('1.1.0.0')))
  1008. # test exception raised when first and last aren't IP addresses
  1009. self.assertRaises(TypeError, list,
  1010. summarize(ipaddress.ip_network('1.1.1.0'),
  1011. ipaddress.ip_network('1.1.0.0')))
  1012. self.assertRaises(TypeError, list,
  1013. summarize(ipaddress.ip_network('1.1.1.0'),
  1014. ipaddress.ip_network('1.1.0.0')))
  1015. # test exception raised when first and last are not same version
  1016. self.assertRaises(TypeError, list,
  1017. summarize(ipaddress.ip_address('::'),
  1018. ipaddress.ip_network('1.1.0.0')))
  1019. def testAddressComparison(self):
  1020. self.assertTrue(ipaddress.ip_address('1.1.1.1') <=
  1021. ipaddress.ip_address('1.1.1.1'))
  1022. self.assertTrue(ipaddress.ip_address('1.1.1.1') <=
  1023. ipaddress.ip_address('1.1.1.2'))
  1024. self.assertTrue(ipaddress.ip_address('::1') <=
  1025. ipaddress.ip_address('::1'))
  1026. self.assertTrue(ipaddress.ip_address('::1') <=
  1027. ipaddress.ip_address('::2'))
  1028. def testInterfaceComparison(self):
  1029. self.assertTrue(ipaddress.ip_interface('1.1.1.1') <=
  1030. ipaddress.ip_interface('1.1.1.1'))
  1031. self.assertTrue(ipaddress.ip_interface('1.1.1.1') <=
  1032. ipaddress.ip_interface('1.1.1.2'))
  1033. self.assertTrue(ipaddress.ip_interface('::1') <=
  1034. ipaddress.ip_interface('::1'))
  1035. self.assertTrue(ipaddress.ip_interface('::1') <=
  1036. ipaddress.ip_interface('::2'))
  1037. def testNetworkComparison(self):
  1038. # ip1 and ip2 have the same network address
  1039. ip1 = ipaddress.IPv4Network('1.1.1.0/24')
  1040. ip2 = ipaddress.IPv4Network('1.1.1.0/32')
  1041. ip3 = ipaddress.IPv4Network('1.1.2.0/24')
  1042. self.assertTrue(ip1 < ip3)
  1043. self.assertTrue(ip3 > ip2)
  1044. self.assertEqual(ip1.compare_networks(ip1), 0)
  1045. # if addresses are the same, sort by netmask
  1046. self.assertEqual(ip1.compare_networks(ip2), -1)
  1047. self.assertEqual(ip2.compare_networks(ip1), 1)
  1048. self.assertEqual(ip1.compare_networks(ip3), -1)
  1049. self.assertEqual(ip3.compare_networks(ip1), 1)
  1050. self.assertTrue(ip1._get_networks_key() < ip3._get_networks_key())
  1051. ip1 = ipaddress.IPv6Network('2001:2000::/96')
  1052. ip2 = ipaddress.IPv6Network('2001:2001::/96')
  1053. ip3 = ipaddress.IPv6Network('2001:ffff:2000::/96')
  1054. self.assertTrue(ip1 < ip3)
  1055. self.assertTrue(ip3 > ip2)
  1056. self.assertEqual(ip1.compare_networks(ip3), -1)
  1057. self.assertTrue(ip1._get_networks_key() < ip3._get_networks_key())
  1058. # Test comparing different protocols.
  1059. # Should always raise a TypeError.
  1060. self.assertRaises(TypeError,
  1061. self.ipv4_network.compare_networks,
  1062. self.ipv6_network)
  1063. ipv6 = ipaddress.IPv6Interface('::/0')
  1064. ipv4 = ipaddress.IPv4Interface('0.0.0.0/0')
  1065. self.assertRaises(TypeError, ipv4.__lt__, ipv6)
  1066. self.assertRaises(TypeError, ipv4.__gt__, ipv6)
  1067. self.assertRaises(TypeError, ipv6.__lt__, ipv4)
  1068. self.assertRaises(TypeError, ipv6.__gt__, ipv4)
  1069. # Regression test for issue 19.
  1070. ip1 = ipaddress.ip_network('10.1.2.128/25')
  1071. self.assertFalse(ip1 < ip1)
  1072. self.assertFalse(ip1 > ip1)
  1073. ip2 = ipaddress.ip_network('10.1.3.0/24')
  1074. self.assertTrue(ip1 < ip2)
  1075. self.assertFalse(ip2 < ip1)
  1076. self.assertFalse(ip1 > ip2)
  1077. self.assertTrue(ip2 > ip1)
  1078. ip3 = ipaddress.ip_network('10.1.3.0/25')
  1079. self.assertTrue(ip2 < ip3)
  1080. self.assertFalse(ip3 < ip2)
  1081. self.assertFalse(ip2 > ip3)
  1082. self.assertTrue(ip3 > ip2)
  1083. # Regression test for issue 28.
  1084. ip1 = ipaddress.ip_network('10.10.10.0/31')
  1085. ip2 = ipaddress.ip_network('10.10.10.0')
  1086. ip3 = ipaddress.ip_network('10.10.10.2/31')
  1087. ip4 = ipaddress.ip_network('10.10.10.2')
  1088. sorted = [ip1, ip2, ip3, ip4]
  1089. unsorted = [ip2, ip4, ip1, ip3]
  1090. unsorted.sort()
  1091. self.assertEqual(sorted, unsorted)
  1092. unsorted = [ip4, ip1, ip3, ip2]
  1093. unsorted.sort()
  1094. self.assertEqual(sorted, unsorted)
  1095. self.assertRaises(TypeError, ip1.__lt__,
  1096. ipaddress.ip_address('10.10.10.0'))
  1097. self.assertRaises(TypeError, ip2.__lt__,
  1098. ipaddress.ip_address('10.10.10.0'))
  1099. # <=, >=
  1100. self.assertTrue(ipaddress.ip_network('1.1.1.1') <=
  1101. ipaddress.ip_network('1.1.1.1'))
  1102. self.assertTrue(ipaddress.ip_network('1.1.1.1') <=
  1103. ipaddress.ip_network('1.1.1.2'))
  1104. self.assertFalse(ipaddress.ip_network('1.1.1.2') <=
  1105. ipaddress.ip_network('1.1.1.1'))
  1106. self.assertTrue(ipaddress.ip_network('::1') <=
  1107. ipaddress.ip_network('::1'))
  1108. self.assertTrue(ipaddress.ip_network('::1') <=
  1109. ipaddress.ip_network('::2'))
  1110. self.assertFalse(ipaddress.ip_network('::2') <=
  1111. ipaddress.ip_network('::1'))
  1112. def testStrictNetworks(self):
  1113. self.assertRaises(ValueError, ipaddress.ip_network, '192.168.1.1/24')
  1114. self.assertRaises(ValueError, ipaddress.ip_network, '::1/120')
  1115. def testOverlaps(self):
  1116. other = ipaddress.IPv4Network('1.2.3.0/30')
  1117. other2 = ipaddress.IPv4Network('1.2.2.0/24')
  1118. other3 = ipaddress.IPv4Network('1.2.2.64/26')
  1119. self.assertTrue(self.ipv4_network.overlaps(other))
  1120. self.assertFalse(self.ipv4_network.overlaps(other2))
  1121. self.assertTrue(other2.overlaps(other3))
  1122. def testEmbeddedIpv4(self):
  1123. ipv4_string = '192.168.0.1'
  1124. ipv4 = ipaddress.IPv4Interface(ipv4_string)
  1125. v4compat_ipv6 = ipaddress.IPv6Interface('::%s' % ipv4_string)
  1126. self.assertEqual(int(v4compat_ipv6.ip), int(ipv4.ip))
  1127. v4mapped_ipv6 = ipaddress.IPv6Interface('::ffff:%s' % ipv4_string)
  1128. self.assertNotEqual(v4mapped_ipv6.ip, ipv4.ip)
  1129. self.assertRaises(ipaddress.AddressValueError, ipaddress.IPv6Interface,
  1130. '2001:1.1.1.1:1.1.1.1')
  1131. # Issue 67: IPv6 with embedded IPv4 address not recognized.
  1132. def testIPv6AddressTooLarge(self):
  1133. # RFC4291 2.5.5.2
  1134. self.assertEqual(ipaddress.ip_address('::FFFF:192.0.2.1'),
  1135. ipaddress.ip_address('::FFFF:c000:201'))
  1136. # RFC4291 2.2 (part 3) x::d.d.d.d
  1137. self.assertEqual(ipaddress.ip_address('FFFF::192.0.2.1'),
  1138. ipaddress.ip_address('FFFF::c000:201'))
  1139. def testIPVersion(self):
  1140. self.assertEqual(self.ipv4_address.version, 4)
  1141. self.assertEqual(self.ipv6_address.version, 6)
  1142. def testMaxPrefixLength(self):
  1143. self.assertEqual(self.ipv4_interface.max_prefixlen, 32)
  1144. self.assertEqual(self.ipv6_interface.max_prefixlen, 128)
  1145. def testPacked(self):
  1146. self.assertEqual(self.ipv4_address.packed,
  1147. bytearray(b'\x01\x02\x03\x04'))
  1148. self.assertEqual(ipaddress.IPv4Interface('255.254.253.252').packed,
  1149. bytearray(b'\xff\xfe\xfd\xfc'))
  1150. self.assertEqual(self.ipv6_address.packed,
  1151. bytearray(b'\x20\x01\x06\x58\x02\x2a\xca\xfe'
  1152. b'\x02\x00\x00\x00\x00\x00\x00\x01'))
  1153. self.assertEqual(ipaddress.IPv6Interface('ffff:2:3:4:ffff::').packed,
  1154. bytearray(b'\xff\xff\x00\x02\x00\x03\x00\x04\xff\xff')
  1155. + bytearray(b'\x00') * 6)
  1156. self.assertEqual(ipaddress.IPv6Interface('::1:0:0:0:0').packed,
  1157. bytearray(b'\x00') * 6 + bytearray(b'\x00\x01') + bytearray(b'\x00') * 8)
  1158. def testIpType(self):
  1159. ipv4net = ipaddress.ip_network('1.2.3.4')
  1160. ipv4addr = ipaddress.ip_address('1.2.3.4')
  1161. ipv6net = ipaddress.ip_network('::1.2.3.4')
  1162. ipv6addr = ipaddress.ip_address('::1.2.3.4')
  1163. self.assertEqual(ipaddress.IPv4Network, type(ipv4net))
  1164. self.assertEqual(ipaddress.IPv4Address, type(ipv4addr))
  1165. self.assertEqual(ipaddress.IPv6Network, type(ipv6net))
  1166. self.assertEqual(ipaddress.IPv6Address, type(ipv6addr))
  1167. def testReservedIpv4(self):
  1168. # test networks
  1169. self.assertEqual(True, ipaddress.ip_interface(
  1170. '224.1.1.1/31').is_multicast)
  1171. self.assertEqual(False, ipaddress.ip_network('240.0.0.0').is_multicast)
  1172. self.assertEqual(True, ipaddress.ip_network('240.0.0.0').is_reserved)
  1173. self.assertEqual(True, ipaddress.ip_interface(
  1174. '192.168.1.1/17').is_private)
  1175. self.assertEqual(False, ipaddress.ip_network('192.169.0.0').is_private)
  1176. self.assertEqual(True, ipaddress.ip_network(
  1177. '10.255.255.255').is_private)
  1178. self.assertEqual(False, ipaddress.ip_network('11.0.0.0').is_private)
  1179. self.assertEqual(False, ipaddress.ip_network('11.0.0.0').is_reserved)
  1180. self.assertEqual(True, ipaddress.ip_network(
  1181. '172.31.255.255').is_private)
  1182. self.assertEqual(False, ipaddress.ip_network('172.32.0.0').is_private)
  1183. self.assertEqual(True,
  1184. ipaddress.ip_network('169.254.1.0/24').is_link_local)
  1185. self.assertEqual(True,
  1186. ipaddress.ip_interface(
  1187. '169.254.100.200/24').is_link_local)
  1188. self.assertEqual(False,
  1189. ipaddress.ip_interface(
  1190. '169.255.100.200/24').is_link_local)
  1191. self.assertEqual(True,
  1192. ipaddress.ip_network(
  1193. '127.100.200.254/32').is_loopback)
  1194. self.assertEqual(True, ipaddress.ip_network(
  1195. '127.42.0.0/16').is_loopback)
  1196. self.assertEqual(False, ipaddress.ip_network('128.0.0.0').is_loopback)
  1197. self.assertEqual(False,
  1198. ipaddress.ip_network('100.64.0.0/10').is_private)
  1199. self.assertEqual(False, ipaddress.ip_network('100.64.0.0/10').is_global)
  1200. self.assertEqual(True,
  1201. ipaddress.ip_network('192.0.2.128/25').is_private)
  1202. self.assertEqual(True,
  1203. ipaddress.ip_network('192.0.3.0/24').is_global)
  1204. # test addresses
  1205. self.assertEqual(True, ipaddress.ip_address('0.0.0.0').is_unspecified)
  1206. self.assertEqual(True, ipaddress.ip_address('224.1.1.1').is_multicast)
  1207. self.assertEqual(False, ipaddress.ip_address('240.0.0.0').is_multicast)
  1208. self.assertEqual(True, ipaddress.ip_address('240.0.0.1').is_reserved)
  1209. self.assertEqual(False,
  1210. ipaddress.ip_address('239.255.255.255').is_reserved)
  1211. self.assertEqual(True, ipaddress.ip_address('192.168.1.1').is_private)
  1212. self.assertEqual(False, ipaddress.ip_address('192.169.0.0').is_private)
  1213. self.assertEqual(True, ipaddress.ip_address(
  1214. '10.255.255.255').is_private)
  1215. self.assertEqual(False, ipaddress.ip_address('11.0.0.0').is_private)
  1216. self.assertEqual(True, ipaddress.ip_address(
  1217. '172.31.255.255').is_private)
  1218. self.assertEqual(False, ipaddress.ip_address('172.32.0.0').is_private)
  1219. self.assertEqual(True,
  1220. ipaddress.ip_address('169.254.100.200').is_link_local)
  1221. self.assertEqual(False,
  1222. ipaddress.ip_address('169.255.100.200').is_link_local)
  1223. self.assertEqual(True,
  1224. ipaddress.ip_address('127.100.200.254').is_loopback)
  1225. self.assertEqual(True, ipaddress.ip_address('127.42.0.0').is_loopback)
  1226. self.assertEqual(False, ipaddress.ip_address('128.0.0.0').is_loopback)
  1227. self.assertEqual(True, ipaddress.ip_network('0.0.0.0').is_unspecified)
  1228. def testReservedIpv6(self):
  1229. self.assertEqual(True, ipaddress.ip_network('ffff::').is_multicast)
  1230. self.assertEqual(True, ipaddress.ip_network(2**128 - 1).is_multicast)
  1231. self.assertEqual(True, ipaddress.ip_network('ff00::').is_multicast)
  1232. self.assertEqual(False, ipaddress.ip_network('fdff::').is_multicast)
  1233. self.assertEqual(True, ipaddress.ip_network('fecf::').is_site_local)
  1234. self.assertEqual(True, ipaddress.ip_network(
  1235. 'feff:ffff:ffff:ffff::').is_site_local)
  1236. self.assertEqual(False, ipaddress.ip_network(
  1237. 'fbf:ffff::').is_site_local)
  1238. self.assertEqual(False, ipaddress.ip_network('ff00::').is_site_local)
  1239. self.assertEqual(True, ipaddress.ip_network('fc00::').is_private)
  1240. self.assertEqual(True, ipaddress.ip_network(
  1241. 'fc00:ffff:ffff:ffff::').is_private)
  1242. self.assertEqual(False, ipaddress.ip_network('fbff:ffff::').is_private)
  1243. self.assertEqual(False, ipaddress.ip_network('fe00::').is_private)
  1244. self.assertEqual(True, ipaddress.ip_network('fea0::').is_link_local)
  1245. self.assertEqual(True, ipaddress.ip_network(
  1246. 'febf:ffff::').is_link_local)
  1247. self.assertEqual(False, ipaddress.ip_network(
  1248. 'fe7f:ffff::').is_link_local)
  1249. self.assertEqual(False, ipaddress.ip_network('fec0::').is_link_local)
  1250. self.assertEqual(True, ipaddress.ip_interface('0:0::0:01').is_loopback)
  1251. self.assertEqual(False, ipaddress.ip_interface('::1/127').is_loopback)
  1252. self.assertEqual(False, ipaddress.ip_network('::').is_loopback)
  1253. self.assertEqual(False, ipaddress.ip_network('::2').is_loopback)
  1254. self.assertEqual(True, ipaddress.ip_network('0::0').is_unspecified)
  1255. self.assertEqual(False, ipaddress.ip_network('::1').is_unspecified)
  1256. self.assertEqual(False, ipaddress.ip_network('::/127').is_unspecified)
  1257. self.assertEqual(True,
  1258. ipaddress.ip_network('2001::1/128').is_private)
  1259. self.assertEqual(True,
  1260. ipaddress.ip_network('200::1/128').is_global)
  1261. # test addresses
  1262. self.assertEqual(True, ipaddress.ip_address('ffff::').is_multicast)
  1263. self.assertEqual(True, ipaddress.ip_address(2**128 - 1).is_multicast)
  1264. self.assertEqual(True, ipaddress.ip_address('ff00::').is_multicast)
  1265. self.assertEqual(False, ipaddress.ip_address('fdff::').is_multicast)
  1266. self.assertEqual(True, ipaddress.ip_address('fecf::').is_site_local)
  1267. self.assertEqual(True, ipaddress.ip_address(
  1268. 'feff:ffff:ffff:ffff::').is_site_local)
  1269. self.assertEqual(False, ipaddress.ip_address(
  1270. 'fbf:ffff::').is_site_local)
  1271. self.assertEqual(False, ipaddress.ip_address('ff00::').is_site_local)
  1272. self.assertEqual(True, ipaddress.ip_address('fc00::').is_private)
  1273. self.assertEqual(True, ipaddress.ip_address(
  1274. 'fc00:ffff:ffff:ffff::').is_private)
  1275. self.assertEqual(False, ipaddress.ip_address('fbff:ffff::').is_private)
  1276. self.assertEqual(False, ipaddress.ip_address('fe00::').is_private)
  1277. self.assertEqual(True, ipaddress.ip_address('fea0::').is_link_local)
  1278. self.assertEqual(True, ipaddress.ip_address(
  1279. 'febf:ffff::').is_link_local)
  1280. self.assertEqual(False, ipaddress.ip_address(
  1281. 'fe7f:ffff::').is_link_local)
  1282. self.assertEqual(False, ipaddress.ip_address('fec0::').is_link_local)
  1283. self.assertEqual(True, ipaddress.ip_address('0:0::0:01').is_loopback)
  1284. self.assertEqual(True, ipaddress.ip_address('::1').is_loopback)
  1285. self.assertEqual(False, ipaddress.ip_address('::2').is_loopback)
  1286. self.assertEqual(True, ipaddress.ip_address('0::0').is_unspecified)
  1287. self.assertEqual(False, ipaddress.ip_address('::1').is_unspecified)
  1288. # some generic IETF reserved addresses
  1289. self.assertEqual(True, ipaddress.ip_address('100::').is_reserved)
  1290. self.assertEqual(True, ipaddress.ip_network('4000::1/128').is_reserved)
  1291. def testIpv4Mapped(self):
  1292. self.assertEqual(
  1293. ipaddress.ip_address('::ffff:192.168.1.1').ipv4_mapped,
  1294. ipaddress.ip_address('192.168.1.1'))
  1295. self.assertEqual(ipaddress.ip_address('::c0a8:101').ipv4_mapped, None)
  1296. self.assertEqual(ipaddress.ip_address('::ffff:c0a8:101').ipv4_mapped,
  1297. ipaddress.ip_address('192.168.1.1'))
  1298. def testAddrExclude(self):
  1299. addr1 = ipaddress.ip_network('10.1.1.0/24')
  1300. addr2 = ipaddress.ip_network('10.1.1.0/26')
  1301. addr3 = ipaddress.ip_network('10.2.1.0/24')
  1302. addr4 = ipaddress.ip_address('10.1.1.0')
  1303. addr5 = ipaddress.ip_network('2001:db8::0/32')
  1304. self.assertEqual(sorted(list(addr1.address_exclude(addr2))),
  1305. [ipaddress.ip_network('10.1.1.64/26'),
  1306. ipaddress.ip_network('10.1.1.128/25')])
  1307. self.assertRaises(ValueError, list, addr1.address_exclude(addr3))
  1308. self.assertRaises(TypeError, list, addr1.address_exclude(addr4))
  1309. self.assertRaises(TypeError, list, addr1.address_exclude(addr5))
  1310. self.assertEqual(list(addr1.address_exclude(addr1)), [])
  1311. def testHash(self):
  1312. self.assertEqual(hash(ipaddress.ip_interface('10.1.1.0/24')),
  1313. hash(ipaddress.ip_interface('10.1.1.0/24')))
  1314. self.assertEqual(hash(ipaddress.ip_network('10.1.1.0/24')),
  1315. hash(ipaddress.ip_network('10.1.1.0/24')))
  1316. self.assertEqual(hash(ipaddress.ip_address('10.1.1.0')),
  1317. hash(ipaddress.ip_address('10.1.1.0')))
  1318. # i70
  1319. self.assertEqual(hash(ipaddress.ip_address('1.2.3.4')),
  1320. hash(ipaddress.ip_address(
  1321. int(ipaddress.ip_address('1.2.3.4')._ip))))
  1322. ip1 = ipaddress.ip_address('10.1.1.0')
  1323. ip2 = ipaddress.ip_address('1::')
  1324. dummy = {}
  1325. dummy[self.ipv4_address] = None
  1326. dummy[self.ipv6_address] = None
  1327. dummy[ip1] = None
  1328. dummy[ip2] = None
  1329. self.assertIn(self.ipv4_address, dummy)
  1330. self.assertIn(ip2, dummy)
  1331. def testIPBases(self):
  1332. net = self.ipv4_network
  1333. self.assertEqual('1.2.3.0/24', net.compressed)
  1334. net = self.ipv6_network
  1335. self.assertRaises(ValueError, net._string_from_ip_int, 2**128 + 1)
  1336. def testIPv6NetworkHelpers(self):
  1337. net = self.ipv6_network
  1338. self.assertEqual('2001:658:22a:cafe::/64', net.with_prefixlen)
  1339. self.assertEqual('2001:658:22a:cafe::/ffff:ffff:ffff:ffff::',
  1340. net.with_netmask)
  1341. self.assertEqual('2001:658:22a:cafe::/::ffff:ffff:ffff:ffff',
  1342. net.with_hostmask)
  1343. self.assertEqual('2001:658:22a:cafe::/64', str(net))
  1344. def testIPv4NetworkHelpers(self):
  1345. net = self.ipv4_network
  1346. self.assertEqual('1.2.3.0/24', net.with_prefixlen)
  1347. self.assertEqual('1.2.3.0/255.255.255.0', net.with_netmask)
  1348. self.assertEqual('1.2.3.0/0.0.0.255', net.with_hostmask)
  1349. self.assertEqual('1.2.3.0/24', str(net))
  1350. def testCopyConstructor(self):
  1351. addr1 = ipaddress.ip_network('10.1.1.0/24')
  1352. addr2 = ipaddress.ip_network(addr1)
  1353. addr3 = ipaddress.ip_interface('2001:658:22a:cafe:200::1/64')
  1354. addr4 = ipaddress.ip_interface(addr3)
  1355. addr5 = ipaddress.IPv4Address('1.1.1.1')
  1356. addr6 = ipaddress.IPv6Address('2001:658:22a:cafe:200::1')
  1357. self.assertEqual(addr1, addr2)
  1358. self.assertEqual(addr3, addr4)
  1359. self.assertEqual(addr5, ipaddress.IPv4Address(addr5))
  1360. self.assertEqual(addr6, ipaddress.IPv6Address(addr6))
  1361. def testCompressIPv6Address(self):
  1362. test_addresses = {
  1363. '1:2:3:4:5:6:7:8': '1:2:3:4:5:6:7:8/128',
  1364. '2001:0:0:4:0:0:0:8': '2001:0:0:4::8/128',
  1365. '2001:0:0:4:5:6:7:8': '2001::4:5:6:7:8/128',
  1366. '2001:0:3:4:5:6:7:8': '2001:0:3:4:5:6:7:8/128',
  1367. '2001:0:3:4:5:6:7:8': '2001:0:3:4:5:6:7:8/128',
  1368. '0:0:3:0:0:0:0:ffff': '0:0:3::ffff/128',
  1369. '0:0:0:4:0:0:0:ffff': '::4:0:0:0:ffff/128',
  1370. '0:0:0:0:5:0:0:ffff': '::5:0:0:ffff/128',
  1371. '1:0:0:4:0:0:7:8': '1::4:0:0:7:8/128',
  1372. '0:0:0:0:0:0:0:0': '::/128',
  1373. '0:0:0:0:0:0:0:0/0': '::/0',
  1374. '0:0:0:0:0:0:0:1': '::1/128',
  1375. '2001:0658:022a:cafe:0000:0000:0000:0000/66':
  1376. '2001:658:22a:cafe::/66',
  1377. '::1.2.3.4': '::102:304/128',
  1378. '1:2:3:4:5:ffff:1.2.3.4': '1:2:3:4:5:ffff:102:304/128',
  1379. '::7:6:5:4:3:2:1': '0:7:6:5:4:3:2:1/128',
  1380. '::7:6:5:4:3:2:0': '0:7:6:5:4:3:2:0/128',
  1381. '7:6:5:4:3:2:1::': '7:6:5:4:3:2:1:0/128',
  1382. '0:6:5:4:3:2:1::': '0:6:5:4:3:2:1:0/128',
  1383. }
  1384. for uncompressed, compressed in list(test_addresses.items()):
  1385. self.assertEqual(compressed, str(ipaddress.IPv6Interface(
  1386. uncompressed)))
  1387. def testExplodeShortHandIpStr(self):
  1388. addr1 = ipaddress.IPv6Interface('2001::1')
  1389. addr2 = ipaddress.IPv6Address('2001:0:5ef5:79fd:0:59d:a0e5:ba1')
  1390. addr3 = ipaddress.IPv6Network('2001::/96')
  1391. addr4 = ipaddress.IPv4Address('192.168.178.1')
  1392. self.assertEqual('2001:0000:0000:0000:0000:0000:0000:0001/128',
  1393. addr1.exploded)
  1394. self.assertEqual('0000:0000:0000:0000:0000:0000:0000:0001/128',
  1395. ipaddress.IPv6Interface('::1/128').exploded)
  1396. # issue 77
  1397. self.assertEqual('2001:0000:5ef5:79fd:0000:059d:a0e5:0ba1',
  1398. addr2.exploded)
  1399. self.assertEqual('2001:0000:0000:0000:0000:0000:0000:0000/96',
  1400. addr3.exploded)
  1401. self.assertEqual('192.168.178.1', addr4.exploded)
  1402. def testIntRepresentation(self):
  1403. self.assertEqual(16909060, int(self.ipv4_address))
  1404. self.assertEqual(42540616829182469433547762482097946625,
  1405. int(self.ipv6_address))
  1406. def testForceVersion(self):
  1407. self.assertEqual(ipaddress.ip_network(1).version, 4)
  1408. self.assertEqual(ipaddress.IPv6Network(1).version, 6)
  1409. def testWithStar(self):
  1410. self.assertEqual(self.ipv4_interface.with_prefixlen, "1.2.3.4/24")
  1411. self.assertEqual(self.ipv4_interface.with_netmask,
  1412. "1.2.3.4/255.255.255.0")
  1413. self.assertEqual(self.ipv4_interface.with_hostmask,
  1414. "1.2.3.4/0.0.0.255")
  1415. self.assertEqual(self.ipv6_interface.with_prefixlen,
  1416. '2001:658:22a:cafe:200::1/64')
  1417. self.assertEqual(self.ipv6_interface.with_netmask,
  1418. '2001:658:22a:cafe:200::1/ffff:ffff:ffff:ffff::')
  1419. # this probably don't make much sense, but it's included for
  1420. # compatibility with ipv4
  1421. self.assertEqual(self.ipv6_interface.with_hostmask,
  1422. '2001:658:22a:cafe:200::1/::ffff:ffff:ffff:ffff')
  1423. def testNetworkElementCaching(self):
  1424. # V4 - make sure we're empty
  1425. self.assertNotIn('network_address', self.ipv4_network._cache)
  1426. self.assertNotIn('broadcast_address', self.ipv4_network._cache)
  1427. self.assertNotIn('hostmask', self.ipv4_network._cache)
  1428. # V4 - populate and test
  1429. self.assertEqual(self.ipv4_network.network_address,
  1430. ipaddress.IPv4Address('1.2.3.0'))
  1431. self.assertEqual(self.ipv4_network.broadcast_address,
  1432. ipaddress.IPv4Address('1.2.3.255'))
  1433. self.assertEqual(self.ipv4_network.hostmask,
  1434. ipaddress.IPv4Address('0.0.0.255'))
  1435. # V4 - check we're cached
  1436. self.assertIn('broadcast_address', self.ipv4_network._cache)
  1437. self.assertIn('hostmask', self.ipv4_network._cache)
  1438. # V6 - make sure we're empty
  1439. self.assertNotIn('broadcast_address', self.ipv6_network._cache)
  1440. self.assertNotIn('hostmask', self.ipv6_network._cache)
  1441. # V6 - populate and test
  1442. self.assertEqual(self.ipv6_network.network_address,
  1443. ipaddress.IPv6Address('2001:658:22a:cafe::'))
  1444. self.assertEqual(self.ipv6_interface.network.network_address,
  1445. ipaddress.IPv6Address('2001:658:22a:cafe::'))
  1446. self.assertEqual(
  1447. self.ipv6_network.broadcast_address,
  1448. ipaddress.IPv6Address('2001:658:22a:cafe:ffff:ffff:ffff:ffff'))
  1449. self.assertEqual(self.ipv6_network.hostmask,
  1450. ipaddress.IPv6Address('::ffff:ffff:ffff:ffff'))
  1451. self.assertEqual(
  1452. self.ipv6_interface.network.broadcast_address,
  1453. ipaddress.IPv6Address('2001:658:22a:cafe:ffff:ffff:ffff:ffff'))
  1454. self.assertEqual(self.ipv6_interface.network.hostmask,
  1455. ipaddress.IPv6Address('::ffff:ffff:ffff:ffff'))
  1456. # V6 - check we're cached
  1457. self.assertIn('broadcast_address', self.ipv6_network._cache)
  1458. self.assertIn('hostmask', self.ipv6_network._cache)
  1459. self.assertIn('broadcast_address', self.ipv6_interface.network._cache)
  1460. self.assertIn('hostmask', self.ipv6_interface.network._cache)
  1461. def testTeredo(self):
  1462. # stolen from wikipedia
  1463. server = ipaddress.IPv4Address('65.54.227.120')
  1464. client = ipaddress.IPv4Address('192.0.2.45')
  1465. teredo_addr = '2001:0000:4136:e378:8000:63bf:3fff:fdd2'
  1466. self.assertEqual((server, client),
  1467. ipaddress.ip_address(teredo_addr).teredo)
  1468. bad_addr = '2000::4136:e378:8000:63bf:3fff:fdd2'
  1469. self.assertFalse(ipaddress.ip_address(bad_addr).teredo)
  1470. bad_addr = '2001:0001:4136:e378:8000:63bf:3fff:fdd2'
  1471. self.assertFalse(ipaddress.ip_address(bad_addr).teredo)
  1472. # i77
  1473. teredo_addr = ipaddress.IPv6Address('2001:0:5ef5:79fd:0:59d:a0e5:ba1')
  1474. self.assertEqual((ipaddress.IPv4Address('94.245.121.253'),
  1475. ipaddress.IPv4Address('95.26.244.94')),
  1476. teredo_addr.teredo)
  1477. def testsixtofour(self):
  1478. sixtofouraddr = ipaddress.ip_address('2002:ac1d:2d64::1')
  1479. bad_addr = ipaddress.ip_address('2000:ac1d:2d64::1')
  1480. self.assertEqual(ipaddress.IPv4Address('172.29.45.100'),
  1481. sixtofouraddr.sixtofour)
  1482. self.assertFalse(bad_addr.sixtofour)