IPNetwork.cs 58 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006
  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. var 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. var 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. var 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. var 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. var bmask = new BigInteger(mask);
  109. var 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. var 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. var uintIpAddress = IPNetwork.ToBigInteger(ipaddress);
  445. bool parsed = IPNetwork.TryToCidr(netmask, out var cidr2);
  446. if (parsed == false)
  447. {
  448. if (tryParse == false)
  449. {
  450. throw new ArgumentException("netmask");
  451. }
  452. ipnetwork = null;
  453. return;
  454. }
  455. byte cidr = (byte)cidr2;
  456. var ipnet = new IPNetwork(uintIpAddress, ipaddress.AddressFamily, cidr);
  457. ipnetwork = ipnet;
  458. return;
  459. }
  460. /// <summary>
  461. /// 192.168.168.100/24
  462. ///
  463. /// Network : 192.168.168.0
  464. /// Netmask : 255.255.255.0
  465. /// Cidr : 24
  466. /// Start : 192.168.168.1
  467. /// End : 192.168.168.254
  468. /// Broadcast : 192.168.168.255
  469. /// </summary>
  470. /// <param name="ipaddress"></param>
  471. /// <param name="cidr"></param>
  472. /// <returns></returns>
  473. private static void InternalParse(bool tryParse, string ipaddress, byte cidr, out IPNetwork ipnetwork)
  474. {
  475. if (string.IsNullOrEmpty(ipaddress))
  476. {
  477. if (tryParse == false)
  478. {
  479. throw new ArgumentNullException(nameof(ipaddress));
  480. }
  481. ipnetwork = null;
  482. return;
  483. }
  484. IPAddress ip = null;
  485. bool ipaddressParsed = IPAddress.TryParse(ipaddress, out ip);
  486. if (ipaddressParsed == false)
  487. {
  488. if (tryParse == false)
  489. {
  490. throw new ArgumentException("ipaddress");
  491. }
  492. ipnetwork = null;
  493. return;
  494. }
  495. IPAddress mask = null;
  496. bool parsedNetmask = IPNetwork.TryToNetmask(cidr, ip.AddressFamily, out mask);
  497. if (parsedNetmask == false)
  498. {
  499. if (tryParse == false)
  500. {
  501. throw new ArgumentException("cidr");
  502. }
  503. ipnetwork = null;
  504. return;
  505. }
  506. IPNetwork.InternalParse(tryParse, ip, mask, out ipnetwork);
  507. }
  508. #endregion
  509. #region converters
  510. #region ToUint
  511. /// <summary>
  512. /// Convert an ipadress to decimal
  513. /// 0.0.0.0 -> 0
  514. /// 0.0.1.0 -> 256
  515. /// </summary>
  516. /// <param name="ipaddress"></param>
  517. /// <returns></returns>
  518. public static BigInteger ToBigInteger(IPAddress ipaddress)
  519. {
  520. IPNetwork.InternalToBigInteger(false, ipaddress, out var uintIpAddress);
  521. return (BigInteger)uintIpAddress;
  522. }
  523. /// <summary>
  524. /// Convert an ipadress to decimal
  525. /// 0.0.0.0 -> 0
  526. /// 0.0.1.0 -> 256
  527. /// </summary>
  528. /// <param name="ipaddress"></param>
  529. /// <returns></returns>
  530. public static bool TryToBigInteger(IPAddress ipaddress, out BigInteger? uintIpAddress)
  531. {
  532. IPNetwork.InternalToBigInteger(true, ipaddress, out var uintIpAddress2);
  533. bool parsed = (uintIpAddress2 != null);
  534. uintIpAddress = uintIpAddress2;
  535. return parsed;
  536. }
  537. #if TRAVISCI
  538. public
  539. #else
  540. internal
  541. #endif
  542. static void InternalToBigInteger(bool tryParse, IPAddress ipaddress, out BigInteger? uintIpAddress)
  543. {
  544. if (ipaddress == null)
  545. {
  546. if (tryParse == false)
  547. {
  548. throw new ArgumentNullException(nameof(ipaddress));
  549. }
  550. uintIpAddress = null;
  551. return;
  552. }
  553. byte[] bytes = ipaddress.GetAddressBytes();
  554. /// 20180217 lduchosal
  555. /// code impossible to reach, GetAddressBytes returns either 4 or 16 bytes length addresses
  556. /// if (bytes.Length != 4 && bytes.Length != 16) {
  557. /// if (tryParse == false) {
  558. /// throw new ArgumentException("bytes");
  559. /// }
  560. /// uintIpAddress = null;
  561. /// return;
  562. /// }
  563. Array.Reverse(bytes);
  564. var unsigned = new List<byte>(bytes);
  565. unsigned.Add(0);
  566. uintIpAddress = new BigInteger(unsigned.ToArray());
  567. return;
  568. }
  569. /// <summary>
  570. /// Convert a cidr to BigInteger netmask
  571. /// </summary>
  572. /// <param name="cidr"></param>
  573. /// <returns></returns>
  574. public static BigInteger ToUint(byte cidr, AddressFamily family)
  575. {
  576. IPNetwork.InternalToBigInteger(false, cidr, family, out var uintNetmask);
  577. return (BigInteger)uintNetmask;
  578. }
  579. /// <summary>
  580. /// Convert a cidr to uint netmask
  581. /// </summary>
  582. /// <param name="cidr"></param>
  583. /// <returns></returns>
  584. public static bool TryToUint(byte cidr, AddressFamily family, out BigInteger? uintNetmask)
  585. {
  586. IPNetwork.InternalToBigInteger(true, cidr, family, out var uintNetmask2);
  587. bool parsed = (uintNetmask2 != null);
  588. uintNetmask = uintNetmask2;
  589. return parsed;
  590. }
  591. /// <summary>
  592. /// Convert a cidr to uint netmask
  593. /// </summary>
  594. /// <param name="cidr"></param>
  595. /// <returns></returns>
  596. #if TRAVISCI
  597. public
  598. #else
  599. internal
  600. #endif
  601. static void InternalToBigInteger(bool tryParse, byte cidr, AddressFamily family, out BigInteger? uintNetmask)
  602. {
  603. if (family == AddressFamily.InterNetwork && cidr > 32)
  604. {
  605. if (tryParse == false)
  606. {
  607. throw new ArgumentOutOfRangeException(nameof(cidr));
  608. }
  609. uintNetmask = null;
  610. return;
  611. }
  612. if (family == AddressFamily.InterNetworkV6 && cidr > 128)
  613. {
  614. if (tryParse == false)
  615. {
  616. throw new ArgumentOutOfRangeException(nameof(cidr));
  617. }
  618. uintNetmask = null;
  619. return;
  620. }
  621. if (family != AddressFamily.InterNetwork
  622. && family != AddressFamily.InterNetworkV6)
  623. {
  624. if (tryParse == false)
  625. {
  626. throw new NotSupportedException(family.ToString());
  627. }
  628. uintNetmask = null;
  629. return;
  630. }
  631. if (family == AddressFamily.InterNetwork)
  632. {
  633. uintNetmask = cidr == 0 ? 0 : 0xffffffff << (32 - cidr);
  634. return;
  635. }
  636. var mask = new BigInteger(new byte[] {
  637. 0xff, 0xff, 0xff, 0xff,
  638. 0xff, 0xff, 0xff, 0xff,
  639. 0xff, 0xff, 0xff, 0xff,
  640. 0xff, 0xff, 0xff, 0xff,
  641. 0x00
  642. });
  643. var masked = cidr == 0 ? 0 : mask << (128 - cidr);
  644. byte[] m = masked.ToByteArray();
  645. byte[] bmask = new byte[17];
  646. int copy = m.Length > 16 ? 16 : m.Length;
  647. Array.Copy(m, 0, bmask, 0, copy);
  648. uintNetmask = new BigInteger(bmask);
  649. }
  650. #endregion
  651. #region ToCidr
  652. /// <summary>
  653. /// Convert netmask to CIDR
  654. /// 255.255.255.0 -> 24
  655. /// 255.255.0.0 -> 16
  656. /// 255.0.0.0 -> 8
  657. /// </summary>
  658. /// <param name="netmask"></param>
  659. /// <returns></returns>
  660. private static void InternalToCidr(bool tryParse, BigInteger netmask, AddressFamily family, out byte? cidr)
  661. {
  662. if (!IPNetwork.InternalValidNetmask(netmask, family))
  663. {
  664. if (tryParse == false)
  665. {
  666. throw new ArgumentException("netmask");
  667. }
  668. cidr = null;
  669. return;
  670. }
  671. byte cidr2 = IPNetwork.BitsSet(netmask, family);
  672. cidr = cidr2;
  673. return;
  674. }
  675. /// <summary>
  676. /// Convert netmask to CIDR
  677. /// 255.255.255.0 -> 24
  678. /// 255.255.0.0 -> 16
  679. /// 255.0.0.0 -> 8
  680. /// </summary>
  681. /// <param name="netmask"></param>
  682. /// <returns></returns>
  683. public static byte ToCidr(IPAddress netmask)
  684. {
  685. IPNetwork.InternalToCidr(false, netmask, out var cidr);
  686. return (byte)cidr;
  687. }
  688. /// <summary>
  689. /// Convert netmask to CIDR
  690. /// 255.255.255.0 -> 24
  691. /// 255.255.0.0 -> 16
  692. /// 255.0.0.0 -> 8
  693. /// </summary>
  694. /// <param name="netmask"></param>
  695. /// <returns></returns>
  696. public static bool TryToCidr(IPAddress netmask, out byte? cidr)
  697. {
  698. IPNetwork.InternalToCidr(true, netmask, out var cidr2);
  699. bool parsed = (cidr2 != null);
  700. cidr = cidr2;
  701. return parsed;
  702. }
  703. private static void InternalToCidr(bool tryParse, IPAddress netmask, out byte? cidr)
  704. {
  705. if (netmask == null)
  706. {
  707. if (tryParse == false)
  708. {
  709. throw new ArgumentNullException(nameof(netmask));
  710. }
  711. cidr = null;
  712. return;
  713. }
  714. bool parsed = IPNetwork.TryToBigInteger(netmask, out var uintNetmask2);
  715. /// 20180217 lduchosal
  716. /// impossible to reach code.
  717. /// if (parsed == false) {
  718. /// if (tryParse == false) {
  719. /// throw new ArgumentException("netmask");
  720. /// }
  721. /// cidr = null;
  722. /// return;
  723. /// }
  724. var uintNetmask = (BigInteger)uintNetmask2;
  725. IPNetwork.InternalToCidr(tryParse, uintNetmask, netmask.AddressFamily, out var cidr2);
  726. cidr = cidr2;
  727. return;
  728. }
  729. #endregion
  730. #region ToNetmask
  731. /// <summary>
  732. /// Convert CIDR to netmask
  733. /// 24 -> 255.255.255.0
  734. /// 16 -> 255.255.0.0
  735. /// 8 -> 255.0.0.0
  736. /// </summary>
  737. /// <see cref="http://snipplr.com/view/15557/cidr-class-for-ipv4/"/>
  738. /// <param name="cidr"></param>
  739. /// <returns></returns>
  740. public static IPAddress ToNetmask(byte cidr, AddressFamily family)
  741. {
  742. IPAddress netmask = null;
  743. IPNetwork.InternalToNetmask(false, cidr, family, out netmask);
  744. return netmask;
  745. }
  746. /// <summary>
  747. /// Convert CIDR to netmask
  748. /// 24 -> 255.255.255.0
  749. /// 16 -> 255.255.0.0
  750. /// 8 -> 255.0.0.0
  751. /// </summary>
  752. /// <see cref="http://snipplr.com/view/15557/cidr-class-for-ipv4/"/>
  753. /// <param name="cidr"></param>
  754. /// <returns></returns>
  755. public static bool TryToNetmask(byte cidr, AddressFamily family, out IPAddress netmask)
  756. {
  757. IPAddress netmask2 = null;
  758. IPNetwork.InternalToNetmask(true, cidr, family, out netmask2);
  759. bool parsed = (netmask2 != null);
  760. netmask = netmask2;
  761. return parsed;
  762. }
  763. #if TRAVISCI
  764. public
  765. #else
  766. internal
  767. #endif
  768. static void InternalToNetmask(bool tryParse, byte cidr, AddressFamily family, out IPAddress netmask)
  769. {
  770. if (family != AddressFamily.InterNetwork
  771. && family != AddressFamily.InterNetworkV6)
  772. {
  773. if (tryParse == false)
  774. {
  775. throw new ArgumentException("family");
  776. }
  777. netmask = null;
  778. return;
  779. }
  780. /// 20180217 lduchosal
  781. /// impossible to reach code, byte cannot be negative :
  782. ///
  783. /// if (cidr < 0) {
  784. /// if (tryParse == false) {
  785. /// throw new ArgumentOutOfRangeException("cidr");
  786. /// }
  787. /// netmask = null;
  788. /// return;
  789. /// }
  790. int maxCidr = family == Sockets.AddressFamily.InterNetwork ? 32 : 128;
  791. if (cidr > maxCidr)
  792. {
  793. if (tryParse == false)
  794. {
  795. throw new ArgumentOutOfRangeException(nameof(cidr));
  796. }
  797. netmask = null;
  798. return;
  799. }
  800. var mask = IPNetwork.ToUint(cidr, family);
  801. var netmask2 = IPNetwork.ToIPAddress(mask, family);
  802. netmask = netmask2;
  803. return;
  804. }
  805. #endregion
  806. #endregion
  807. #region utils
  808. #region BitsSet
  809. /// <summary>
  810. /// Count bits set to 1 in netmask
  811. /// </summary>
  812. /// <see cref="http://stackoverflow.com/questions/109023/best-algorithm-to-count-the-number-of-set-bits-in-a-32-bit-integer"/>
  813. /// <param name="netmask"></param>
  814. /// <returns></returns>
  815. private static byte BitsSet(BigInteger netmask, AddressFamily family)
  816. {
  817. string s = netmask.ToBinaryString();
  818. return (byte)s.Replace("0", "")
  819. .ToCharArray()
  820. .Length;
  821. }
  822. /// <summary>
  823. /// Count bits set to 1 in netmask
  824. /// </summary>
  825. /// <param name="netmask"></param>
  826. /// <returns></returns>
  827. public static uint BitsSet(IPAddress netmask)
  828. {
  829. var uintNetmask = IPNetwork.ToBigInteger(netmask);
  830. uint bits = IPNetwork.BitsSet(uintNetmask, netmask.AddressFamily);
  831. return bits;
  832. }
  833. #endregion
  834. #region ValidNetmask
  835. /// <summary>
  836. /// return true if netmask is a valid netmask
  837. /// 255.255.255.0, 255.0.0.0, 255.255.240.0, ...
  838. /// </summary>
  839. /// <see cref="http://www.actionsnip.com/snippets/tomo_atlacatl/calculate-if-a-netmask-is-valid--as2-"/>
  840. /// <param name="netmask"></param>
  841. /// <returns></returns>
  842. public static bool ValidNetmask(IPAddress netmask)
  843. {
  844. if (netmask == null)
  845. {
  846. throw new ArgumentNullException(nameof(netmask));
  847. }
  848. var uintNetmask = IPNetwork.ToBigInteger(netmask);
  849. bool valid = IPNetwork.InternalValidNetmask(uintNetmask, netmask.AddressFamily);
  850. return valid;
  851. }
  852. #if TRAVISCI
  853. public
  854. #else
  855. internal
  856. #endif
  857. static bool InternalValidNetmask(BigInteger netmask, AddressFamily family)
  858. {
  859. if (family != AddressFamily.InterNetwork
  860. && family != AddressFamily.InterNetworkV6)
  861. {
  862. throw new ArgumentException("family");
  863. }
  864. var mask = family == AddressFamily.InterNetwork
  865. ? new BigInteger(0x0ffffffff)
  866. : new BigInteger(new byte[]{
  867. 0xff, 0xff, 0xff, 0xff,
  868. 0xff, 0xff, 0xff, 0xff,
  869. 0xff, 0xff, 0xff, 0xff,
  870. 0xff, 0xff, 0xff, 0xff,
  871. 0x00
  872. });
  873. var neg = ((~netmask) & (mask));
  874. bool isNetmask = ((neg + 1) & neg) == 0;
  875. return isNetmask;
  876. }
  877. #endregion
  878. #region ToIPAddress
  879. /// <summary>
  880. /// Transform a uint ipaddress into IPAddress object
  881. /// </summary>
  882. /// <param name="ipaddress"></param>
  883. /// <returns></returns>
  884. public static IPAddress ToIPAddress(BigInteger ipaddress, AddressFamily family)
  885. {
  886. int width = family == AddressFamily.InterNetwork ? 4 : 16;
  887. byte[] bytes = ipaddress.ToByteArray();
  888. byte[] bytes2 = new byte[width];
  889. int copy = bytes.Length > width ? width : bytes.Length;
  890. Array.Copy(bytes, 0, bytes2, 0, copy);
  891. Array.Reverse(bytes2);
  892. byte[] sized = Resize(bytes2, family);
  893. var ip = new IPAddress(sized);
  894. return ip;
  895. }
  896. #if TRAVISCI
  897. public
  898. #else
  899. internal
  900. #endif
  901. static byte[] Resize(byte[] bytes, AddressFamily family)
  902. {
  903. if (family != AddressFamily.InterNetwork
  904. && family != AddressFamily.InterNetworkV6)
  905. {
  906. throw new ArgumentException("family");
  907. }
  908. int width = family == AddressFamily.InterNetwork ? 4 : 16;
  909. if (bytes.Length > width)
  910. {
  911. throw new ArgumentException("bytes");
  912. }
  913. byte[] result = new byte[width];
  914. Array.Copy(bytes, 0, result, 0, bytes.Length);
  915. return result;
  916. }
  917. #endregion
  918. #endregion
  919. #region contains
  920. /// <summary>
  921. /// return true if ipaddress is contained in network
  922. /// </summary>
  923. /// <param name="ipaddress"></param>
  924. /// <returns></returns>
  925. public bool Contains(IPAddress ipaddress)
  926. {
  927. if (ipaddress == null)
  928. {
  929. throw new ArgumentNullException(nameof(ipaddress));
  930. }
  931. if (AddressFamily != ipaddress.AddressFamily)
  932. {
  933. return false;
  934. }
  935. var uintNetwork = _network;
  936. var uintBroadcast = _broadcast;
  937. var uintAddress = IPNetwork.ToBigInteger(ipaddress);
  938. bool contains = (uintAddress >= uintNetwork
  939. && uintAddress <= uintBroadcast);
  940. return contains;
  941. }
  942. /// <summary>
  943. /// return true is network2 is fully contained in network
  944. /// </summary>
  945. /// <param name="network2"></param>
  946. /// <returns></returns>
  947. public bool Contains(IPNetwork network2)
  948. {
  949. if (network2 == null)
  950. {
  951. throw new ArgumentNullException(nameof(network2));
  952. }
  953. var uintNetwork = _network;
  954. var uintBroadcast = _broadcast;
  955. var uintFirst = network2._network;
  956. var uintLast = network2._broadcast;
  957. bool contains = (uintFirst >= uintNetwork
  958. && uintLast <= uintBroadcast);
  959. return contains;
  960. }
  961. #endregion
  962. #region overlap
  963. /// <summary>
  964. /// return true is network2 overlap network
  965. /// </summary>
  966. /// <param name="network2"></param>
  967. /// <returns></returns>
  968. public bool Overlap(IPNetwork network2)
  969. {
  970. if (network2 == null)
  971. {
  972. throw new ArgumentNullException(nameof(network2));
  973. }
  974. var uintNetwork = _network;
  975. var uintBroadcast = _broadcast;
  976. var uintFirst = network2._network;
  977. var uintLast = network2._broadcast;
  978. bool overlap =
  979. (uintFirst >= uintNetwork && uintFirst <= uintBroadcast)
  980. || (uintLast >= uintNetwork && uintLast <= uintBroadcast)
  981. || (uintFirst <= uintNetwork && uintLast >= uintBroadcast)
  982. || (uintFirst >= uintNetwork && uintLast <= uintBroadcast);
  983. return overlap;
  984. }
  985. #endregion
  986. #region ToString
  987. public override string ToString()
  988. {
  989. return string.Format("{0}/{1}", this.Network, this.Cidr);
  990. }
  991. #endregion
  992. #region IANA block
  993. private static readonly Lazy<IPNetwork> _iana_ablock_reserved = new Lazy<IPNetwork>(() => IPNetwork.Parse("10.0.0.0/8"));
  994. private static readonly Lazy<IPNetwork> _iana_bblock_reserved = new Lazy<IPNetwork>(() => IPNetwork.Parse("172.16.0.0/12"));
  995. private static readonly Lazy<IPNetwork> _iana_cblock_reserved = new Lazy<IPNetwork>(() => IPNetwork.Parse("192.168.0.0/16"));
  996. /// <summary>
  997. /// 10.0.0.0/8
  998. /// </summary>
  999. /// <returns></returns>
  1000. public static IPNetwork IANA_ABLK_RESERVED1 => _iana_ablock_reserved.Value;
  1001. /// <summary>
  1002. /// 172.12.0.0/12
  1003. /// </summary>
  1004. /// <returns></returns>
  1005. public static IPNetwork IANA_BBLK_RESERVED1 => _iana_bblock_reserved.Value;
  1006. /// <summary>
  1007. /// 192.168.0.0/16
  1008. /// </summary>
  1009. /// <returns></returns>
  1010. public static IPNetwork IANA_CBLK_RESERVED1 => _iana_cblock_reserved.Value;
  1011. /// <summary>
  1012. /// return true if ipaddress is contained in
  1013. /// IANA_ABLK_RESERVED1, IANA_BBLK_RESERVED1, IANA_CBLK_RESERVED1
  1014. /// </summary>
  1015. /// <param name="ipaddress"></param>
  1016. /// <returns></returns>
  1017. public static bool IsIANAReserved(IPAddress ipaddress)
  1018. {
  1019. if (ipaddress == null)
  1020. {
  1021. throw new ArgumentNullException(nameof(ipaddress));
  1022. }
  1023. return IPNetwork.IANA_ABLK_RESERVED1.Contains(ipaddress)
  1024. || IPNetwork.IANA_BBLK_RESERVED1.Contains(ipaddress)
  1025. || IPNetwork.IANA_CBLK_RESERVED1.Contains(ipaddress);
  1026. }
  1027. /// <summary>
  1028. /// return true if ipnetwork is contained in
  1029. /// IANA_ABLK_RESERVED1, IANA_BBLK_RESERVED1, IANA_CBLK_RESERVED1
  1030. /// </summary>
  1031. /// <returns></returns>
  1032. public bool IsIANAReserved()
  1033. {
  1034. return IPNetwork.IANA_ABLK_RESERVED1.Contains(this)
  1035. || IPNetwork.IANA_BBLK_RESERVED1.Contains(this)
  1036. || IPNetwork.IANA_CBLK_RESERVED1.Contains(this);
  1037. }
  1038. #endregion
  1039. #region Subnet
  1040. /// <summary>
  1041. /// Subnet a network into multiple nets of cidr mask
  1042. /// Subnet 192.168.0.0/24 into cidr 25 gives 192.168.0.0/25, 192.168.0.128/25
  1043. /// Subnet 10.0.0.0/8 into cidr 9 gives 10.0.0.0/9, 10.128.0.0/9
  1044. /// </summary>
  1045. /// <param name="cidr"></param>
  1046. /// <returns></returns>
  1047. public IPNetworkCollection Subnet(byte cidr)
  1048. {
  1049. IPNetworkCollection ipnetworkCollection = null;
  1050. IPNetwork.InternalSubnet(false, this, cidr, out ipnetworkCollection);
  1051. return ipnetworkCollection;
  1052. }
  1053. /// <summary>
  1054. /// Subnet a network into multiple nets of cidr mask
  1055. /// Subnet 192.168.0.0/24 into cidr 25 gives 192.168.0.0/25, 192.168.0.128/25
  1056. /// Subnet 10.0.0.0/8 into cidr 9 gives 10.0.0.0/9, 10.128.0.0/9
  1057. /// </summary>
  1058. /// <param name="cidr"></param>
  1059. /// <returns></returns>
  1060. public bool TrySubnet(byte cidr, out IPNetworkCollection ipnetworkCollection)
  1061. {
  1062. IPNetworkCollection inc = null;
  1063. IPNetwork.InternalSubnet(true, this, cidr, out inc);
  1064. if (inc == null)
  1065. {
  1066. ipnetworkCollection = null;
  1067. return false;
  1068. }
  1069. ipnetworkCollection = inc;
  1070. return true;
  1071. }
  1072. #if TRAVISCI
  1073. public
  1074. #else
  1075. internal
  1076. #endif
  1077. static void InternalSubnet(bool trySubnet, IPNetwork network, byte cidr, out IPNetworkCollection ipnetworkCollection)
  1078. {
  1079. if (network == null)
  1080. {
  1081. if (trySubnet == false)
  1082. {
  1083. throw new ArgumentNullException(nameof(network));
  1084. }
  1085. ipnetworkCollection = null;
  1086. return;
  1087. }
  1088. int maxCidr = network._family == Sockets.AddressFamily.InterNetwork ? 32 : 128;
  1089. if (cidr > maxCidr)
  1090. {
  1091. if (trySubnet == false)
  1092. {
  1093. throw new ArgumentOutOfRangeException(nameof(cidr));
  1094. }
  1095. ipnetworkCollection = null;
  1096. return;
  1097. }
  1098. if (cidr < network.Cidr)
  1099. {
  1100. if (trySubnet == false)
  1101. {
  1102. throw new ArgumentException("cidr");
  1103. }
  1104. ipnetworkCollection = null;
  1105. return;
  1106. }
  1107. ipnetworkCollection = new IPNetworkCollection(network, cidr);
  1108. return;
  1109. }
  1110. #endregion
  1111. #region Supernet
  1112. /// <summary>
  1113. /// Supernet two consecutive cidr equal subnet into a single one
  1114. /// 192.168.0.0/24 + 192.168.1.0/24 = 192.168.0.0/23
  1115. /// 10.1.0.0/16 + 10.0.0.0/16 = 10.0.0.0/15
  1116. /// 192.168.0.0/24 + 192.168.0.0/25 = 192.168.0.0/24
  1117. /// </summary>
  1118. /// <param name="network2"></param>
  1119. /// <returns></returns>
  1120. public IPNetwork Supernet(IPNetwork network2)
  1121. {
  1122. IPNetwork supernet = null;
  1123. IPNetwork.InternalSupernet(false, this, network2, out supernet);
  1124. return supernet;
  1125. }
  1126. /// <summary>
  1127. /// Try to supernet two consecutive cidr equal subnet into a single one
  1128. /// 192.168.0.0/24 + 192.168.1.0/24 = 192.168.0.0/23
  1129. /// 10.1.0.0/16 + 10.0.0.0/16 = 10.0.0.0/15
  1130. /// 192.168.0.0/24 + 192.168.0.0/25 = 192.168.0.0/24
  1131. /// </summary>
  1132. /// <param name="network2"></param>
  1133. /// <returns></returns>
  1134. public bool TrySupernet(IPNetwork network2, out IPNetwork supernet)
  1135. {
  1136. IPNetwork outSupernet = null;
  1137. IPNetwork.InternalSupernet(true, this, network2, out outSupernet);
  1138. bool parsed = (outSupernet != null);
  1139. supernet = outSupernet;
  1140. return parsed;
  1141. }
  1142. #if TRAVISCI
  1143. public
  1144. #else
  1145. internal
  1146. #endif
  1147. static void InternalSupernet(bool trySupernet, IPNetwork network1, IPNetwork network2, out IPNetwork supernet)
  1148. {
  1149. if (network1 == null)
  1150. {
  1151. if (trySupernet == false)
  1152. {
  1153. throw new ArgumentNullException(nameof(network1));
  1154. }
  1155. supernet = null;
  1156. return;
  1157. }
  1158. if (network2 == null)
  1159. {
  1160. if (trySupernet == false)
  1161. {
  1162. throw new ArgumentNullException(nameof(network2));
  1163. }
  1164. supernet = null;
  1165. return;
  1166. }
  1167. if (network1.Contains(network2))
  1168. {
  1169. supernet = new IPNetwork(network1._network, network1._family, network1.Cidr);
  1170. return;
  1171. }
  1172. if (network2.Contains(network1))
  1173. {
  1174. supernet = new IPNetwork(network2._network, network2._family, network2.Cidr);
  1175. return;
  1176. }
  1177. if (network1._cidr != network2._cidr)
  1178. {
  1179. if (trySupernet == false)
  1180. {
  1181. throw new ArgumentException("cidr");
  1182. }
  1183. supernet = null;
  1184. return;
  1185. }
  1186. var first = (network1._network < network2._network) ? network1 : network2;
  1187. var last = (network1._network > network2._network) ? network1 : network2;
  1188. /// Starting from here :
  1189. /// network1 and network2 have the same cidr,
  1190. /// network1 does not contain network2,
  1191. /// network2 does not contain network1,
  1192. /// first is the lower subnet
  1193. /// last is the higher subnet
  1194. if ((first._broadcast + 1) != last._network)
  1195. {
  1196. if (trySupernet == false)
  1197. {
  1198. throw new ArgumentOutOfRangeException(nameof(trySupernet), "TrySupernet was false while the first and last networks are not adjacent.");
  1199. }
  1200. supernet = null;
  1201. return;
  1202. }
  1203. var uintSupernet = first._network;
  1204. byte cidrSupernet = (byte)(first._cidr - 1);
  1205. var networkSupernet = new IPNetwork(uintSupernet, first._family, cidrSupernet);
  1206. if (networkSupernet._network != first._network)
  1207. {
  1208. if (trySupernet == false)
  1209. {
  1210. throw new ArgumentException("network");
  1211. }
  1212. supernet = null;
  1213. return;
  1214. }
  1215. supernet = networkSupernet;
  1216. return;
  1217. }
  1218. #endregion
  1219. #region GetHashCode
  1220. public override int GetHashCode()
  1221. {
  1222. return string.Format("{0}|{1}|{2}",
  1223. this._ipaddress.GetHashCode(),
  1224. this._network.GetHashCode(),
  1225. this._cidr.GetHashCode()).GetHashCode();
  1226. }
  1227. #endregion
  1228. #region SupernetArray
  1229. /// <summary>
  1230. /// Supernet a list of subnet
  1231. /// 192.168.0.0/24 + 192.168.1.0/24 = 192.168.0.0/23
  1232. /// 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
  1233. /// </summary>
  1234. /// <param name="ipnetworks">The IP networks</param>
  1235. /// <returns></returns>
  1236. public static IPNetwork[] Supernet(IPNetwork[] ipnetworks)
  1237. {
  1238. InternalSupernet(false, ipnetworks, out var supernet);
  1239. return supernet;
  1240. }
  1241. /// <summary>
  1242. /// Supernet a list of subnet
  1243. /// 192.168.0.0/24 + 192.168.1.0/24 = 192.168.0.0/23
  1244. /// 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
  1245. /// </summary>
  1246. /// <param name="ipnetworks"></param>
  1247. /// <param name="supernet"></param>
  1248. /// <returns></returns>
  1249. public static bool TrySupernet(IPNetwork[] ipnetworks, out IPNetwork[] supernet)
  1250. {
  1251. bool supernetted = InternalSupernet(true, ipnetworks, out supernet);
  1252. return supernetted;
  1253. }
  1254. #if TRAVISCI
  1255. public
  1256. #else
  1257. internal
  1258. #endif
  1259. static bool InternalSupernet(bool trySupernet, IPNetwork[] ipnetworks, out IPNetwork[] supernet)
  1260. {
  1261. if (ipnetworks == null)
  1262. {
  1263. if (trySupernet == false)
  1264. {
  1265. throw new ArgumentNullException(nameof(ipnetworks));
  1266. }
  1267. supernet = null;
  1268. return false;
  1269. }
  1270. if (ipnetworks.Length <= 0)
  1271. {
  1272. supernet = new IPNetwork[0];
  1273. return true;
  1274. }
  1275. var supernetted = new List<IPNetwork>();
  1276. var ipns = IPNetwork.Array2List(ipnetworks);
  1277. var current = IPNetwork.List2Stack(ipns);
  1278. int previousCount = 0;
  1279. int currentCount = current.Count;
  1280. while (previousCount != currentCount)
  1281. {
  1282. supernetted.Clear();
  1283. while (current.Count > 1)
  1284. {
  1285. var ipn1 = current.Pop();
  1286. var ipn2 = current.Peek();
  1287. IPNetwork outNetwork = null;
  1288. bool success = ipn1.TrySupernet(ipn2, out outNetwork);
  1289. if (success)
  1290. {
  1291. current.Pop();
  1292. current.Push(outNetwork);
  1293. }
  1294. else
  1295. {
  1296. supernetted.Add(ipn1);
  1297. }
  1298. }
  1299. if (current.Count == 1)
  1300. {
  1301. supernetted.Add(current.Pop());
  1302. }
  1303. previousCount = currentCount;
  1304. currentCount = supernetted.Count;
  1305. current = IPNetwork.List2Stack(supernetted);
  1306. }
  1307. supernet = supernetted.ToArray();
  1308. return true;
  1309. }
  1310. private static Stack<IPNetwork> List2Stack(List<IPNetwork> list)
  1311. {
  1312. var stack = new Stack<IPNetwork>();
  1313. list.ForEach(new Action<IPNetwork>(
  1314. delegate (IPNetwork ipn)
  1315. {
  1316. stack.Push(ipn);
  1317. }
  1318. ));
  1319. return stack;
  1320. }
  1321. private static List<IPNetwork> Array2List(IPNetwork[] array)
  1322. {
  1323. var ipns = new List<IPNetwork>();
  1324. ipns.AddRange(array);
  1325. IPNetwork.RemoveNull(ipns);
  1326. ipns.Sort(new Comparison<IPNetwork>(
  1327. delegate (IPNetwork ipn1, IPNetwork ipn2)
  1328. {
  1329. int networkCompare = ipn1._network.CompareTo(ipn2._network);
  1330. if (networkCompare == 0)
  1331. {
  1332. int cidrCompare = ipn1._cidr.CompareTo(ipn2._cidr);
  1333. return cidrCompare;
  1334. }
  1335. return networkCompare;
  1336. }
  1337. ));
  1338. ipns.Reverse();
  1339. return ipns;
  1340. }
  1341. private static void RemoveNull(List<IPNetwork> ipns)
  1342. {
  1343. ipns.RemoveAll(new Predicate<IPNetwork>(
  1344. delegate (IPNetwork ipn)
  1345. {
  1346. if (ipn == null)
  1347. {
  1348. return true;
  1349. }
  1350. return false;
  1351. }
  1352. ));
  1353. }
  1354. #endregion
  1355. #region WideSubnet
  1356. public static IPNetwork WideSubnet(string start, string end)
  1357. {
  1358. if (string.IsNullOrEmpty(start))
  1359. {
  1360. throw new ArgumentNullException(nameof(start));
  1361. }
  1362. if (string.IsNullOrEmpty(end))
  1363. {
  1364. throw new ArgumentNullException(nameof(end));
  1365. }
  1366. if (!IPAddress.TryParse(start, out var startIP))
  1367. {
  1368. throw new ArgumentException("start");
  1369. }
  1370. if (!IPAddress.TryParse(end, out var endIP))
  1371. {
  1372. throw new ArgumentException("end");
  1373. }
  1374. if (startIP.AddressFamily != endIP.AddressFamily)
  1375. {
  1376. throw new NotSupportedException("MixedAddressFamily");
  1377. }
  1378. var ipnetwork = new IPNetwork(0, startIP.AddressFamily, 0);
  1379. for (byte cidr = 32; cidr >= 0; cidr--)
  1380. {
  1381. var wideSubnet = IPNetwork.Parse(start, cidr);
  1382. if (wideSubnet.Contains(endIP))
  1383. {
  1384. ipnetwork = wideSubnet;
  1385. break;
  1386. }
  1387. }
  1388. return ipnetwork;
  1389. }
  1390. public static bool TryWideSubnet(IPNetwork[] ipnetworks, out IPNetwork ipnetwork)
  1391. {
  1392. IPNetwork ipn = null;
  1393. IPNetwork.InternalWideSubnet(true, ipnetworks, out ipn);
  1394. if (ipn == null)
  1395. {
  1396. ipnetwork = null;
  1397. return false;
  1398. }
  1399. ipnetwork = ipn;
  1400. return true;
  1401. }
  1402. public static IPNetwork WideSubnet(IPNetwork[] ipnetworks)
  1403. {
  1404. IPNetwork ipn = null;
  1405. IPNetwork.InternalWideSubnet(false, ipnetworks, out ipn);
  1406. return ipn;
  1407. }
  1408. internal static void InternalWideSubnet(bool tryWide, IPNetwork[] ipnetworks, out IPNetwork ipnetwork)
  1409. {
  1410. if (ipnetworks == null)
  1411. {
  1412. if (tryWide == false)
  1413. {
  1414. throw new ArgumentNullException(nameof(ipnetworks));
  1415. }
  1416. ipnetwork = null;
  1417. return;
  1418. }
  1419. IPNetwork[] nnin = Array.FindAll(ipnetworks, new Predicate<IPNetwork>(
  1420. delegate (IPNetwork ipnet)
  1421. {
  1422. return ipnet != null;
  1423. }
  1424. ));
  1425. if (nnin.Length <= 0)
  1426. {
  1427. if (tryWide == false)
  1428. {
  1429. throw new ArgumentException("ipnetworks");
  1430. }
  1431. ipnetwork = null;
  1432. return;
  1433. }
  1434. if (nnin.Length == 1)
  1435. {
  1436. var ipn0 = nnin[0];
  1437. ipnetwork = ipn0;
  1438. return;
  1439. }
  1440. Array.Sort(nnin);
  1441. var nnin0 = nnin[0];
  1442. var uintNnin0 = nnin0._ipaddress;
  1443. var nninX = nnin[nnin.Length - 1];
  1444. var ipaddressX = nninX.Broadcast;
  1445. var family = ipnetworks[0]._family;
  1446. foreach (var ipnx in ipnetworks)
  1447. {
  1448. if (ipnx._family != family)
  1449. {
  1450. throw new ArgumentException("MixedAddressFamily");
  1451. }
  1452. }
  1453. var ipn = new IPNetwork(0, family, 0);
  1454. for (byte cidr = nnin0._cidr; cidr >= 0; cidr--)
  1455. {
  1456. var wideSubnet = new IPNetwork(uintNnin0, family, cidr);
  1457. if (wideSubnet.Contains(ipaddressX))
  1458. {
  1459. ipn = wideSubnet;
  1460. break;
  1461. }
  1462. }
  1463. ipnetwork = ipn;
  1464. return;
  1465. }
  1466. #endregion
  1467. #region Print
  1468. /// <summary>
  1469. /// Print an ipnetwork in a clear representation string
  1470. /// </summary>
  1471. /// <returns></returns>
  1472. public string Print()
  1473. {
  1474. var sw = new StringWriter();
  1475. sw.WriteLine("IPNetwork : {0}", ToString());
  1476. sw.WriteLine("Network : {0}", Network);
  1477. sw.WriteLine("Netmask : {0}", Netmask);
  1478. sw.WriteLine("Cidr : {0}", Cidr);
  1479. sw.WriteLine("Broadcast : {0}", Broadcast);
  1480. sw.WriteLine("FirstUsable : {0}", FirstUsable);
  1481. sw.WriteLine("LastUsable : {0}", LastUsable);
  1482. sw.WriteLine("Usable : {0}", Usable);
  1483. return sw.ToString();
  1484. }
  1485. #endregion
  1486. #region TryGuessCidr
  1487. /// <summary>
  1488. ///
  1489. /// Class Leading bits Default netmask
  1490. /// A (CIDR /8) 00 255.0.0.0
  1491. /// A (CIDR /8) 01 255.0.0.0
  1492. /// B (CIDR /16) 10 255.255.0.0
  1493. /// C (CIDR /24) 11 255.255.255.0
  1494. ///
  1495. /// </summary>
  1496. /// <param name="ip"></param>
  1497. /// <param name="cidr"></param>
  1498. /// <returns></returns>
  1499. public static bool TryGuessCidr(string ip, out byte cidr)
  1500. {
  1501. IPAddress ipaddress = null;
  1502. bool parsed = IPAddress.TryParse(string.Format("{0}", ip), out ipaddress);
  1503. if (parsed == false)
  1504. {
  1505. cidr = 0;
  1506. return false;
  1507. }
  1508. if (ipaddress.AddressFamily == AddressFamily.InterNetworkV6)
  1509. {
  1510. cidr = 64;
  1511. return true;
  1512. }
  1513. var uintIPAddress = IPNetwork.ToBigInteger(ipaddress);
  1514. uintIPAddress = uintIPAddress >> 29;
  1515. if (uintIPAddress <= 3)
  1516. {
  1517. cidr = 8;
  1518. return true;
  1519. }
  1520. else if (uintIPAddress <= 5)
  1521. {
  1522. cidr = 16;
  1523. return true;
  1524. }
  1525. else if (uintIPAddress <= 6)
  1526. {
  1527. cidr = 24;
  1528. return true;
  1529. }
  1530. cidr = 0;
  1531. return false;
  1532. }
  1533. /// <summary>
  1534. /// Try to parse cidr. Have to be >= 0 and <= 32 or 128
  1535. /// </summary>
  1536. /// <param name="sidr"></param>
  1537. /// <param name="cidr"></param>
  1538. /// <returns></returns>
  1539. public static bool TryParseCidr(string sidr, AddressFamily family, out byte? cidr)
  1540. {
  1541. byte b = 0;
  1542. if (!byte.TryParse(sidr, out b))
  1543. {
  1544. cidr = null;
  1545. return false;
  1546. }
  1547. IPAddress netmask = null;
  1548. if (!IPNetwork.TryToNetmask(b, family, out netmask))
  1549. {
  1550. cidr = null;
  1551. return false;
  1552. }
  1553. cidr = b;
  1554. return true;
  1555. }
  1556. #endregion
  1557. #region ListIPAddress
  1558. public IPAddressCollection ListIPAddress()
  1559. {
  1560. return new IPAddressCollection(this);
  1561. }
  1562. #endregion
  1563. /**
  1564. * Need a better way to do it
  1565. *
  1566. #region TrySubstractNetwork
  1567. public static bool TrySubstractNetwork(IPNetwork[] ipnetworks, IPNetwork substract, out IEnumerable<IPNetwork> result) {
  1568. if (ipnetworks == null) {
  1569. result = null;
  1570. return false;
  1571. }
  1572. if (ipnetworks.Length <= 0) {
  1573. result = null;
  1574. return false;
  1575. }
  1576. if (substract == null) {
  1577. result = null;
  1578. return false;
  1579. }
  1580. var results = new List<IPNetwork>();
  1581. foreach (var ipn in ipnetworks) {
  1582. if (!Overlap(ipn, substract)) {
  1583. results.Add(ipn);
  1584. continue;
  1585. }
  1586. var collection = ipn.Subnet(substract.Cidr);
  1587. var rtemp = new List<IPNetwork>();
  1588. foreach(var subnet in collection) {
  1589. if (subnet != substract) {
  1590. rtemp.Add(subnet);
  1591. }
  1592. }
  1593. var supernets = Supernet(rtemp.ToArray());
  1594. results.AddRange(supernets);
  1595. }
  1596. result = results;
  1597. return true;
  1598. }
  1599. #endregion
  1600. * **/
  1601. #region IComparable<IPNetwork> Members
  1602. public static int Compare(IPNetwork left, IPNetwork right)
  1603. {
  1604. // two null IPNetworks are equal
  1605. if (ReferenceEquals(left, null) && ReferenceEquals(right, null)) return 0;
  1606. // two same IPNetworks are equal
  1607. if (ReferenceEquals(left, right)) return 0;
  1608. // null is always sorted first
  1609. if (ReferenceEquals(left, null)) return -1;
  1610. if (ReferenceEquals(right, null)) return 1;
  1611. // first test the network
  1612. var result = left._network.CompareTo(right._network);
  1613. if (result != 0) return result;
  1614. // then test the cidr
  1615. result = left._cidr.CompareTo(right._cidr);
  1616. return result;
  1617. }
  1618. public int CompareTo(IPNetwork other)
  1619. {
  1620. return Compare(this, other);
  1621. }
  1622. public int CompareTo(object obj)
  1623. {
  1624. // null is at less
  1625. if (obj == null) return 1;
  1626. // convert to a proper Cidr object
  1627. var other = obj as IPNetwork;
  1628. // type problem if null
  1629. if (other == null)
  1630. {
  1631. throw new ArgumentException(
  1632. "The supplied parameter is an invalid type. Please supply an IPNetwork type.",
  1633. nameof(obj));
  1634. }
  1635. // perform the comparision
  1636. return CompareTo(other);
  1637. }
  1638. #endregion
  1639. #region IEquatable<IPNetwork> Members
  1640. public static bool Equals(IPNetwork left, IPNetwork right)
  1641. {
  1642. return Compare(left, right) == 0;
  1643. }
  1644. public bool Equals(IPNetwork other)
  1645. {
  1646. return Equals(this, other);
  1647. }
  1648. public override bool Equals(object obj)
  1649. {
  1650. return Equals(this, obj as IPNetwork);
  1651. }
  1652. #endregion
  1653. #region Operators
  1654. public static bool operator ==(IPNetwork left, IPNetwork right)
  1655. {
  1656. return Equals(left, right);
  1657. }
  1658. public static bool operator !=(IPNetwork left, IPNetwork right)
  1659. {
  1660. return !Equals(left, right);
  1661. }
  1662. public static bool operator <(IPNetwork left, IPNetwork right)
  1663. {
  1664. return Compare(left, right) < 0;
  1665. }
  1666. public static bool operator >(IPNetwork left, IPNetwork right)
  1667. {
  1668. return Compare(left, right) > 0;
  1669. }
  1670. #endregion
  1671. }
  1672. }