IPNetwork.cs 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018
  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. return ipnet != null;
  1434. }
  1435. ));
  1436. if (nnin.Length <= 0)
  1437. {
  1438. if (tryWide == false)
  1439. {
  1440. throw new ArgumentException("ipnetworks");
  1441. }
  1442. ipnetwork = null;
  1443. return;
  1444. }
  1445. if (nnin.Length == 1)
  1446. {
  1447. IPNetwork ipn0 = nnin[0];
  1448. ipnetwork = ipn0;
  1449. return;
  1450. }
  1451. Array.Sort<IPNetwork>(nnin);
  1452. IPNetwork nnin0 = nnin[0];
  1453. BigInteger uintNnin0 = nnin0._ipaddress;
  1454. IPNetwork nninX = nnin[nnin.Length - 1];
  1455. IPAddress ipaddressX = nninX.Broadcast;
  1456. AddressFamily family = ipnetworks[0]._family;
  1457. foreach (var ipnx in ipnetworks)
  1458. {
  1459. if (ipnx._family != family)
  1460. {
  1461. throw new ArgumentException("MixedAddressFamily");
  1462. }
  1463. }
  1464. IPNetwork ipn = new IPNetwork(0, family, 0);
  1465. for (byte cidr = nnin0._cidr; cidr >= 0; cidr--)
  1466. {
  1467. IPNetwork wideSubnet = new IPNetwork(uintNnin0, family, cidr);
  1468. if (wideSubnet.Contains(ipaddressX))
  1469. {
  1470. ipn = wideSubnet;
  1471. break;
  1472. }
  1473. }
  1474. ipnetwork = ipn;
  1475. return;
  1476. }
  1477. #endregion
  1478. #region Print
  1479. /// <summary>
  1480. /// Print an ipnetwork in a clear representation string
  1481. /// </summary>
  1482. /// <returns></returns>
  1483. public string Print()
  1484. {
  1485. StringWriter sw = new StringWriter();
  1486. sw.WriteLine("IPNetwork : {0}", ToString());
  1487. sw.WriteLine("Network : {0}", Network);
  1488. sw.WriteLine("Netmask : {0}", Netmask);
  1489. sw.WriteLine("Cidr : {0}", Cidr);
  1490. sw.WriteLine("Broadcast : {0}", Broadcast);
  1491. sw.WriteLine("FirstUsable : {0}", FirstUsable);
  1492. sw.WriteLine("LastUsable : {0}", LastUsable);
  1493. sw.WriteLine("Usable : {0}", Usable);
  1494. return sw.ToString();
  1495. }
  1496. #endregion
  1497. #region TryGuessCidr
  1498. /// <summary>
  1499. ///
  1500. /// Class Leading bits Default netmask
  1501. /// A (CIDR /8) 00 255.0.0.0
  1502. /// A (CIDR /8) 01 255.0.0.0
  1503. /// B (CIDR /16) 10 255.255.0.0
  1504. /// C (CIDR /24) 11 255.255.255.0
  1505. ///
  1506. /// </summary>
  1507. /// <param name="ip"></param>
  1508. /// <param name="cidr"></param>
  1509. /// <returns></returns>
  1510. public static bool TryGuessCidr(string ip, out byte cidr)
  1511. {
  1512. IPAddress ipaddress = null;
  1513. bool parsed = IPAddress.TryParse(string.Format("{0}", ip), out ipaddress);
  1514. if (parsed == false)
  1515. {
  1516. cidr = 0;
  1517. return false;
  1518. }
  1519. if (ipaddress.AddressFamily == AddressFamily.InterNetworkV6)
  1520. {
  1521. cidr = 64;
  1522. return true;
  1523. }
  1524. BigInteger uintIPAddress = IPNetwork.ToBigInteger(ipaddress);
  1525. uintIPAddress = uintIPAddress >> 29;
  1526. if (uintIPAddress <= 3)
  1527. {
  1528. cidr = 8;
  1529. return true;
  1530. }
  1531. else if (uintIPAddress <= 5)
  1532. {
  1533. cidr = 16;
  1534. return true;
  1535. }
  1536. else if (uintIPAddress <= 6)
  1537. {
  1538. cidr = 24;
  1539. return true;
  1540. }
  1541. cidr = 0;
  1542. return false;
  1543. }
  1544. /// <summary>
  1545. /// Try to parse cidr. Have to be >= 0 and <= 32 or 128
  1546. /// </summary>
  1547. /// <param name="sidr"></param>
  1548. /// <param name="cidr"></param>
  1549. /// <returns></returns>
  1550. public static bool TryParseCidr(string sidr, AddressFamily family, out byte? cidr)
  1551. {
  1552. byte b = 0;
  1553. if (!byte.TryParse(sidr, out b))
  1554. {
  1555. cidr = null;
  1556. return false;
  1557. }
  1558. IPAddress netmask = null;
  1559. if (!IPNetwork.TryToNetmask(b, family, out netmask))
  1560. {
  1561. cidr = null;
  1562. return false;
  1563. }
  1564. cidr = b;
  1565. return true;
  1566. }
  1567. #endregion
  1568. #region ListIPAddress
  1569. public IPAddressCollection ListIPAddress()
  1570. {
  1571. return new IPAddressCollection(this);
  1572. }
  1573. #endregion
  1574. /**
  1575. * Need a better way to do it
  1576. *
  1577. #region TrySubstractNetwork
  1578. public static bool TrySubstractNetwork(IPNetwork[] ipnetworks, IPNetwork substract, out IEnumerable<IPNetwork> result) {
  1579. if (ipnetworks == null) {
  1580. result = null;
  1581. return false;
  1582. }
  1583. if (ipnetworks.Length <= 0) {
  1584. result = null;
  1585. return false;
  1586. }
  1587. if (substract == null) {
  1588. result = null;
  1589. return false;
  1590. }
  1591. var results = new List<IPNetwork>();
  1592. foreach (var ipn in ipnetworks) {
  1593. if (!Overlap(ipn, substract)) {
  1594. results.Add(ipn);
  1595. continue;
  1596. }
  1597. var collection = ipn.Subnet(substract.Cidr);
  1598. var rtemp = new List<IPNetwork>();
  1599. foreach(var subnet in collection) {
  1600. if (subnet != substract) {
  1601. rtemp.Add(subnet);
  1602. }
  1603. }
  1604. var supernets = Supernet(rtemp.ToArray());
  1605. results.AddRange(supernets);
  1606. }
  1607. result = results;
  1608. return true;
  1609. }
  1610. #endregion
  1611. * **/
  1612. #region IComparable<IPNetwork> Members
  1613. public static int Compare(IPNetwork left, IPNetwork right)
  1614. {
  1615. // two null IPNetworks are equal
  1616. if (ReferenceEquals(left, null) && ReferenceEquals(right, null)) return 0;
  1617. // two same IPNetworks are equal
  1618. if (ReferenceEquals(left, right)) return 0;
  1619. // null is always sorted first
  1620. if (ReferenceEquals(left, null)) return -1;
  1621. if (ReferenceEquals(right, null)) return 1;
  1622. // first test the network
  1623. var result = left._network.CompareTo(right._network);
  1624. if (result != 0) return result;
  1625. // then test the cidr
  1626. result = left._cidr.CompareTo(right._cidr);
  1627. return result;
  1628. }
  1629. public int CompareTo(IPNetwork other)
  1630. {
  1631. return Compare(this, other);
  1632. }
  1633. public int CompareTo(object obj)
  1634. {
  1635. // null is at less
  1636. if (obj == null) return 1;
  1637. // convert to a proper Cidr object
  1638. var other = obj as IPNetwork;
  1639. // type problem if null
  1640. if (other == null)
  1641. {
  1642. throw new ArgumentException(
  1643. "The supplied parameter is an invalid type. Please supply an IPNetwork type.",
  1644. nameof(obj));
  1645. }
  1646. // perform the comparision
  1647. return CompareTo(other);
  1648. }
  1649. #endregion
  1650. #region IEquatable<IPNetwork> Members
  1651. public static bool Equals(IPNetwork left, IPNetwork right)
  1652. {
  1653. return Compare(left, right) == 0;
  1654. }
  1655. public bool Equals(IPNetwork other)
  1656. {
  1657. return Equals(this, other);
  1658. }
  1659. public override bool Equals(object obj)
  1660. {
  1661. return Equals(this, obj as IPNetwork);
  1662. }
  1663. #endregion
  1664. #region Operators
  1665. public static bool operator ==(IPNetwork left, IPNetwork right)
  1666. {
  1667. return Equals(left, right);
  1668. }
  1669. public static bool operator !=(IPNetwork left, IPNetwork right)
  1670. {
  1671. return !Equals(left, right);
  1672. }
  1673. public static bool operator <(IPNetwork left, IPNetwork right)
  1674. {
  1675. return Compare(left, right) < 0;
  1676. }
  1677. public static bool operator >(IPNetwork left, IPNetwork right)
  1678. {
  1679. return Compare(left, right) > 0;
  1680. }
  1681. #endregion
  1682. }
  1683. }