IPNetwork.cs 63 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170
  1. using System.Collections.Generic;
  2. using System.IO;
  3. using System.Net.Sockets;
  4. using System.Numerics;
  5. using System.Text.RegularExpressions;
  6. namespace System.Net
  7. {
  8. /// <summary>
  9. /// IP Network utility class.
  10. /// Use IPNetwork.Parse to create instances.
  11. /// </summary>
  12. public class IPNetwork : IComparable<IPNetwork>
  13. {
  14. #region properties
  15. //private uint _network;
  16. private BigInteger _ipaddress;
  17. private AddressFamily _family;
  18. //private uint _netmask;
  19. //private uint _broadcast;
  20. //private uint _firstUsable;
  21. //private uint _lastUsable;
  22. //private uint _usable;
  23. private byte _cidr;
  24. #endregion
  25. #region accessors
  26. private BigInteger _network
  27. {
  28. get
  29. {
  30. BigInteger uintNetwork = this._ipaddress & this._netmask;
  31. return uintNetwork;
  32. }
  33. }
  34. /// <summary>
  35. /// Network address
  36. /// </summary>
  37. public IPAddress Network
  38. {
  39. get
  40. {
  41. return IPNetwork.ToIPAddress(this._network, this._family);
  42. }
  43. }
  44. /// <summary>
  45. /// Address Family
  46. /// </summary>
  47. public AddressFamily AddressFamily
  48. {
  49. get
  50. {
  51. return this._family;
  52. }
  53. }
  54. private BigInteger _netmask
  55. {
  56. get
  57. {
  58. return IPNetwork.ToUint(this._cidr, this._family);
  59. }
  60. }
  61. /// <summary>
  62. /// Netmask
  63. /// </summary>
  64. public IPAddress Netmask
  65. {
  66. get
  67. {
  68. return IPNetwork.ToIPAddress(this._netmask, this._family);
  69. }
  70. }
  71. private BigInteger _broadcast
  72. {
  73. get
  74. {
  75. int width = this._family == Sockets.AddressFamily.InterNetwork ? 4 : 16;
  76. BigInteger uintBroadcast = this._network + this._netmask.PositiveReverse(width);
  77. return uintBroadcast;
  78. }
  79. }
  80. /// <summary>
  81. /// Broadcast address
  82. /// </summary>
  83. public IPAddress Broadcast
  84. {
  85. get
  86. {
  87. if (this._family == Sockets.AddressFamily.InterNetworkV6)
  88. {
  89. return null;
  90. }
  91. return IPNetwork.ToIPAddress(this._broadcast, this._family);
  92. }
  93. }
  94. /// <summary>
  95. /// First usable IP adress in Network
  96. /// </summary>
  97. public IPAddress FirstUsable
  98. {
  99. get
  100. {
  101. BigInteger fisrt = this._family == Sockets.AddressFamily.InterNetworkV6
  102. ? this._network
  103. : (this.Usable <= 0) ? this._network : this._network + 1;
  104. return IPNetwork.ToIPAddress(fisrt, this._family);
  105. }
  106. }
  107. /// <summary>
  108. /// Last usable IP adress in Network
  109. /// </summary>
  110. public IPAddress LastUsable
  111. {
  112. get
  113. {
  114. BigInteger last = this._family == Sockets.AddressFamily.InterNetworkV6
  115. ? this._broadcast
  116. : (this.Usable <= 0) ? this._network : this._broadcast - 1;
  117. return IPNetwork.ToIPAddress(last, this._family);
  118. }
  119. }
  120. /// <summary>
  121. /// Number of usable IP adress in Network
  122. /// </summary>
  123. public BigInteger Usable
  124. {
  125. get
  126. {
  127. if (this._family == Sockets.AddressFamily.InterNetworkV6)
  128. {
  129. return this.Total;
  130. }
  131. byte[] mask = new byte[] { 0xff, 0xff, 0xff, 0xff, 0x00 };
  132. BigInteger bmask = new BigInteger(mask);
  133. BigInteger usableIps = (_cidr > 30) ? 0 : ((bmask >> _cidr) - 1);
  134. return usableIps;
  135. }
  136. }
  137. /// <summary>
  138. /// Number of IP adress in Network
  139. /// </summary>
  140. public BigInteger Total
  141. {
  142. get
  143. {
  144. int max = this._family == Sockets.AddressFamily.InterNetwork ? 32 : 128;
  145. BigInteger count = BigInteger.Pow(2, (max - _cidr));
  146. return count;
  147. }
  148. }
  149. /// <summary>
  150. /// The CIDR netmask notation
  151. /// </summary>
  152. public byte Cidr
  153. {
  154. get
  155. {
  156. return this._cidr;
  157. }
  158. }
  159. #endregion
  160. #region constructor
  161. #if TRAVISCI
  162. public
  163. #else
  164. internal
  165. #endif
  166. IPNetwork(BigInteger ipaddress, AddressFamily family, byte cidr)
  167. {
  168. int maxCidr = family == Sockets.AddressFamily.InterNetwork ? 32 : 128;
  169. if (cidr > maxCidr)
  170. {
  171. throw new ArgumentOutOfRangeException("cidr");
  172. }
  173. this._ipaddress = ipaddress;
  174. this._family = family;
  175. this._cidr = cidr;
  176. }
  177. #endregion
  178. #region parsers
  179. /// <summary>
  180. /// 192.168.168.100 - 255.255.255.0
  181. ///
  182. /// Network : 192.168.168.0
  183. /// Netmask : 255.255.255.0
  184. /// Cidr : 24
  185. /// Start : 192.168.168.1
  186. /// End : 192.168.168.254
  187. /// Broadcast : 192.168.168.255
  188. /// </summary>
  189. /// <param name="ipaddress"></param>
  190. /// <param name="netmask"></param>
  191. /// <returns></returns>
  192. public static IPNetwork Parse(string ipaddress, string netmask)
  193. {
  194. IPNetwork ipnetwork = null;
  195. IPNetwork.InternalParse(false, ipaddress, netmask, out ipnetwork);
  196. return ipnetwork;
  197. }
  198. /// <summary>
  199. /// 192.168.168.100/24
  200. ///
  201. /// Network : 192.168.168.0
  202. /// Netmask : 255.255.255.0
  203. /// Cidr : 24
  204. /// Start : 192.168.168.1
  205. /// End : 192.168.168.254
  206. /// Broadcast : 192.168.168.255
  207. /// </summary>
  208. /// <param name="ipaddress"></param>
  209. /// <param name="cidr"></param>
  210. /// <returns></returns>
  211. public static IPNetwork Parse(string ipaddress, byte cidr)
  212. {
  213. IPNetwork ipnetwork = null;
  214. IPNetwork.InternalParse(false, ipaddress, cidr, out ipnetwork);
  215. return ipnetwork;
  216. }
  217. /// <summary>
  218. /// 192.168.168.100 255.255.255.0
  219. ///
  220. /// Network : 192.168.168.0
  221. /// Netmask : 255.255.255.0
  222. /// Cidr : 24
  223. /// Start : 192.168.168.1
  224. /// End : 192.168.168.254
  225. /// Broadcast : 192.168.168.255
  226. /// </summary>
  227. /// <param name="ipaddress"></param>
  228. /// <param name="netmask"></param>
  229. /// <returns></returns>
  230. public static IPNetwork Parse(IPAddress ipaddress, IPAddress netmask)
  231. {
  232. IPNetwork ipnetwork = null;
  233. IPNetwork.InternalParse(false, ipaddress, netmask, out ipnetwork);
  234. return ipnetwork;
  235. }
  236. /// <summary>
  237. /// 192.168.0.1/24
  238. /// 192.168.0.1 255.255.255.0
  239. ///
  240. /// Network : 192.168.0.0
  241. /// Netmask : 255.255.255.0
  242. /// Cidr : 24
  243. /// Start : 192.168.0.1
  244. /// End : 192.168.0.254
  245. /// Broadcast : 192.168.0.255
  246. /// </summary>
  247. /// <param name="network"></param>
  248. /// <returns></returns>
  249. public static IPNetwork Parse(string network)
  250. {
  251. IPNetwork ipnetwork = null;
  252. IPNetwork.InternalParse(false, network, out ipnetwork);
  253. return ipnetwork;
  254. }
  255. #endregion
  256. #region TryParse
  257. /// <summary>
  258. /// 192.168.168.100 - 255.255.255.0
  259. ///
  260. /// Network : 192.168.168.0
  261. /// Netmask : 255.255.255.0
  262. /// Cidr : 24
  263. /// Start : 192.168.168.1
  264. /// End : 192.168.168.254
  265. /// Broadcast : 192.168.168.255
  266. /// </summary>
  267. /// <param name="ipaddress"></param>
  268. /// <param name="netmask"></param>
  269. /// <returns></returns>
  270. public static bool TryParse(string ipaddress, string netmask, out IPNetwork ipnetwork)
  271. {
  272. IPNetwork ipnetwork2 = null;
  273. IPNetwork.InternalParse(true, ipaddress, netmask, out ipnetwork2);
  274. bool parsed = (ipnetwork2 != null);
  275. ipnetwork = ipnetwork2;
  276. return parsed;
  277. }
  278. /// <summary>
  279. /// 192.168.168.100/24
  280. ///
  281. /// Network : 192.168.168.0
  282. /// Netmask : 255.255.255.0
  283. /// Cidr : 24
  284. /// Start : 192.168.168.1
  285. /// End : 192.168.168.254
  286. /// Broadcast : 192.168.168.255
  287. /// </summary>
  288. /// <param name="ipaddress"></param>
  289. /// <param name="cidr"></param>
  290. /// <returns></returns>
  291. public static bool TryParse(string ipaddress, byte cidr, out IPNetwork ipnetwork)
  292. {
  293. IPNetwork ipnetwork2 = null;
  294. IPNetwork.InternalParse(true, ipaddress, cidr, out ipnetwork2);
  295. bool parsed = (ipnetwork2 != null);
  296. ipnetwork = ipnetwork2;
  297. return parsed;
  298. }
  299. /// <summary>
  300. /// 192.168.0.1/24
  301. /// 192.168.0.1 255.255.255.0
  302. ///
  303. /// Network : 192.168.0.0
  304. /// Netmask : 255.255.255.0
  305. /// Cidr : 24
  306. /// Start : 192.168.0.1
  307. /// End : 192.168.0.254
  308. /// Broadcast : 192.168.0.255
  309. /// </summary>
  310. /// <param name="network"></param>
  311. /// <param name="ipnetwork"></param>
  312. /// <returns></returns>
  313. public static bool TryParse(string network, out IPNetwork ipnetwork)
  314. {
  315. IPNetwork ipnetwork2 = null;
  316. IPNetwork.InternalParse(true, network, out ipnetwork2);
  317. bool parsed = (ipnetwork2 != null);
  318. ipnetwork = ipnetwork2;
  319. return parsed;
  320. }
  321. /// <summary>
  322. /// 192.168.0.1/24
  323. /// 192.168.0.1 255.255.255.0
  324. ///
  325. /// Network : 192.168.0.0
  326. /// Netmask : 255.255.255.0
  327. /// Cidr : 24
  328. /// Start : 192.168.0.1
  329. /// End : 192.168.0.254
  330. /// Broadcast : 192.168.0.255
  331. /// </summary>
  332. /// <param name="ipaddress"></param>
  333. /// <param name="netmask"></param>
  334. /// <param name="ipnetwork"></param>
  335. /// <returns></returns>
  336. public static bool TryParse(IPAddress ipaddress, IPAddress netmask, out IPNetwork ipnetwork)
  337. {
  338. IPNetwork ipnetwork2 = null;
  339. IPNetwork.InternalParse(true, ipaddress, netmask, out ipnetwork2);
  340. bool parsed = (ipnetwork2 != null);
  341. ipnetwork = ipnetwork2;
  342. return parsed;
  343. }
  344. #endregion
  345. #region InternalParse
  346. /// <summary>
  347. /// 192.168.168.100 - 255.255.255.0
  348. ///
  349. /// Network : 192.168.168.0
  350. /// Netmask : 255.255.255.0
  351. /// Cidr : 24
  352. /// Start : 192.168.168.1
  353. /// End : 192.168.168.254
  354. /// Broadcast : 192.168.168.255
  355. /// </summary>
  356. /// <param name="ipaddress"></param>
  357. /// <param name="netmask"></param>
  358. /// <returns></returns>
  359. private static void InternalParse(bool tryParse, string ipaddress, string netmask, out IPNetwork ipnetwork)
  360. {
  361. if (string.IsNullOrEmpty(ipaddress))
  362. {
  363. if (tryParse == false)
  364. {
  365. throw new ArgumentNullException("ipaddress");
  366. }
  367. ipnetwork = null;
  368. return;
  369. }
  370. if (string.IsNullOrEmpty(netmask))
  371. {
  372. if (tryParse == false)
  373. {
  374. throw new ArgumentNullException("netmask");
  375. }
  376. ipnetwork = null;
  377. return;
  378. }
  379. IPAddress ip = null;
  380. bool ipaddressParsed = IPAddress.TryParse(ipaddress, out ip);
  381. if (ipaddressParsed == false)
  382. {
  383. if (tryParse == false)
  384. {
  385. throw new ArgumentException("ipaddress");
  386. }
  387. ipnetwork = null;
  388. return;
  389. }
  390. IPAddress mask = null;
  391. bool netmaskParsed = IPAddress.TryParse(netmask, out mask);
  392. if (netmaskParsed == false)
  393. {
  394. if (tryParse == false)
  395. {
  396. throw new ArgumentException("netmask");
  397. }
  398. ipnetwork = null;
  399. return;
  400. }
  401. IPNetwork.InternalParse(tryParse, ip, mask, out ipnetwork);
  402. }
  403. private static void InternalParse(bool tryParse, string network, out IPNetwork ipnetwork)
  404. {
  405. if (string.IsNullOrEmpty(network))
  406. {
  407. if (tryParse == false)
  408. {
  409. throw new ArgumentNullException("network");
  410. }
  411. ipnetwork = null;
  412. return;
  413. }
  414. network = Regex.Replace(network, @"[^0-9a-fA-F\.\/\s\:]+", "");
  415. network = Regex.Replace(network, @"\s{2,}", " ");
  416. network = network.Trim();
  417. string[] args = network.Split(new char[] { ' ', '/' });
  418. byte cidr = 0;
  419. if (args.Length == 1)
  420. {
  421. if (IPNetwork.TryGuessCidr(args[0], out cidr))
  422. {
  423. IPNetwork.InternalParse(tryParse, args[0], cidr, out ipnetwork);
  424. return;
  425. }
  426. if (tryParse == false)
  427. {
  428. throw new ArgumentException("network");
  429. }
  430. ipnetwork = null;
  431. return;
  432. }
  433. if (byte.TryParse(args[1], out cidr))
  434. {
  435. IPNetwork.InternalParse(tryParse, args[0], cidr, out ipnetwork);
  436. return;
  437. }
  438. IPNetwork.InternalParse(tryParse, args[0], args[1], out ipnetwork);
  439. return;
  440. }
  441. /// <summary>
  442. /// 192.168.168.100 255.255.255.0
  443. ///
  444. /// Network : 192.168.168.0
  445. /// Netmask : 255.255.255.0
  446. /// Cidr : 24
  447. /// Start : 192.168.168.1
  448. /// End : 192.168.168.254
  449. /// Broadcast : 192.168.168.255
  450. /// </summary>
  451. /// <param name="ipaddress"></param>
  452. /// <param name="netmask"></param>
  453. /// <returns></returns>
  454. private static void InternalParse(bool tryParse, IPAddress ipaddress, IPAddress netmask, out IPNetwork ipnetwork)
  455. {
  456. if (ipaddress == null)
  457. {
  458. if (tryParse == false)
  459. {
  460. throw new ArgumentNullException("ipaddress");
  461. }
  462. ipnetwork = null;
  463. return;
  464. }
  465. if (netmask == null)
  466. {
  467. if (tryParse == false)
  468. {
  469. throw new ArgumentNullException("netmask");
  470. }
  471. ipnetwork = null;
  472. return;
  473. }
  474. BigInteger uintIpAddress = IPNetwork.ToBigInteger(ipaddress);
  475. byte? cidr2 = null;
  476. bool parsed = IPNetwork.TryToCidr(netmask, out cidr2);
  477. if (parsed == false)
  478. {
  479. if (tryParse == false)
  480. {
  481. throw new ArgumentException("netmask");
  482. }
  483. ipnetwork = null;
  484. return;
  485. }
  486. byte cidr = (byte)cidr2;
  487. IPNetwork ipnet = new IPNetwork(uintIpAddress, ipaddress.AddressFamily, cidr);
  488. ipnetwork = ipnet;
  489. return;
  490. }
  491. /// <summary>
  492. /// 192.168.168.100/24
  493. ///
  494. /// Network : 192.168.168.0
  495. /// Netmask : 255.255.255.0
  496. /// Cidr : 24
  497. /// Start : 192.168.168.1
  498. /// End : 192.168.168.254
  499. /// Broadcast : 192.168.168.255
  500. /// </summary>
  501. /// <param name="ipaddress"></param>
  502. /// <param name="cidr"></param>
  503. /// <returns></returns>
  504. private static void InternalParse(bool tryParse, string ipaddress, byte cidr, out IPNetwork ipnetwork)
  505. {
  506. if (string.IsNullOrEmpty(ipaddress))
  507. {
  508. if (tryParse == false)
  509. {
  510. throw new ArgumentNullException("ipaddress");
  511. }
  512. ipnetwork = null;
  513. return;
  514. }
  515. IPAddress ip = null;
  516. bool ipaddressParsed = IPAddress.TryParse(ipaddress, out ip);
  517. if (ipaddressParsed == false)
  518. {
  519. if (tryParse == false)
  520. {
  521. throw new ArgumentException("ipaddress");
  522. }
  523. ipnetwork = null;
  524. return;
  525. }
  526. IPAddress mask = null;
  527. bool parsedNetmask = IPNetwork.TryToNetmask(cidr, ip.AddressFamily, out mask);
  528. if (parsedNetmask == false)
  529. {
  530. if (tryParse == false)
  531. {
  532. throw new ArgumentException("cidr");
  533. }
  534. ipnetwork = null;
  535. return;
  536. }
  537. IPNetwork.InternalParse(tryParse, ip, mask, out ipnetwork);
  538. }
  539. #endregion
  540. #region converters
  541. #region ToUint
  542. /// <summary>
  543. /// Convert an ipadress to decimal
  544. /// 0.0.0.0 -> 0
  545. /// 0.0.1.0 -> 256
  546. /// </summary>
  547. /// <param name="ipaddress"></param>
  548. /// <returns></returns>
  549. public static BigInteger ToBigInteger(IPAddress ipaddress)
  550. {
  551. BigInteger? uintIpAddress = null;
  552. IPNetwork.InternalToBigInteger(false, ipaddress, out uintIpAddress);
  553. return (BigInteger)uintIpAddress;
  554. }
  555. /// <summary>
  556. /// Convert an ipadress to decimal
  557. /// 0.0.0.0 -> 0
  558. /// 0.0.1.0 -> 256
  559. /// </summary>
  560. /// <param name="ipaddress"></param>
  561. /// <returns></returns>
  562. public static bool TryToBigInteger(IPAddress ipaddress, out BigInteger? uintIpAddress)
  563. {
  564. BigInteger? uintIpAddress2 = null;
  565. IPNetwork.InternalToBigInteger(true, ipaddress, out uintIpAddress2);
  566. bool parsed = (uintIpAddress2 != null);
  567. uintIpAddress = uintIpAddress2;
  568. return parsed;
  569. }
  570. #if TRAVISCI
  571. public
  572. #else
  573. internal
  574. #endif
  575. static void InternalToBigInteger(bool tryParse, IPAddress ipaddress, out BigInteger? uintIpAddress)
  576. {
  577. if (ipaddress == null)
  578. {
  579. if (tryParse == false)
  580. {
  581. throw new ArgumentNullException("ipaddress");
  582. }
  583. uintIpAddress = null;
  584. return;
  585. }
  586. byte[] bytes = ipaddress.GetAddressBytes();
  587. /// 20180217 lduchosal
  588. /// code impossible to reach, GetAddressBytes returns either 4 or 16 bytes length addresses
  589. /// if (bytes.Length != 4 && bytes.Length != 16) {
  590. /// if (tryParse == false) {
  591. /// throw new ArgumentException("bytes");
  592. /// }
  593. /// uintIpAddress = null;
  594. /// return;
  595. /// }
  596. Array.Reverse(bytes);
  597. var unsigned = new List<byte>(bytes);
  598. unsigned.Add(0);
  599. uintIpAddress = new BigInteger(unsigned.ToArray());
  600. return;
  601. }
  602. /// <summary>
  603. /// Convert a cidr to BigInteger netmask
  604. /// </summary>
  605. /// <param name="cidr"></param>
  606. /// <returns></returns>
  607. public static BigInteger ToUint(byte cidr, AddressFamily family)
  608. {
  609. BigInteger? uintNetmask = null;
  610. IPNetwork.InternalToBigInteger(false, cidr, family, out uintNetmask);
  611. return (BigInteger)uintNetmask;
  612. }
  613. /// <summary>
  614. /// Convert a cidr to uint netmask
  615. /// </summary>
  616. /// <param name="cidr"></param>
  617. /// <returns></returns>
  618. public static bool TryToUint(byte cidr, AddressFamily family, out BigInteger? uintNetmask)
  619. {
  620. BigInteger? uintNetmask2 = null;
  621. IPNetwork.InternalToBigInteger(true, cidr, family, out uintNetmask2);
  622. bool parsed = (uintNetmask2 != null);
  623. uintNetmask = uintNetmask2;
  624. return parsed;
  625. }
  626. /// <summary>
  627. /// Convert a cidr to uint netmask
  628. /// </summary>
  629. /// <param name="cidr"></param>
  630. /// <returns></returns>
  631. #if TRAVISCI
  632. public
  633. #else
  634. internal
  635. #endif
  636. static void InternalToBigInteger(bool tryParse, byte cidr, AddressFamily family, out BigInteger? uintNetmask)
  637. {
  638. if (family == AddressFamily.InterNetwork && cidr > 32)
  639. {
  640. if (tryParse == false)
  641. {
  642. throw new ArgumentOutOfRangeException("cidr");
  643. }
  644. uintNetmask = null;
  645. return;
  646. }
  647. if (family == AddressFamily.InterNetworkV6 && cidr > 128)
  648. {
  649. if (tryParse == false)
  650. {
  651. throw new ArgumentOutOfRangeException("cidr");
  652. }
  653. uintNetmask = null;
  654. return;
  655. }
  656. if (family != AddressFamily.InterNetwork
  657. && family != AddressFamily.InterNetworkV6)
  658. {
  659. if (tryParse == false)
  660. {
  661. throw new NotSupportedException(family.ToString());
  662. }
  663. uintNetmask = null;
  664. return;
  665. }
  666. if (family == AddressFamily.InterNetwork)
  667. {
  668. uintNetmask = cidr == 0 ? 0 : 0xffffffff << (32 - cidr);
  669. return;
  670. }
  671. BigInteger mask = new BigInteger(new byte[] {
  672. 0xff, 0xff, 0xff, 0xff,
  673. 0xff, 0xff, 0xff, 0xff,
  674. 0xff, 0xff, 0xff, 0xff,
  675. 0xff, 0xff, 0xff, 0xff,
  676. 0x00
  677. });
  678. BigInteger masked = cidr == 0 ? 0 : mask << (128 - cidr);
  679. byte[] m = masked.ToByteArray();
  680. byte[] bmask = new byte[17];
  681. int copy = m.Length > 16 ? 16 : m.Length;
  682. Array.Copy(m, 0, bmask, 0, copy);
  683. uintNetmask = new BigInteger(bmask);
  684. }
  685. #endregion
  686. #region ToCidr
  687. /// <summary>
  688. /// Convert netmask to CIDR
  689. /// 255.255.255.0 -> 24
  690. /// 255.255.0.0 -> 16
  691. /// 255.0.0.0 -> 8
  692. /// </summary>
  693. /// <param name="netmask"></param>
  694. /// <returns></returns>
  695. private static void InternalToCidr(bool tryParse, BigInteger netmask, AddressFamily family, out byte? cidr)
  696. {
  697. if (!IPNetwork.InternalValidNetmask(netmask, family))
  698. {
  699. if (tryParse == false)
  700. {
  701. throw new ArgumentException("netmask");
  702. }
  703. cidr = null;
  704. return;
  705. }
  706. byte cidr2 = IPNetwork.BitsSet(netmask, family);
  707. cidr = cidr2;
  708. return;
  709. }
  710. /// <summary>
  711. /// Convert netmask to CIDR
  712. /// 255.255.255.0 -> 24
  713. /// 255.255.0.0 -> 16
  714. /// 255.0.0.0 -> 8
  715. /// </summary>
  716. /// <param name="netmask"></param>
  717. /// <returns></returns>
  718. public static byte ToCidr(IPAddress netmask)
  719. {
  720. byte? cidr = null;
  721. IPNetwork.InternalToCidr(false, netmask, out cidr);
  722. return (byte)cidr;
  723. }
  724. /// <summary>
  725. /// Convert netmask to CIDR
  726. /// 255.255.255.0 -> 24
  727. /// 255.255.0.0 -> 16
  728. /// 255.0.0.0 -> 8
  729. /// </summary>
  730. /// <param name="netmask"></param>
  731. /// <returns></returns>
  732. public static bool TryToCidr(IPAddress netmask, out byte? cidr)
  733. {
  734. byte? cidr2 = null;
  735. IPNetwork.InternalToCidr(true, netmask, out cidr2);
  736. bool parsed = (cidr2 != null);
  737. cidr = cidr2;
  738. return parsed;
  739. }
  740. private static void InternalToCidr(bool tryParse, IPAddress netmask, out byte? cidr)
  741. {
  742. if (netmask == null)
  743. {
  744. if (tryParse == false)
  745. {
  746. throw new ArgumentNullException("netmask");
  747. }
  748. cidr = null;
  749. return;
  750. }
  751. BigInteger? uintNetmask2 = null;
  752. bool parsed = IPNetwork.TryToBigInteger(netmask, out uintNetmask2);
  753. /// 20180217 lduchosal
  754. /// impossible to reach code.
  755. /// if (parsed == false) {
  756. /// if (tryParse == false) {
  757. /// throw new ArgumentException("netmask");
  758. /// }
  759. /// cidr = null;
  760. /// return;
  761. /// }
  762. BigInteger uintNetmask = (BigInteger)uintNetmask2;
  763. byte? cidr2 = null;
  764. IPNetwork.InternalToCidr(tryParse, uintNetmask, netmask.AddressFamily, out cidr2);
  765. cidr = cidr2;
  766. return;
  767. }
  768. #endregion
  769. #region ToNetmask
  770. /// <summary>
  771. /// Convert CIDR to netmask
  772. /// 24 -> 255.255.255.0
  773. /// 16 -> 255.255.0.0
  774. /// 8 -> 255.0.0.0
  775. /// </summary>
  776. /// <see cref="http://snipplr.com/view/15557/cidr-class-for-ipv4/"/>
  777. /// <param name="cidr"></param>
  778. /// <returns></returns>
  779. public static IPAddress ToNetmask(byte cidr, AddressFamily family)
  780. {
  781. IPAddress netmask = null;
  782. IPNetwork.InternalToNetmask(false, cidr, family, out netmask);
  783. return netmask;
  784. }
  785. /// <summary>
  786. /// Convert CIDR to netmask
  787. /// 24 -> 255.255.255.0
  788. /// 16 -> 255.255.0.0
  789. /// 8 -> 255.0.0.0
  790. /// </summary>
  791. /// <see cref="http://snipplr.com/view/15557/cidr-class-for-ipv4/"/>
  792. /// <param name="cidr"></param>
  793. /// <returns></returns>
  794. public static bool TryToNetmask(byte cidr, AddressFamily family, out IPAddress netmask)
  795. {
  796. IPAddress netmask2 = null;
  797. IPNetwork.InternalToNetmask(true, cidr, family, out netmask2);
  798. bool parsed = (netmask2 != null);
  799. netmask = netmask2;
  800. return parsed;
  801. }
  802. #if TRAVISCI
  803. public
  804. #else
  805. internal
  806. #endif
  807. static void InternalToNetmask(bool tryParse, byte cidr, AddressFamily family, out IPAddress netmask)
  808. {
  809. if (family != AddressFamily.InterNetwork
  810. && family != AddressFamily.InterNetworkV6)
  811. {
  812. if (tryParse == false)
  813. {
  814. throw new ArgumentException("family");
  815. }
  816. netmask = null;
  817. return;
  818. }
  819. /// 20180217 lduchosal
  820. /// impossible to reach code, byte cannot be negative :
  821. ///
  822. /// if (cidr < 0) {
  823. /// if (tryParse == false) {
  824. /// throw new ArgumentOutOfRangeException("cidr");
  825. /// }
  826. /// netmask = null;
  827. /// return;
  828. /// }
  829. int maxCidr = family == Sockets.AddressFamily.InterNetwork ? 32 : 128;
  830. if (cidr > maxCidr)
  831. {
  832. if (tryParse == false)
  833. {
  834. throw new ArgumentOutOfRangeException("cidr");
  835. }
  836. netmask = null;
  837. return;
  838. }
  839. BigInteger mask = IPNetwork.ToUint(cidr, family);
  840. IPAddress netmask2 = IPNetwork.ToIPAddress(mask, family);
  841. netmask = netmask2;
  842. return;
  843. }
  844. #endregion
  845. #endregion
  846. #region utils
  847. #region BitsSet
  848. /// <summary>
  849. /// Count bits set to 1 in netmask
  850. /// </summary>
  851. /// <see cref="http://stackoverflow.com/questions/109023/best-algorithm-to-count-the-number-of-set-bits-in-a-32-bit-integer"/>
  852. /// <param name="netmask"></param>
  853. /// <returns></returns>
  854. private static byte BitsSet(BigInteger netmask, AddressFamily family)
  855. {
  856. string s = netmask.ToBinaryString();
  857. return (byte)s.Replace("0", "")
  858. .ToCharArray()
  859. .Length;
  860. }
  861. /// <summary>
  862. /// Count bits set to 1 in netmask
  863. /// </summary>
  864. /// <param name="netmask"></param>
  865. /// <returns></returns>
  866. public static uint BitsSet(IPAddress netmask)
  867. {
  868. BigInteger uintNetmask = IPNetwork.ToBigInteger(netmask);
  869. uint bits = IPNetwork.BitsSet(uintNetmask, netmask.AddressFamily);
  870. return bits;
  871. }
  872. #endregion
  873. #region ValidNetmask
  874. /// <summary>
  875. /// return true if netmask is a valid netmask
  876. /// 255.255.255.0, 255.0.0.0, 255.255.240.0, ...
  877. /// </summary>
  878. /// <see cref="http://www.actionsnip.com/snippets/tomo_atlacatl/calculate-if-a-netmask-is-valid--as2-"/>
  879. /// <param name="netmask"></param>
  880. /// <returns></returns>
  881. public static bool ValidNetmask(IPAddress netmask)
  882. {
  883. if (netmask == null)
  884. {
  885. throw new ArgumentNullException("netmask");
  886. }
  887. BigInteger uintNetmask = IPNetwork.ToBigInteger(netmask);
  888. bool valid = IPNetwork.InternalValidNetmask(uintNetmask, netmask.AddressFamily);
  889. return valid;
  890. }
  891. #if TRAVISCI
  892. public
  893. #else
  894. internal
  895. #endif
  896. static bool InternalValidNetmask(BigInteger netmask, AddressFamily family)
  897. {
  898. if (family != AddressFamily.InterNetwork
  899. && family != AddressFamily.InterNetworkV6)
  900. {
  901. throw new ArgumentException("family");
  902. }
  903. var mask = family == AddressFamily.InterNetwork
  904. ? new BigInteger(0x0ffffffff)
  905. : new BigInteger(new byte[]{
  906. 0xff, 0xff, 0xff, 0xff,
  907. 0xff, 0xff, 0xff, 0xff,
  908. 0xff, 0xff, 0xff, 0xff,
  909. 0xff, 0xff, 0xff, 0xff,
  910. 0x00
  911. });
  912. BigInteger neg = ((~netmask) & (mask));
  913. bool isNetmask = ((neg + 1) & neg) == 0;
  914. return isNetmask;
  915. }
  916. #endregion
  917. #region ToIPAddress
  918. /// <summary>
  919. /// Transform a uint ipaddress into IPAddress object
  920. /// </summary>
  921. /// <param name="ipaddress"></param>
  922. /// <returns></returns>
  923. public static IPAddress ToIPAddress(BigInteger ipaddress, AddressFamily family)
  924. {
  925. int width = family == AddressFamily.InterNetwork ? 4 : 16;
  926. byte[] bytes = ipaddress.ToByteArray();
  927. byte[] bytes2 = new byte[width];
  928. int copy = bytes.Length > width ? width : bytes.Length;
  929. Array.Copy(bytes, 0, bytes2, 0, copy);
  930. Array.Reverse(bytes2);
  931. byte[] sized = Resize(bytes2, family);
  932. IPAddress ip = new IPAddress(sized);
  933. return ip;
  934. }
  935. #if TRAVISCI
  936. public
  937. #else
  938. internal
  939. #endif
  940. static byte[] Resize(byte[] bytes, AddressFamily family)
  941. {
  942. if (family != AddressFamily.InterNetwork
  943. && family != AddressFamily.InterNetworkV6)
  944. {
  945. throw new ArgumentException("family");
  946. }
  947. int width = family == AddressFamily.InterNetwork ? 4 : 16;
  948. if (bytes.Length > width)
  949. {
  950. throw new ArgumentException("bytes");
  951. }
  952. byte[] result = new byte[width];
  953. Array.Copy(bytes, 0, result, 0, bytes.Length);
  954. return result;
  955. }
  956. #endregion
  957. #endregion
  958. #region contains
  959. /// <summary>
  960. /// return true if ipaddress is contained in network
  961. /// </summary>
  962. /// <param name="ipaddress"></param>
  963. /// <returns></returns>
  964. public bool Contains(IPAddress ipaddress)
  965. {
  966. if (ipaddress == null)
  967. {
  968. throw new ArgumentNullException("ipaddress");
  969. }
  970. if (AddressFamily != ipaddress.AddressFamily)
  971. {
  972. return false;
  973. }
  974. BigInteger uintNetwork = _network;
  975. BigInteger uintBroadcast = _broadcast;
  976. BigInteger uintAddress = IPNetwork.ToBigInteger(ipaddress);
  977. bool contains = (uintAddress >= uintNetwork
  978. && uintAddress <= uintBroadcast);
  979. return contains;
  980. }
  981. [Obsolete("static Contains is deprecated, please use instance Contains.")]
  982. public static bool Contains(IPNetwork network, IPAddress ipaddress)
  983. {
  984. if (network == null)
  985. {
  986. throw new ArgumentNullException("network");
  987. }
  988. return network.Contains(ipaddress);
  989. }
  990. /// <summary>
  991. /// return true is network2 is fully contained in network
  992. /// </summary>
  993. /// <param name="network2"></param>
  994. /// <returns></returns>
  995. public bool Contains(IPNetwork network2)
  996. {
  997. if (network2 == null)
  998. {
  999. throw new ArgumentNullException("network2");
  1000. }
  1001. BigInteger uintNetwork = _network;
  1002. BigInteger uintBroadcast = _broadcast;
  1003. BigInteger uintFirst = network2._network;
  1004. BigInteger uintLast = network2._broadcast;
  1005. bool contains = (uintFirst >= uintNetwork
  1006. && uintLast <= uintBroadcast);
  1007. return contains;
  1008. }
  1009. [Obsolete("static Contains is deprecated, please use instance Contains.")]
  1010. public static bool Contains(IPNetwork network, IPNetwork network2)
  1011. {
  1012. if (network == null)
  1013. {
  1014. throw new ArgumentNullException("network");
  1015. }
  1016. return network.Contains(network2);
  1017. }
  1018. #endregion
  1019. #region overlap
  1020. /// <summary>
  1021. /// return true is network2 overlap network
  1022. /// </summary>
  1023. /// <param name="network2"></param>
  1024. /// <returns></returns>
  1025. public bool Overlap(IPNetwork network2)
  1026. {
  1027. if (network2 == null)
  1028. {
  1029. throw new ArgumentNullException("network2");
  1030. }
  1031. BigInteger uintNetwork = _network;
  1032. BigInteger uintBroadcast = _broadcast;
  1033. BigInteger uintFirst = network2._network;
  1034. BigInteger uintLast = network2._broadcast;
  1035. bool overlap =
  1036. (uintFirst >= uintNetwork && uintFirst <= uintBroadcast)
  1037. || (uintLast >= uintNetwork && uintLast <= uintBroadcast)
  1038. || (uintFirst <= uintNetwork && uintLast >= uintBroadcast)
  1039. || (uintFirst >= uintNetwork && uintLast <= uintBroadcast);
  1040. return overlap;
  1041. }
  1042. [Obsolete("static Overlap is deprecated, please use instance Overlap.")]
  1043. public static bool Overlap(IPNetwork network, IPNetwork network2)
  1044. {
  1045. if (network == null)
  1046. {
  1047. throw new ArgumentNullException("network");
  1048. }
  1049. return network.Overlap(network2);
  1050. }
  1051. #endregion
  1052. #region ToString
  1053. public override string ToString()
  1054. {
  1055. return string.Format("{0}/{1}", this.Network, this.Cidr);
  1056. }
  1057. #endregion
  1058. #region IANA block
  1059. private static readonly Lazy<IPNetwork> _iana_ablock_reserved = new Lazy<IPNetwork>(() => IPNetwork.Parse("10.0.0.0/8"));
  1060. private static readonly Lazy<IPNetwork> _iana_bblock_reserved = new Lazy<IPNetwork>(() => IPNetwork.Parse("172.16.0.0/12"));
  1061. private static readonly Lazy<IPNetwork> _iana_cblock_reserved = new Lazy<IPNetwork>(() => IPNetwork.Parse("192.168.0.0/16"));
  1062. /// <summary>
  1063. /// 10.0.0.0/8
  1064. /// </summary>
  1065. /// <returns></returns>
  1066. public static IPNetwork IANA_ABLK_RESERVED1
  1067. {
  1068. get
  1069. {
  1070. return _iana_ablock_reserved.Value;
  1071. }
  1072. }
  1073. /// <summary>
  1074. /// 172.12.0.0/12
  1075. /// </summary>
  1076. /// <returns></returns>
  1077. public static IPNetwork IANA_BBLK_RESERVED1
  1078. {
  1079. get
  1080. {
  1081. return _iana_bblock_reserved.Value;
  1082. }
  1083. }
  1084. /// <summary>
  1085. /// 192.168.0.0/16
  1086. /// </summary>
  1087. /// <returns></returns>
  1088. public static IPNetwork IANA_CBLK_RESERVED1
  1089. {
  1090. get
  1091. {
  1092. return _iana_cblock_reserved.Value;
  1093. }
  1094. }
  1095. /// <summary>
  1096. /// return true if ipaddress is contained in
  1097. /// IANA_ABLK_RESERVED1, IANA_BBLK_RESERVED1, IANA_CBLK_RESERVED1
  1098. /// </summary>
  1099. /// <param name="ipaddress"></param>
  1100. /// <returns></returns>
  1101. public static bool IsIANAReserved(IPAddress ipaddress)
  1102. {
  1103. if (ipaddress == null)
  1104. {
  1105. throw new ArgumentNullException("ipaddress");
  1106. }
  1107. return IPNetwork.IANA_ABLK_RESERVED1.Contains(ipaddress)
  1108. || IPNetwork.IANA_BBLK_RESERVED1.Contains(ipaddress)
  1109. || IPNetwork.IANA_CBLK_RESERVED1.Contains(ipaddress);
  1110. }
  1111. /// <summary>
  1112. /// return true if ipnetwork is contained in
  1113. /// IANA_ABLK_RESERVED1, IANA_BBLK_RESERVED1, IANA_CBLK_RESERVED1
  1114. /// </summary>
  1115. /// <returns></returns>
  1116. public bool IsIANAReserved()
  1117. {
  1118. return IPNetwork.IANA_ABLK_RESERVED1.Contains(this)
  1119. || IPNetwork.IANA_BBLK_RESERVED1.Contains(this)
  1120. || IPNetwork.IANA_CBLK_RESERVED1.Contains(this);
  1121. }
  1122. [Obsolete("static IsIANAReserved is deprecated, please use instance IsIANAReserved.")]
  1123. public static bool IsIANAReserved(IPNetwork ipnetwork)
  1124. {
  1125. if (ipnetwork == null)
  1126. {
  1127. throw new ArgumentNullException("ipnetwork");
  1128. }
  1129. return ipnetwork.IsIANAReserved();
  1130. }
  1131. #endregion
  1132. #region Subnet
  1133. /// <summary>
  1134. /// Subnet a network into multiple nets of cidr mask
  1135. /// Subnet 192.168.0.0/24 into cidr 25 gives 192.168.0.0/25, 192.168.0.128/25
  1136. /// Subnet 10.0.0.0/8 into cidr 9 gives 10.0.0.0/9, 10.128.0.0/9
  1137. /// </summary>
  1138. /// <param name="cidr"></param>
  1139. /// <returns></returns>
  1140. public IPNetworkCollection Subnet(byte cidr)
  1141. {
  1142. IPNetworkCollection ipnetworkCollection = null;
  1143. IPNetwork.InternalSubnet(false, this, cidr, out ipnetworkCollection);
  1144. return ipnetworkCollection;
  1145. }
  1146. [Obsolete("static Subnet is deprecated, please use instance Subnet.")]
  1147. public static IPNetworkCollection Subnet(IPNetwork network, byte cidr)
  1148. {
  1149. if (network == null)
  1150. {
  1151. throw new ArgumentNullException("network");
  1152. }
  1153. return network.Subnet(cidr);
  1154. }
  1155. /// <summary>
  1156. /// Subnet a network into multiple nets of cidr mask
  1157. /// Subnet 192.168.0.0/24 into cidr 25 gives 192.168.0.0/25, 192.168.0.128/25
  1158. /// Subnet 10.0.0.0/8 into cidr 9 gives 10.0.0.0/9, 10.128.0.0/9
  1159. /// </summary>
  1160. /// <param name="cidr"></param>
  1161. /// <returns></returns>
  1162. public bool TrySubnet(byte cidr, out IPNetworkCollection ipnetworkCollection)
  1163. {
  1164. IPNetworkCollection inc = null;
  1165. IPNetwork.InternalSubnet(true, this, cidr, out inc);
  1166. if (inc == null)
  1167. {
  1168. ipnetworkCollection = null;
  1169. return false;
  1170. }
  1171. ipnetworkCollection = inc;
  1172. return true;
  1173. }
  1174. [Obsolete("static TrySubnet is deprecated, please use instance TrySubnet.")]
  1175. public static bool TrySubnet(IPNetwork network, byte cidr, out IPNetworkCollection ipnetworkCollection)
  1176. {
  1177. if (network == null)
  1178. {
  1179. throw new ArgumentNullException("network");
  1180. }
  1181. return network.TrySubnet(cidr, out ipnetworkCollection);
  1182. }
  1183. #if TRAVISCI
  1184. public
  1185. #else
  1186. internal
  1187. #endif
  1188. static void InternalSubnet(bool trySubnet, IPNetwork network, byte cidr, out IPNetworkCollection ipnetworkCollection)
  1189. {
  1190. if (network == null)
  1191. {
  1192. if (trySubnet == false)
  1193. {
  1194. throw new ArgumentNullException("network");
  1195. }
  1196. ipnetworkCollection = null;
  1197. return;
  1198. }
  1199. int maxCidr = network._family == Sockets.AddressFamily.InterNetwork ? 32 : 128;
  1200. if (cidr > maxCidr)
  1201. {
  1202. if (trySubnet == false)
  1203. {
  1204. throw new ArgumentOutOfRangeException("cidr");
  1205. }
  1206. ipnetworkCollection = null;
  1207. return;
  1208. }
  1209. if (cidr < network.Cidr)
  1210. {
  1211. if (trySubnet == false)
  1212. {
  1213. throw new ArgumentException("cidr");
  1214. }
  1215. ipnetworkCollection = null;
  1216. return;
  1217. }
  1218. ipnetworkCollection = new IPNetworkCollection(network, cidr);
  1219. return;
  1220. }
  1221. #endregion
  1222. #region Supernet
  1223. /// <summary>
  1224. /// Supernet two consecutive cidr equal subnet into a single one
  1225. /// 192.168.0.0/24 + 192.168.1.0/24 = 192.168.0.0/23
  1226. /// 10.1.0.0/16 + 10.0.0.0/16 = 10.0.0.0/15
  1227. /// 192.168.0.0/24 + 192.168.0.0/25 = 192.168.0.0/24
  1228. /// </summary>
  1229. /// <param name="network2"></param>
  1230. /// <returns></returns>
  1231. public IPNetwork Supernet(IPNetwork network2)
  1232. {
  1233. IPNetwork supernet = null;
  1234. IPNetwork.InternalSupernet(false, this, network2, out supernet);
  1235. return supernet;
  1236. }
  1237. [Obsolete("static Supernet is deprecated, please use instance Supernet.")]
  1238. public static IPNetwork Supernet(IPNetwork network, IPNetwork network2)
  1239. {
  1240. return network.Supernet(network2);
  1241. }
  1242. /// <summary>
  1243. /// Try to supernet two consecutive cidr equal subnet into a single one
  1244. /// 192.168.0.0/24 + 192.168.1.0/24 = 192.168.0.0/23
  1245. /// 10.1.0.0/16 + 10.0.0.0/16 = 10.0.0.0/15
  1246. /// 192.168.0.0/24 + 192.168.0.0/25 = 192.168.0.0/24
  1247. /// </summary>
  1248. /// <param name="network2"></param>
  1249. /// <returns></returns>
  1250. public bool TrySupernet(IPNetwork network2, out IPNetwork supernet)
  1251. {
  1252. IPNetwork outSupernet = null;
  1253. IPNetwork.InternalSupernet(true, this, network2, out outSupernet);
  1254. bool parsed = (outSupernet != null);
  1255. supernet = outSupernet;
  1256. return parsed;
  1257. }
  1258. [Obsolete("static TrySupernet is deprecated, please use instance TrySupernet.")]
  1259. public static bool TrySupernet(IPNetwork network, IPNetwork network2, out IPNetwork supernet)
  1260. {
  1261. if (network == null)
  1262. {
  1263. throw new ArgumentNullException("network");
  1264. }
  1265. return network.TrySupernet(network2, out supernet);
  1266. }
  1267. #if TRAVISCI
  1268. public
  1269. #else
  1270. internal
  1271. #endif
  1272. static void InternalSupernet(bool trySupernet, IPNetwork network1, IPNetwork network2, out IPNetwork supernet)
  1273. {
  1274. if (network1 == null)
  1275. {
  1276. if (trySupernet == false)
  1277. {
  1278. throw new ArgumentNullException("network1");
  1279. }
  1280. supernet = null;
  1281. return;
  1282. }
  1283. if (network2 == null)
  1284. {
  1285. if (trySupernet == false)
  1286. {
  1287. throw new ArgumentNullException("network2");
  1288. }
  1289. supernet = null;
  1290. return;
  1291. }
  1292. if (network1.Contains(network2))
  1293. {
  1294. supernet = new IPNetwork(network1._network, network1._family, network1.Cidr);
  1295. return;
  1296. }
  1297. if (network2.Contains(network1))
  1298. {
  1299. supernet = new IPNetwork(network2._network, network2._family, network2.Cidr);
  1300. return;
  1301. }
  1302. if (network1._cidr != network2._cidr)
  1303. {
  1304. if (trySupernet == false)
  1305. {
  1306. throw new ArgumentException("cidr");
  1307. }
  1308. supernet = null;
  1309. return;
  1310. }
  1311. IPNetwork first = (network1._network < network2._network) ? network1 : network2;
  1312. IPNetwork last = (network1._network > network2._network) ? network1 : network2;
  1313. /// Starting from here :
  1314. /// network1 and network2 have the same cidr,
  1315. /// network1 does not contain network2,
  1316. /// network2 does not contain network1,
  1317. /// first is the lower subnet
  1318. /// last is the higher subnet
  1319. if ((first._broadcast + 1) != last._network)
  1320. {
  1321. if (trySupernet == false)
  1322. {
  1323. throw new ArgumentOutOfRangeException("network");
  1324. }
  1325. supernet = null;
  1326. return;
  1327. }
  1328. BigInteger uintSupernet = first._network;
  1329. byte cidrSupernet = (byte)(first._cidr - 1);
  1330. IPNetwork networkSupernet = new IPNetwork(uintSupernet, first._family, cidrSupernet);
  1331. if (networkSupernet._network != first._network)
  1332. {
  1333. if (trySupernet == false)
  1334. {
  1335. throw new ArgumentException("network");
  1336. }
  1337. supernet = null;
  1338. return;
  1339. }
  1340. supernet = networkSupernet;
  1341. return;
  1342. }
  1343. #endregion
  1344. #region GetHashCode
  1345. public override int GetHashCode()
  1346. {
  1347. return string.Format("{0}|{1}|{2}",
  1348. this._ipaddress.GetHashCode(),
  1349. this._network.GetHashCode(),
  1350. this._cidr.GetHashCode()).GetHashCode();
  1351. }
  1352. #endregion
  1353. #region SupernetArray
  1354. /// <summary>
  1355. /// Supernet a list of subnet
  1356. /// 192.168.0.0/24 + 192.168.1.0/24 = 192.168.0.0/23
  1357. /// 192.168.0.0/24 + 192.168.1.0/24 + 192.168.2.0/24 + 192.168.3.0/24 = 192.168.0.0/22
  1358. /// </summary>
  1359. /// <param name="ipnetworks"></param>
  1360. /// <param name="supernet"></param>
  1361. /// <returns></returns>
  1362. public static IPNetwork[] Supernet(IPNetwork[] ipnetworks)
  1363. {
  1364. IPNetwork[] supernet;
  1365. InternalSupernet(false, ipnetworks, out supernet);
  1366. return supernet;
  1367. }
  1368. /// <summary>
  1369. /// Supernet a list of subnet
  1370. /// 192.168.0.0/24 + 192.168.1.0/24 = 192.168.0.0/23
  1371. /// 192.168.0.0/24 + 192.168.1.0/24 + 192.168.2.0/24 + 192.168.3.0/24 = 192.168.0.0/22
  1372. /// </summary>
  1373. /// <param name="ipnetworks"></param>
  1374. /// <param name="supernet"></param>
  1375. /// <returns></returns>
  1376. public static bool TrySupernet(IPNetwork[] ipnetworks, out IPNetwork[] supernet)
  1377. {
  1378. bool supernetted = InternalSupernet(true, ipnetworks, out supernet);
  1379. return supernetted;
  1380. }
  1381. #if TRAVISCI
  1382. public
  1383. #else
  1384. internal
  1385. #endif
  1386. static bool InternalSupernet(bool trySupernet, IPNetwork[] ipnetworks, out IPNetwork[] supernet)
  1387. {
  1388. if (ipnetworks == null)
  1389. {
  1390. if (trySupernet == false)
  1391. {
  1392. throw new ArgumentNullException("ipnetworks");
  1393. }
  1394. supernet = null;
  1395. return false;
  1396. }
  1397. if (ipnetworks.Length <= 0)
  1398. {
  1399. supernet = new IPNetwork[0];
  1400. return true;
  1401. }
  1402. List<IPNetwork> supernetted = new List<IPNetwork>();
  1403. List<IPNetwork> ipns = IPNetwork.Array2List(ipnetworks);
  1404. Stack<IPNetwork> current = IPNetwork.List2Stack(ipns);
  1405. int previousCount = 0;
  1406. int currentCount = current.Count;
  1407. while (previousCount != currentCount)
  1408. {
  1409. supernetted.Clear();
  1410. while (current.Count > 1)
  1411. {
  1412. IPNetwork ipn1 = current.Pop();
  1413. IPNetwork ipn2 = current.Peek();
  1414. IPNetwork outNetwork = null;
  1415. bool success = ipn1.TrySupernet(ipn2, out outNetwork);
  1416. if (success)
  1417. {
  1418. current.Pop();
  1419. current.Push(outNetwork);
  1420. }
  1421. else
  1422. {
  1423. supernetted.Add(ipn1);
  1424. }
  1425. }
  1426. if (current.Count == 1)
  1427. {
  1428. supernetted.Add(current.Pop());
  1429. }
  1430. previousCount = currentCount;
  1431. currentCount = supernetted.Count;
  1432. current = IPNetwork.List2Stack(supernetted);
  1433. }
  1434. supernet = supernetted.ToArray();
  1435. return true;
  1436. }
  1437. private static Stack<IPNetwork> List2Stack(List<IPNetwork> list)
  1438. {
  1439. Stack<IPNetwork> stack = new Stack<IPNetwork>();
  1440. list.ForEach(new Action<IPNetwork>(
  1441. delegate (IPNetwork ipn)
  1442. {
  1443. stack.Push(ipn);
  1444. }
  1445. ));
  1446. return stack;
  1447. }
  1448. private static List<IPNetwork> Array2List(IPNetwork[] array)
  1449. {
  1450. List<IPNetwork> ipns = new List<IPNetwork>();
  1451. ipns.AddRange(array);
  1452. IPNetwork.RemoveNull(ipns);
  1453. ipns.Sort(new Comparison<IPNetwork>(
  1454. delegate (IPNetwork ipn1, IPNetwork ipn2)
  1455. {
  1456. int networkCompare = ipn1._network.CompareTo(ipn2._network);
  1457. if (networkCompare == 0)
  1458. {
  1459. int cidrCompare = ipn1._cidr.CompareTo(ipn2._cidr);
  1460. return cidrCompare;
  1461. }
  1462. return networkCompare;
  1463. }
  1464. ));
  1465. ipns.Reverse();
  1466. return ipns;
  1467. }
  1468. private static void RemoveNull(List<IPNetwork> ipns)
  1469. {
  1470. ipns.RemoveAll(new Predicate<IPNetwork>(
  1471. delegate (IPNetwork ipn)
  1472. {
  1473. if (ipn == null)
  1474. {
  1475. return true;
  1476. }
  1477. return false;
  1478. }
  1479. ));
  1480. }
  1481. #endregion
  1482. #region WideSubnet
  1483. public static IPNetwork WideSubnet(string start, string end)
  1484. {
  1485. if (string.IsNullOrEmpty(start))
  1486. {
  1487. throw new ArgumentNullException("start");
  1488. }
  1489. if (string.IsNullOrEmpty(end))
  1490. {
  1491. throw new ArgumentNullException("end");
  1492. }
  1493. IPAddress startIP;
  1494. if (!IPAddress.TryParse(start, out startIP))
  1495. {
  1496. throw new ArgumentException("start");
  1497. }
  1498. IPAddress endIP;
  1499. if (!IPAddress.TryParse(end, out endIP))
  1500. {
  1501. throw new ArgumentException("end");
  1502. }
  1503. if (startIP.AddressFamily != endIP.AddressFamily)
  1504. {
  1505. throw new NotSupportedException("MixedAddressFamily");
  1506. }
  1507. IPNetwork ipnetwork = new IPNetwork(0, startIP.AddressFamily, 0);
  1508. for (byte cidr = 32; cidr >= 0; cidr--)
  1509. {
  1510. IPNetwork wideSubnet = IPNetwork.Parse(start, cidr);
  1511. if (wideSubnet.Contains(endIP))
  1512. {
  1513. ipnetwork = wideSubnet;
  1514. break;
  1515. }
  1516. }
  1517. return ipnetwork;
  1518. }
  1519. public static bool TryWideSubnet(IPNetwork[] ipnetworks, out IPNetwork ipnetwork)
  1520. {
  1521. IPNetwork ipn = null;
  1522. IPNetwork.InternalWideSubnet(true, ipnetworks, out ipn);
  1523. if (ipn == null)
  1524. {
  1525. ipnetwork = null;
  1526. return false;
  1527. }
  1528. ipnetwork = ipn;
  1529. return true;
  1530. }
  1531. public static IPNetwork WideSubnet(IPNetwork[] ipnetworks)
  1532. {
  1533. IPNetwork ipn = null;
  1534. IPNetwork.InternalWideSubnet(false, ipnetworks, out ipn);
  1535. return ipn;
  1536. }
  1537. internal static void InternalWideSubnet(bool tryWide, IPNetwork[] ipnetworks, out IPNetwork ipnetwork)
  1538. {
  1539. if (ipnetworks == null)
  1540. {
  1541. if (tryWide == false)
  1542. {
  1543. throw new ArgumentNullException("ipnetworks");
  1544. }
  1545. ipnetwork = null;
  1546. return;
  1547. }
  1548. IPNetwork[] nnin = Array.FindAll<IPNetwork>(ipnetworks, new Predicate<IPNetwork>(
  1549. delegate (IPNetwork ipnet) {
  1550. return ipnet != null;
  1551. }
  1552. ));
  1553. if (nnin.Length <= 0)
  1554. {
  1555. if (tryWide == false)
  1556. {
  1557. throw new ArgumentException("ipnetworks");
  1558. }
  1559. ipnetwork = null;
  1560. return;
  1561. }
  1562. if (nnin.Length == 1)
  1563. {
  1564. IPNetwork ipn0 = nnin[0];
  1565. ipnetwork = ipn0;
  1566. return;
  1567. }
  1568. Array.Sort<IPNetwork>(nnin);
  1569. IPNetwork nnin0 = nnin[0];
  1570. BigInteger uintNnin0 = nnin0._ipaddress;
  1571. IPNetwork nninX = nnin[nnin.Length - 1];
  1572. IPAddress ipaddressX = nninX.Broadcast;
  1573. AddressFamily family = ipnetworks[0]._family;
  1574. foreach (var ipnx in ipnetworks)
  1575. {
  1576. if (ipnx._family != family)
  1577. {
  1578. throw new ArgumentException("MixedAddressFamily");
  1579. }
  1580. }
  1581. IPNetwork ipn = new IPNetwork(0, family, 0);
  1582. for (byte cidr = nnin0._cidr; cidr >= 0; cidr--)
  1583. {
  1584. IPNetwork wideSubnet = new IPNetwork(uintNnin0, family, cidr);
  1585. if (wideSubnet.Contains(ipaddressX))
  1586. {
  1587. ipn = wideSubnet;
  1588. break;
  1589. }
  1590. }
  1591. ipnetwork = ipn;
  1592. return;
  1593. }
  1594. #endregion
  1595. #region Print
  1596. /// <summary>
  1597. /// Print an ipnetwork in a clear representation string
  1598. /// </summary>
  1599. /// <returns></returns>
  1600. public string Print()
  1601. {
  1602. StringWriter sw = new StringWriter();
  1603. sw.WriteLine("IPNetwork : {0}", ToString());
  1604. sw.WriteLine("Network : {0}", Network);
  1605. sw.WriteLine("Netmask : {0}", Netmask);
  1606. sw.WriteLine("Cidr : {0}", Cidr);
  1607. sw.WriteLine("Broadcast : {0}", Broadcast);
  1608. sw.WriteLine("FirstUsable : {0}", FirstUsable);
  1609. sw.WriteLine("LastUsable : {0}", LastUsable);
  1610. sw.WriteLine("Usable : {0}", Usable);
  1611. return sw.ToString();
  1612. }
  1613. [Obsolete("static Print is deprecated, please use instance Print.")]
  1614. public static string Print(IPNetwork ipnetwork)
  1615. {
  1616. if (ipnetwork == null)
  1617. {
  1618. throw new ArgumentNullException("ipnetwork");
  1619. }
  1620. return ipnetwork.Print();
  1621. }
  1622. #endregion
  1623. #region TryGuessCidr
  1624. /// <summary>
  1625. ///
  1626. /// Class Leading bits Default netmask
  1627. /// A (CIDR /8) 00 255.0.0.0
  1628. /// A (CIDR /8) 01 255.0.0.0
  1629. /// B (CIDR /16) 10 255.255.0.0
  1630. /// C (CIDR /24) 11 255.255.255.0
  1631. ///
  1632. /// </summary>
  1633. /// <param name="ip"></param>
  1634. /// <param name="cidr"></param>
  1635. /// <returns></returns>
  1636. public static bool TryGuessCidr(string ip, out byte cidr)
  1637. {
  1638. IPAddress ipaddress = null;
  1639. bool parsed = IPAddress.TryParse(string.Format("{0}", ip), out ipaddress);
  1640. if (parsed == false)
  1641. {
  1642. cidr = 0;
  1643. return false;
  1644. }
  1645. if (ipaddress.AddressFamily == AddressFamily.InterNetworkV6)
  1646. {
  1647. cidr = 64;
  1648. return true;
  1649. }
  1650. BigInteger uintIPAddress = IPNetwork.ToBigInteger(ipaddress);
  1651. uintIPAddress = uintIPAddress >> 29;
  1652. if (uintIPAddress <= 3)
  1653. {
  1654. cidr = 8;
  1655. return true;
  1656. }
  1657. else if (uintIPAddress <= 5)
  1658. {
  1659. cidr = 16;
  1660. return true;
  1661. }
  1662. else if (uintIPAddress <= 6)
  1663. {
  1664. cidr = 24;
  1665. return true;
  1666. }
  1667. cidr = 0;
  1668. return false;
  1669. }
  1670. /// <summary>
  1671. /// Try to parse cidr. Have to be >= 0 and <= 32 or 128
  1672. /// </summary>
  1673. /// <param name="sidr"></param>
  1674. /// <param name="cidr"></param>
  1675. /// <returns></returns>
  1676. public static bool TryParseCidr(string sidr, AddressFamily family, out byte? cidr)
  1677. {
  1678. byte b = 0;
  1679. if (!byte.TryParse(sidr, out b))
  1680. {
  1681. cidr = null;
  1682. return false;
  1683. }
  1684. IPAddress netmask = null;
  1685. if (!IPNetwork.TryToNetmask(b, family, out netmask))
  1686. {
  1687. cidr = null;
  1688. return false;
  1689. }
  1690. cidr = b;
  1691. return true;
  1692. }
  1693. #endregion
  1694. #region ListIPAddress
  1695. [Obsolete("static ListIPAddress is deprecated, please use instance ListIPAddress.")]
  1696. public static IPAddressCollection ListIPAddress(IPNetwork ipnetwork)
  1697. {
  1698. return ipnetwork.ListIPAddress();
  1699. }
  1700. public IPAddressCollection ListIPAddress()
  1701. {
  1702. return new IPAddressCollection(this);
  1703. }
  1704. #endregion
  1705. /**
  1706. * Need a better way to do it
  1707. *
  1708. #region TrySubstractNetwork
  1709. public static bool TrySubstractNetwork(IPNetwork[] ipnetworks, IPNetwork substract, out IEnumerable<IPNetwork> result) {
  1710. if (ipnetworks == null) {
  1711. result = null;
  1712. return false;
  1713. }
  1714. if (ipnetworks.Length <= 0) {
  1715. result = null;
  1716. return false;
  1717. }
  1718. if (substract == null) {
  1719. result = null;
  1720. return false;
  1721. }
  1722. var results = new List<IPNetwork>();
  1723. foreach (var ipn in ipnetworks) {
  1724. if (!Overlap(ipn, substract)) {
  1725. results.Add(ipn);
  1726. continue;
  1727. }
  1728. var collection = ipn.Subnet(substract.Cidr);
  1729. var rtemp = new List<IPNetwork>();
  1730. foreach(var subnet in collection) {
  1731. if (subnet != substract) {
  1732. rtemp.Add(subnet);
  1733. }
  1734. }
  1735. var supernets = Supernet(rtemp.ToArray());
  1736. results.AddRange(supernets);
  1737. }
  1738. result = results;
  1739. return true;
  1740. }
  1741. #endregion
  1742. * **/
  1743. #region IComparable<IPNetwork> Members
  1744. public static Int32 Compare(IPNetwork left, IPNetwork right)
  1745. {
  1746. // two null IPNetworks are equal
  1747. if (ReferenceEquals(left, null) && ReferenceEquals(right, null)) return 0;
  1748. // two same IPNetworks are equal
  1749. if (ReferenceEquals(left, right)) return 0;
  1750. // null is always sorted first
  1751. if (ReferenceEquals(left, null)) return -1;
  1752. if (ReferenceEquals(right, null)) return 1;
  1753. // first test the network
  1754. var result = left._network.CompareTo(right._network);
  1755. if (result != 0) return result;
  1756. // then test the cidr
  1757. result = left._cidr.CompareTo(right._cidr);
  1758. return result;
  1759. }
  1760. public Int32 CompareTo(IPNetwork other)
  1761. {
  1762. return Compare(this, other);
  1763. }
  1764. public Int32 CompareTo(Object obj)
  1765. {
  1766. // null is at less
  1767. if (obj == null) return 1;
  1768. // convert to a proper Cidr object
  1769. var other = obj as IPNetwork;
  1770. // type problem if null
  1771. if (other == null)
  1772. {
  1773. throw new ArgumentException(
  1774. "The supplied parameter is an invalid type. Please supply an IPNetwork type.",
  1775. "obj");
  1776. }
  1777. // perform the comparision
  1778. return CompareTo(other);
  1779. }
  1780. #endregion
  1781. #region IEquatable<IPNetwork> Members
  1782. public static Boolean Equals(IPNetwork left, IPNetwork right)
  1783. {
  1784. return Compare(left, right) == 0;
  1785. }
  1786. public Boolean Equals(IPNetwork other)
  1787. {
  1788. return Equals(this, other);
  1789. }
  1790. public override Boolean Equals(Object obj)
  1791. {
  1792. return Equals(this, obj as IPNetwork);
  1793. }
  1794. #endregion
  1795. #region Operators
  1796. public static Boolean operator ==(IPNetwork left, IPNetwork right)
  1797. {
  1798. return Equals(left, right);
  1799. }
  1800. public static Boolean operator !=(IPNetwork left, IPNetwork right)
  1801. {
  1802. return !Equals(left, right);
  1803. }
  1804. public static Boolean operator <(IPNetwork left, IPNetwork right)
  1805. {
  1806. return Compare(left, right) < 0;
  1807. }
  1808. public static Boolean operator >(IPNetwork left, IPNetwork right)
  1809. {
  1810. return Compare(left, right) > 0;
  1811. }
  1812. #endregion
  1813. }
  1814. }