IPNetwork.cs 59 KB

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