gahser1
gahser1

Reputation: 37

Converting an IP Address into CIDR

I want to design a code where I can search an inputted IP address, and using it, it gives the output of the IP address' CIDR. I need the output being a variable as I need that CIDR for another step in the code.

 static void Main(string[] args)
 {
            IPAddress addr = IPAddress.Parse("8.8.8.8");
            IPHostEntry entry = Dns.GetHostEntry(addr);
            Console.WriteLine("IP Address: " + addr);
            Console.WriteLine("Host Name: " + entry.HostName);

Upvotes: 3

Views: 1214

Answers (1)

Sigge
Sigge

Reputation: 2172

I assume by CIDR you want to get the classful netmask length of the given IP address. Using this wiki as a reference, you could convert the address to an array of bits, and then check the first leading bits.

This useful extension class converts your IP address to bits (booleans, really):

/// <summary>
/// Converts an array of bytes to a BitArray instance, 
/// respecting the endian form of the operating system
/// </summary>
public static class BitArrayExtensions
{
    public static BitArray ToBitArray(this byte[] bytes)
    {
        bool[] allbits = new bool[bytes.Length * 8];
        for (int b = 0; b < bytes.Length; b++)
        {
            bool[] bits = new bool[8];
            new BitArray(new byte[] { bytes[b] }).CopyTo(bits, 0);
            if (BitConverter.IsLittleEndian)
                Array.Reverse(bits);

            bits.CopyTo(allbits, b * 8);
        }
        return new BitArray(allbits);
    }
}

With this class at your disposal, it's quite easy to write a method that finds the classful mask length of the IP address: /8, /16 or /24

    /// <summary>
    /// Gets the length of the classful subnet mask of a given IPv4 address
    /// </summary>
    public int GetClassfulMaskbits(IPAddress address)
    {
        BitArray addressInBits = address.GetAddressBytes().ToBitArray();
        if (!addressInBits[0])  //leading bit = 0 => class A
            return 8; //default mask of class A = 255.0.0.0
        if(!addressInBits[1]) //leading bits = 10 => class B
            return 16; //default mask of class B = 255.255.0.0
        if (!addressInBits[2]) //leading bits = 110 => class C
            return 24; //default mask of class C = 255.255.255.0

        return 0; //class D or E has no classful subnet mask
    }

The BitArray extension class could be useful for other IP calculations as well.

Upvotes: 2

Related Questions