Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to convert CIDR to network and IP address range in C#?
    text
    copied!<p>I have been looking around quite a bit to find some C# code to convert a network in CIDR notation (72.20.10.0/24) to an IP address range, without much luck. There are some threads about CIDR on stackoverlow, but none seems to have any C# code and cover exactly what I need. So I decided to cook it myself, and I did not want the code to rely on System.Net for any conversions in this version. </p> <p>Perhaps it may be of help to someone. </p> <p>References: </p> <p><a href="https://stackoverflow.com/questions/218604/whats-the-best-way-to-convert-from-network-bitcount-to-netmask">What&#39;s the best way to convert from network bitcount to netmask?</a></p> <p>"Whatmask" C code from <a href="http://www.laffeycomputer.com/whatmask.html" rel="nofollow noreferrer">http://www.laffeycomputer.com/whatmask.html</a></p> <p>Usage: </p> <pre><code>uint startIP, endIP; Network2IpRange("72.20.10.0/24", out startIP, out endIP); </code></pre> <p>The code assumes 32 bits for everything. </p> <pre class="lang-cs prettyprint-override"><code>static void Network2IpRange(string sNetwork, out uint startIP, out uint endIP) { uint ip, /* ip address */ mask, /* subnet mask */ broadcast, /* Broadcast address */ network; /* Network address */ int bits; string[] elements = sNetwork.Split(new Char[] { '/' }); ip = IP2Int(elements[0]); bits = Convert.ToInt32(elements[1]); mask = ~(0xffffffff &gt;&gt; bits); network = ip &amp; mask; broadcast = network + ~mask; usableIps = (bits &gt;30)?0:(broadcast - network - 1); if (usableIps &lt;= 0) { startIP = endIP = 0; } else { startIP = network + 1; endIP = broadcast - 1; } } public static uint IP2Int(string IPNumber) { uint ip = 0; string[] elements = IPNumber.Split(new Char[] { '.' }); if (elements.Length==4) { ip = Convert.ToUInt32(elements[0])&lt;&lt;24; ip += Convert.ToUInt32(elements[1])&lt;&lt;16; ip += Convert.ToUInt32(elements[2])&lt;&lt;8; ip += Convert.ToUInt32(elements[3]); } return ip; } </code></pre> <p>Feel free to submit your improvements. </p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload