Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert CIDR to network and IP address range in C#?

Tags:

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.

Perhaps it may be of help to someone.

References:

What's the best way to convert from network bitcount to netmask?

"Whatmask" C code from http://www.laffeycomputer.com/whatmask.html

Usage:

uint startIP, endIP;  
Network2IpRange("72.20.10.0/24", out startIP, out endIP); 

The code assumes 32 bits for everything.

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 >> bits);

    network = ip & mask;
    broadcast = network + ~mask;

    usableIps = (bits >30)?0:(broadcast - network - 1); 

    if (usableIps <= 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])<<24;
        ip += Convert.ToUInt32(elements[1])<<16;
        ip += Convert.ToUInt32(elements[2])<<8;
        ip += Convert.ToUInt32(elements[3]);
    }
    return ip;
}

Feel free to submit your improvements.