IPNetwork.cs 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068
  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. /// <summary>
  982. /// return true is network2 is fully contained in network
  983. /// </summary>
  984. /// <param name="network2"></param>
  985. /// <returns></returns>
  986. public bool Contains(IPNetwork network2)
  987. {
  988. if (network2 == null)
  989. {
  990. throw new ArgumentNullException("network2");
  991. }
  992. BigInteger uintNetwork = _network;
  993. BigInteger uintBroadcast = _broadcast;
  994. BigInteger uintFirst = network2._network;
  995. BigInteger uintLast = network2._broadcast;
  996. bool contains = (uintFirst >= uintNetwork
  997. && uintLast <= uintBroadcast);
  998. return contains;
  999. }
  1000. #endregion
  1001. #region overlap
  1002. /// <summary>
  1003. /// return true is network2 overlap network
  1004. /// </summary>
  1005. /// <param name="network2"></param>
  1006. /// <returns></returns>
  1007. public bool Overlap(IPNetwork network2)
  1008. {
  1009. if (network2 == null)
  1010. {
  1011. throw new ArgumentNullException("network2");
  1012. }
  1013. BigInteger uintNetwork = _network;
  1014. BigInteger uintBroadcast = _broadcast;
  1015. BigInteger uintFirst = network2._network;
  1016. BigInteger uintLast = network2._broadcast;
  1017. bool overlap =
  1018. (uintFirst >= uintNetwork && uintFirst <= uintBroadcast)
  1019. || (uintLast >= uintNetwork && uintLast <= uintBroadcast)
  1020. || (uintFirst <= uintNetwork && uintLast >= uintBroadcast)
  1021. || (uintFirst >= uintNetwork && uintLast <= uintBroadcast);
  1022. return overlap;
  1023. }
  1024. #endregion
  1025. #region ToString
  1026. public override string ToString()
  1027. {
  1028. return string.Format("{0}/{1}", this.Network, this.Cidr);
  1029. }
  1030. #endregion
  1031. #region IANA block
  1032. private static readonly Lazy<IPNetwork> _iana_ablock_reserved = new Lazy<IPNetwork>(() => IPNetwork.Parse("10.0.0.0/8"));
  1033. private static readonly Lazy<IPNetwork> _iana_bblock_reserved = new Lazy<IPNetwork>(() => IPNetwork.Parse("172.16.0.0/12"));
  1034. private static readonly Lazy<IPNetwork> _iana_cblock_reserved = new Lazy<IPNetwork>(() => IPNetwork.Parse("192.168.0.0/16"));
  1035. /// <summary>
  1036. /// 10.0.0.0/8
  1037. /// </summary>
  1038. /// <returns></returns>
  1039. public static IPNetwork IANA_ABLK_RESERVED1
  1040. {
  1041. get
  1042. {
  1043. return _iana_ablock_reserved.Value;
  1044. }
  1045. }
  1046. /// <summary>
  1047. /// 172.12.0.0/12
  1048. /// </summary>
  1049. /// <returns></returns>
  1050. public static IPNetwork IANA_BBLK_RESERVED1
  1051. {
  1052. get
  1053. {
  1054. return _iana_bblock_reserved.Value;
  1055. }
  1056. }
  1057. /// <summary>
  1058. /// 192.168.0.0/16
  1059. /// </summary>
  1060. /// <returns></returns>
  1061. public static IPNetwork IANA_CBLK_RESERVED1
  1062. {
  1063. get
  1064. {
  1065. return _iana_cblock_reserved.Value;
  1066. }
  1067. }
  1068. /// <summary>
  1069. /// return true if ipaddress is contained in
  1070. /// IANA_ABLK_RESERVED1, IANA_BBLK_RESERVED1, IANA_CBLK_RESERVED1
  1071. /// </summary>
  1072. /// <param name="ipaddress"></param>
  1073. /// <returns></returns>
  1074. public static bool IsIANAReserved(IPAddress ipaddress)
  1075. {
  1076. if (ipaddress == null)
  1077. {
  1078. throw new ArgumentNullException("ipaddress");
  1079. }
  1080. return IPNetwork.IANA_ABLK_RESERVED1.Contains(ipaddress)
  1081. || IPNetwork.IANA_BBLK_RESERVED1.Contains(ipaddress)
  1082. || IPNetwork.IANA_CBLK_RESERVED1.Contains(ipaddress);
  1083. }
  1084. /// <summary>
  1085. /// return true if ipnetwork is contained in
  1086. /// IANA_ABLK_RESERVED1, IANA_BBLK_RESERVED1, IANA_CBLK_RESERVED1
  1087. /// </summary>
  1088. /// <returns></returns>
  1089. public bool IsIANAReserved()
  1090. {
  1091. return IPNetwork.IANA_ABLK_RESERVED1.Contains(this)
  1092. || IPNetwork.IANA_BBLK_RESERVED1.Contains(this)
  1093. || IPNetwork.IANA_CBLK_RESERVED1.Contains(this);
  1094. }
  1095. #endregion
  1096. #region Subnet
  1097. /// <summary>
  1098. /// Subnet a network into multiple nets of cidr mask
  1099. /// Subnet 192.168.0.0/24 into cidr 25 gives 192.168.0.0/25, 192.168.0.128/25
  1100. /// Subnet 10.0.0.0/8 into cidr 9 gives 10.0.0.0/9, 10.128.0.0/9
  1101. /// </summary>
  1102. /// <param name="cidr"></param>
  1103. /// <returns></returns>
  1104. public IPNetworkCollection Subnet(byte cidr)
  1105. {
  1106. IPNetworkCollection ipnetworkCollection = null;
  1107. IPNetwork.InternalSubnet(false, this, cidr, out ipnetworkCollection);
  1108. return ipnetworkCollection;
  1109. }
  1110. /// <summary>
  1111. /// Subnet a network into multiple nets of cidr mask
  1112. /// Subnet 192.168.0.0/24 into cidr 25 gives 192.168.0.0/25, 192.168.0.128/25
  1113. /// Subnet 10.0.0.0/8 into cidr 9 gives 10.0.0.0/9, 10.128.0.0/9
  1114. /// </summary>
  1115. /// <param name="cidr"></param>
  1116. /// <returns></returns>
  1117. public bool TrySubnet(byte cidr, out IPNetworkCollection ipnetworkCollection)
  1118. {
  1119. IPNetworkCollection inc = null;
  1120. IPNetwork.InternalSubnet(true, this, cidr, out inc);
  1121. if (inc == null)
  1122. {
  1123. ipnetworkCollection = null;
  1124. return false;
  1125. }
  1126. ipnetworkCollection = inc;
  1127. return true;
  1128. }
  1129. #if TRAVISCI
  1130. public
  1131. #else
  1132. internal
  1133. #endif
  1134. static void InternalSubnet(bool trySubnet, IPNetwork network, byte cidr, out IPNetworkCollection ipnetworkCollection)
  1135. {
  1136. if (network == null)
  1137. {
  1138. if (trySubnet == false)
  1139. {
  1140. throw new ArgumentNullException("network");
  1141. }
  1142. ipnetworkCollection = null;
  1143. return;
  1144. }
  1145. int maxCidr = network._family == Sockets.AddressFamily.InterNetwork ? 32 : 128;
  1146. if (cidr > maxCidr)
  1147. {
  1148. if (trySubnet == false)
  1149. {
  1150. throw new ArgumentOutOfRangeException("cidr");
  1151. }
  1152. ipnetworkCollection = null;
  1153. return;
  1154. }
  1155. if (cidr < network.Cidr)
  1156. {
  1157. if (trySubnet == false)
  1158. {
  1159. throw new ArgumentException("cidr");
  1160. }
  1161. ipnetworkCollection = null;
  1162. return;
  1163. }
  1164. ipnetworkCollection = new IPNetworkCollection(network, cidr);
  1165. return;
  1166. }
  1167. #endregion
  1168. #region Supernet
  1169. /// <summary>
  1170. /// Supernet two consecutive cidr equal subnet into a single one
  1171. /// 192.168.0.0/24 + 192.168.1.0/24 = 192.168.0.0/23
  1172. /// 10.1.0.0/16 + 10.0.0.0/16 = 10.0.0.0/15
  1173. /// 192.168.0.0/24 + 192.168.0.0/25 = 192.168.0.0/24
  1174. /// </summary>
  1175. /// <param name="network2"></param>
  1176. /// <returns></returns>
  1177. public IPNetwork Supernet(IPNetwork network2)
  1178. {
  1179. IPNetwork supernet = null;
  1180. IPNetwork.InternalSupernet(false, this, network2, out supernet);
  1181. return supernet;
  1182. }
  1183. /// <summary>
  1184. /// Try to supernet two consecutive cidr equal subnet into a single one
  1185. /// 192.168.0.0/24 + 192.168.1.0/24 = 192.168.0.0/23
  1186. /// 10.1.0.0/16 + 10.0.0.0/16 = 10.0.0.0/15
  1187. /// 192.168.0.0/24 + 192.168.0.0/25 = 192.168.0.0/24
  1188. /// </summary>
  1189. /// <param name="network2"></param>
  1190. /// <returns></returns>
  1191. public bool TrySupernet(IPNetwork network2, out IPNetwork supernet)
  1192. {
  1193. IPNetwork outSupernet = null;
  1194. IPNetwork.InternalSupernet(true, this, network2, out outSupernet);
  1195. bool parsed = (outSupernet != null);
  1196. supernet = outSupernet;
  1197. return parsed;
  1198. }
  1199. #if TRAVISCI
  1200. public
  1201. #else
  1202. internal
  1203. #endif
  1204. static void InternalSupernet(bool trySupernet, IPNetwork network1, IPNetwork network2, out IPNetwork supernet)
  1205. {
  1206. if (network1 == null)
  1207. {
  1208. if (trySupernet == false)
  1209. {
  1210. throw new ArgumentNullException("network1");
  1211. }
  1212. supernet = null;
  1213. return;
  1214. }
  1215. if (network2 == null)
  1216. {
  1217. if (trySupernet == false)
  1218. {
  1219. throw new ArgumentNullException("network2");
  1220. }
  1221. supernet = null;
  1222. return;
  1223. }
  1224. if (network1.Contains(network2))
  1225. {
  1226. supernet = new IPNetwork(network1._network, network1._family, network1.Cidr);
  1227. return;
  1228. }
  1229. if (network2.Contains(network1))
  1230. {
  1231. supernet = new IPNetwork(network2._network, network2._family, network2.Cidr);
  1232. return;
  1233. }
  1234. if (network1._cidr != network2._cidr)
  1235. {
  1236. if (trySupernet == false)
  1237. {
  1238. throw new ArgumentException("cidr");
  1239. }
  1240. supernet = null;
  1241. return;
  1242. }
  1243. IPNetwork first = (network1._network < network2._network) ? network1 : network2;
  1244. IPNetwork last = (network1._network > network2._network) ? network1 : network2;
  1245. /// Starting from here :
  1246. /// network1 and network2 have the same cidr,
  1247. /// network1 does not contain network2,
  1248. /// network2 does not contain network1,
  1249. /// first is the lower subnet
  1250. /// last is the higher subnet
  1251. if ((first._broadcast + 1) != last._network)
  1252. {
  1253. if (trySupernet == false)
  1254. {
  1255. throw new ArgumentOutOfRangeException("network");
  1256. }
  1257. supernet = null;
  1258. return;
  1259. }
  1260. BigInteger uintSupernet = first._network;
  1261. byte cidrSupernet = (byte)(first._cidr - 1);
  1262. IPNetwork networkSupernet = new IPNetwork(uintSupernet, first._family, cidrSupernet);
  1263. if (networkSupernet._network != first._network)
  1264. {
  1265. if (trySupernet == false)
  1266. {
  1267. throw new ArgumentException("network");
  1268. }
  1269. supernet = null;
  1270. return;
  1271. }
  1272. supernet = networkSupernet;
  1273. return;
  1274. }
  1275. #endregion
  1276. #region GetHashCode
  1277. public override int GetHashCode()
  1278. {
  1279. return string.Format("{0}|{1}|{2}",
  1280. this._ipaddress.GetHashCode(),
  1281. this._network.GetHashCode(),
  1282. this._cidr.GetHashCode()).GetHashCode();
  1283. }
  1284. #endregion
  1285. #region SupernetArray
  1286. /// <summary>
  1287. /// Supernet a list of subnet
  1288. /// 192.168.0.0/24 + 192.168.1.0/24 = 192.168.0.0/23
  1289. /// 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
  1290. /// </summary>
  1291. /// <param name="ipnetworks"></param>
  1292. /// <param name="supernet"></param>
  1293. /// <returns></returns>
  1294. public static IPNetwork[] Supernet(IPNetwork[] ipnetworks)
  1295. {
  1296. IPNetwork[] supernet;
  1297. InternalSupernet(false, ipnetworks, out supernet);
  1298. return supernet;
  1299. }
  1300. /// <summary>
  1301. /// Supernet a list of subnet
  1302. /// 192.168.0.0/24 + 192.168.1.0/24 = 192.168.0.0/23
  1303. /// 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
  1304. /// </summary>
  1305. /// <param name="ipnetworks"></param>
  1306. /// <param name="supernet"></param>
  1307. /// <returns></returns>
  1308. public static bool TrySupernet(IPNetwork[] ipnetworks, out IPNetwork[] supernet)
  1309. {
  1310. bool supernetted = InternalSupernet(true, ipnetworks, out supernet);
  1311. return supernetted;
  1312. }
  1313. #if TRAVISCI
  1314. public
  1315. #else
  1316. internal
  1317. #endif
  1318. static bool InternalSupernet(bool trySupernet, IPNetwork[] ipnetworks, out IPNetwork[] supernet)
  1319. {
  1320. if (ipnetworks == null)
  1321. {
  1322. if (trySupernet == false)
  1323. {
  1324. throw new ArgumentNullException("ipnetworks");
  1325. }
  1326. supernet = null;
  1327. return false;
  1328. }
  1329. if (ipnetworks.Length <= 0)
  1330. {
  1331. supernet = new IPNetwork[0];
  1332. return true;
  1333. }
  1334. List<IPNetwork> supernetted = new List<IPNetwork>();
  1335. List<IPNetwork> ipns = IPNetwork.Array2List(ipnetworks);
  1336. Stack<IPNetwork> current = IPNetwork.List2Stack(ipns);
  1337. int previousCount = 0;
  1338. int currentCount = current.Count;
  1339. while (previousCount != currentCount)
  1340. {
  1341. supernetted.Clear();
  1342. while (current.Count > 1)
  1343. {
  1344. IPNetwork ipn1 = current.Pop();
  1345. IPNetwork ipn2 = current.Peek();
  1346. IPNetwork outNetwork = null;
  1347. bool success = ipn1.TrySupernet(ipn2, out outNetwork);
  1348. if (success)
  1349. {
  1350. current.Pop();
  1351. current.Push(outNetwork);
  1352. }
  1353. else
  1354. {
  1355. supernetted.Add(ipn1);
  1356. }
  1357. }
  1358. if (current.Count == 1)
  1359. {
  1360. supernetted.Add(current.Pop());
  1361. }
  1362. previousCount = currentCount;
  1363. currentCount = supernetted.Count;
  1364. current = IPNetwork.List2Stack(supernetted);
  1365. }
  1366. supernet = supernetted.ToArray();
  1367. return true;
  1368. }
  1369. private static Stack<IPNetwork> List2Stack(List<IPNetwork> list)
  1370. {
  1371. Stack<IPNetwork> stack = new Stack<IPNetwork>();
  1372. list.ForEach(new Action<IPNetwork>(
  1373. delegate (IPNetwork ipn)
  1374. {
  1375. stack.Push(ipn);
  1376. }
  1377. ));
  1378. return stack;
  1379. }
  1380. private static List<IPNetwork> Array2List(IPNetwork[] array)
  1381. {
  1382. List<IPNetwork> ipns = new List<IPNetwork>();
  1383. ipns.AddRange(array);
  1384. IPNetwork.RemoveNull(ipns);
  1385. ipns.Sort(new Comparison<IPNetwork>(
  1386. delegate (IPNetwork ipn1, IPNetwork ipn2)
  1387. {
  1388. int networkCompare = ipn1._network.CompareTo(ipn2._network);
  1389. if (networkCompare == 0)
  1390. {
  1391. int cidrCompare = ipn1._cidr.CompareTo(ipn2._cidr);
  1392. return cidrCompare;
  1393. }
  1394. return networkCompare;
  1395. }
  1396. ));
  1397. ipns.Reverse();
  1398. return ipns;
  1399. }
  1400. private static void RemoveNull(List<IPNetwork> ipns)
  1401. {
  1402. ipns.RemoveAll(new Predicate<IPNetwork>(
  1403. delegate (IPNetwork ipn)
  1404. {
  1405. if (ipn == null)
  1406. {
  1407. return true;
  1408. }
  1409. return false;
  1410. }
  1411. ));
  1412. }
  1413. #endregion
  1414. #region WideSubnet
  1415. public static IPNetwork WideSubnet(string start, string end)
  1416. {
  1417. if (string.IsNullOrEmpty(start))
  1418. {
  1419. throw new ArgumentNullException("start");
  1420. }
  1421. if (string.IsNullOrEmpty(end))
  1422. {
  1423. throw new ArgumentNullException("end");
  1424. }
  1425. IPAddress startIP;
  1426. if (!IPAddress.TryParse(start, out startIP))
  1427. {
  1428. throw new ArgumentException("start");
  1429. }
  1430. IPAddress endIP;
  1431. if (!IPAddress.TryParse(end, out endIP))
  1432. {
  1433. throw new ArgumentException("end");
  1434. }
  1435. if (startIP.AddressFamily != endIP.AddressFamily)
  1436. {
  1437. throw new NotSupportedException("MixedAddressFamily");
  1438. }
  1439. IPNetwork ipnetwork = new IPNetwork(0, startIP.AddressFamily, 0);
  1440. for (byte cidr = 32; cidr >= 0; cidr--)
  1441. {
  1442. IPNetwork wideSubnet = IPNetwork.Parse(start, cidr);
  1443. if (wideSubnet.Contains(endIP))
  1444. {
  1445. ipnetwork = wideSubnet;
  1446. break;
  1447. }
  1448. }
  1449. return ipnetwork;
  1450. }
  1451. public static bool TryWideSubnet(IPNetwork[] ipnetworks, out IPNetwork ipnetwork)
  1452. {
  1453. IPNetwork ipn = null;
  1454. IPNetwork.InternalWideSubnet(true, ipnetworks, out ipn);
  1455. if (ipn == null)
  1456. {
  1457. ipnetwork = null;
  1458. return false;
  1459. }
  1460. ipnetwork = ipn;
  1461. return true;
  1462. }
  1463. public static IPNetwork WideSubnet(IPNetwork[] ipnetworks)
  1464. {
  1465. IPNetwork ipn = null;
  1466. IPNetwork.InternalWideSubnet(false, ipnetworks, out ipn);
  1467. return ipn;
  1468. }
  1469. internal static void InternalWideSubnet(bool tryWide, IPNetwork[] ipnetworks, out IPNetwork ipnetwork)
  1470. {
  1471. if (ipnetworks == null)
  1472. {
  1473. if (tryWide == false)
  1474. {
  1475. throw new ArgumentNullException("ipnetworks");
  1476. }
  1477. ipnetwork = null;
  1478. return;
  1479. }
  1480. IPNetwork[] nnin = Array.FindAll<IPNetwork>(ipnetworks, new Predicate<IPNetwork>(
  1481. delegate (IPNetwork ipnet) {
  1482. return ipnet != null;
  1483. }
  1484. ));
  1485. if (nnin.Length <= 0)
  1486. {
  1487. if (tryWide == false)
  1488. {
  1489. throw new ArgumentException("ipnetworks");
  1490. }
  1491. ipnetwork = null;
  1492. return;
  1493. }
  1494. if (nnin.Length == 1)
  1495. {
  1496. IPNetwork ipn0 = nnin[0];
  1497. ipnetwork = ipn0;
  1498. return;
  1499. }
  1500. Array.Sort<IPNetwork>(nnin);
  1501. IPNetwork nnin0 = nnin[0];
  1502. BigInteger uintNnin0 = nnin0._ipaddress;
  1503. IPNetwork nninX = nnin[nnin.Length - 1];
  1504. IPAddress ipaddressX = nninX.Broadcast;
  1505. AddressFamily family = ipnetworks[0]._family;
  1506. foreach (var ipnx in ipnetworks)
  1507. {
  1508. if (ipnx._family != family)
  1509. {
  1510. throw new ArgumentException("MixedAddressFamily");
  1511. }
  1512. }
  1513. IPNetwork ipn = new IPNetwork(0, family, 0);
  1514. for (byte cidr = nnin0._cidr; cidr >= 0; cidr--)
  1515. {
  1516. IPNetwork wideSubnet = new IPNetwork(uintNnin0, family, cidr);
  1517. if (wideSubnet.Contains(ipaddressX))
  1518. {
  1519. ipn = wideSubnet;
  1520. break;
  1521. }
  1522. }
  1523. ipnetwork = ipn;
  1524. return;
  1525. }
  1526. #endregion
  1527. #region Print
  1528. /// <summary>
  1529. /// Print an ipnetwork in a clear representation string
  1530. /// </summary>
  1531. /// <returns></returns>
  1532. public string Print()
  1533. {
  1534. StringWriter sw = new StringWriter();
  1535. sw.WriteLine("IPNetwork : {0}", ToString());
  1536. sw.WriteLine("Network : {0}", Network);
  1537. sw.WriteLine("Netmask : {0}", Netmask);
  1538. sw.WriteLine("Cidr : {0}", Cidr);
  1539. sw.WriteLine("Broadcast : {0}", Broadcast);
  1540. sw.WriteLine("FirstUsable : {0}", FirstUsable);
  1541. sw.WriteLine("LastUsable : {0}", LastUsable);
  1542. sw.WriteLine("Usable : {0}", Usable);
  1543. return sw.ToString();
  1544. }
  1545. #endregion
  1546. #region TryGuessCidr
  1547. /// <summary>
  1548. ///
  1549. /// Class Leading bits Default netmask
  1550. /// A (CIDR /8) 00 255.0.0.0
  1551. /// A (CIDR /8) 01 255.0.0.0
  1552. /// B (CIDR /16) 10 255.255.0.0
  1553. /// C (CIDR /24) 11 255.255.255.0
  1554. ///
  1555. /// </summary>
  1556. /// <param name="ip"></param>
  1557. /// <param name="cidr"></param>
  1558. /// <returns></returns>
  1559. public static bool TryGuessCidr(string ip, out byte cidr)
  1560. {
  1561. IPAddress ipaddress = null;
  1562. bool parsed = IPAddress.TryParse(string.Format("{0}", ip), out ipaddress);
  1563. if (parsed == false)
  1564. {
  1565. cidr = 0;
  1566. return false;
  1567. }
  1568. if (ipaddress.AddressFamily == AddressFamily.InterNetworkV6)
  1569. {
  1570. cidr = 64;
  1571. return true;
  1572. }
  1573. BigInteger uintIPAddress = IPNetwork.ToBigInteger(ipaddress);
  1574. uintIPAddress = uintIPAddress >> 29;
  1575. if (uintIPAddress <= 3)
  1576. {
  1577. cidr = 8;
  1578. return true;
  1579. }
  1580. else if (uintIPAddress <= 5)
  1581. {
  1582. cidr = 16;
  1583. return true;
  1584. }
  1585. else if (uintIPAddress <= 6)
  1586. {
  1587. cidr = 24;
  1588. return true;
  1589. }
  1590. cidr = 0;
  1591. return false;
  1592. }
  1593. /// <summary>
  1594. /// Try to parse cidr. Have to be >= 0 and <= 32 or 128
  1595. /// </summary>
  1596. /// <param name="sidr"></param>
  1597. /// <param name="cidr"></param>
  1598. /// <returns></returns>
  1599. public static bool TryParseCidr(string sidr, AddressFamily family, out byte? cidr)
  1600. {
  1601. byte b = 0;
  1602. if (!byte.TryParse(sidr, out b))
  1603. {
  1604. cidr = null;
  1605. return false;
  1606. }
  1607. IPAddress netmask = null;
  1608. if (!IPNetwork.TryToNetmask(b, family, out netmask))
  1609. {
  1610. cidr = null;
  1611. return false;
  1612. }
  1613. cidr = b;
  1614. return true;
  1615. }
  1616. #endregion
  1617. #region ListIPAddress
  1618. public IPAddressCollection ListIPAddress()
  1619. {
  1620. return new IPAddressCollection(this);
  1621. }
  1622. #endregion
  1623. /**
  1624. * Need a better way to do it
  1625. *
  1626. #region TrySubstractNetwork
  1627. public static bool TrySubstractNetwork(IPNetwork[] ipnetworks, IPNetwork substract, out IEnumerable<IPNetwork> result) {
  1628. if (ipnetworks == null) {
  1629. result = null;
  1630. return false;
  1631. }
  1632. if (ipnetworks.Length <= 0) {
  1633. result = null;
  1634. return false;
  1635. }
  1636. if (substract == null) {
  1637. result = null;
  1638. return false;
  1639. }
  1640. var results = new List<IPNetwork>();
  1641. foreach (var ipn in ipnetworks) {
  1642. if (!Overlap(ipn, substract)) {
  1643. results.Add(ipn);
  1644. continue;
  1645. }
  1646. var collection = ipn.Subnet(substract.Cidr);
  1647. var rtemp = new List<IPNetwork>();
  1648. foreach(var subnet in collection) {
  1649. if (subnet != substract) {
  1650. rtemp.Add(subnet);
  1651. }
  1652. }
  1653. var supernets = Supernet(rtemp.ToArray());
  1654. results.AddRange(supernets);
  1655. }
  1656. result = results;
  1657. return true;
  1658. }
  1659. #endregion
  1660. * **/
  1661. #region IComparable<IPNetwork> Members
  1662. public static Int32 Compare(IPNetwork left, IPNetwork right)
  1663. {
  1664. // two null IPNetworks are equal
  1665. if (ReferenceEquals(left, null) && ReferenceEquals(right, null)) return 0;
  1666. // two same IPNetworks are equal
  1667. if (ReferenceEquals(left, right)) return 0;
  1668. // null is always sorted first
  1669. if (ReferenceEquals(left, null)) return -1;
  1670. if (ReferenceEquals(right, null)) return 1;
  1671. // first test the network
  1672. var result = left._network.CompareTo(right._network);
  1673. if (result != 0) return result;
  1674. // then test the cidr
  1675. result = left._cidr.CompareTo(right._cidr);
  1676. return result;
  1677. }
  1678. public Int32 CompareTo(IPNetwork other)
  1679. {
  1680. return Compare(this, other);
  1681. }
  1682. public Int32 CompareTo(Object obj)
  1683. {
  1684. // null is at less
  1685. if (obj == null) return 1;
  1686. // convert to a proper Cidr object
  1687. var other = obj as IPNetwork;
  1688. // type problem if null
  1689. if (other == null)
  1690. {
  1691. throw new ArgumentException(
  1692. "The supplied parameter is an invalid type. Please supply an IPNetwork type.",
  1693. "obj");
  1694. }
  1695. // perform the comparision
  1696. return CompareTo(other);
  1697. }
  1698. #endregion
  1699. #region IEquatable<IPNetwork> Members
  1700. public static Boolean Equals(IPNetwork left, IPNetwork right)
  1701. {
  1702. return Compare(left, right) == 0;
  1703. }
  1704. public Boolean Equals(IPNetwork other)
  1705. {
  1706. return Equals(this, other);
  1707. }
  1708. public override Boolean Equals(Object obj)
  1709. {
  1710. return Equals(this, obj as IPNetwork);
  1711. }
  1712. #endregion
  1713. #region Operators
  1714. public static Boolean operator ==(IPNetwork left, IPNetwork right)
  1715. {
  1716. return Equals(left, right);
  1717. }
  1718. public static Boolean operator !=(IPNetwork left, IPNetwork right)
  1719. {
  1720. return !Equals(left, right);
  1721. }
  1722. public static Boolean operator <(IPNetwork left, IPNetwork right)
  1723. {
  1724. return Compare(left, right) < 0;
  1725. }
  1726. public static Boolean operator >(IPNetwork left, IPNetwork right)
  1727. {
  1728. return Compare(left, right) > 0;
  1729. }
  1730. #endregion
  1731. }
  1732. }