test_ipaddress.py 73 KB

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