RoelF RoelF - 1 year ago 132
C# Question

Given an IP address and subnetmask, how do I calculate the CIDR?

Ok I can't seem to figure this out: given the following:

IP address =

Subnetmask =

Using c#, how do I calculate the CIDR notation
? Is there an easy way to achieve this? Am I missing something?


Answer Source

I don't have it as C# code but here is the answer in VB. Should not be to hard to convert.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Dim someIP As Net.IPAddress = Net.IPAddress.Parse("")
    Dim someMASK As Net.IPAddress = Net.IPAddress.Parse("")

    Dim ipL As Long = IPtoLong(someIP)
    Dim maskL As Long = IPtoLong(someMASK)

    'Convert  Mask to CIDR(1-30)
    Dim oneBit As Long = &H80000000L
    Dim CIDR As Integer = 0

    For x As Integer = 31 To 0 Step -1
        If (maskL And oneBit) = oneBit Then CIDR += 1 Else Exit For
        oneBit = oneBit >> 1

    Dim answer As String = LongToIp(ipL And maskL) & " /" & CIDR.ToString

End Sub

Public Function IPtoLong(ByVal theIP As Net.IPAddress) As Long 'convert IP to number

    Dim IPb() As Byte = theIP.GetAddressBytes 'get the octets
    Dim addr As Long 'accumulator for address

    For x As Integer = 0 To 3
        addr = addr Or (CLng(IPb(x)) << (3 - x) * 8)
    Return addr

End Function

Public Function LongToIp(ByVal theIP As Long) As String 'convert number back to IP

    Dim IPb(3) As Byte '4 octets
    Dim addr As String = "" 'accumulator for address

    Dim mask8 As Long = MaskFromCidr(8) 'create eight bit mask

    For x = 0 To 3 'get the octets
        IPb(x) = CByte((theIP And mask8) >> ((3 - x) * 8))
        mask8 = mask8 >> 8
        addr &= IPb(x).ToString & "." 'add current octet to string
    Return addr.TrimEnd("."c)

End Function

Private Function MaskFromCidr(ByVal CIDR As Integer) As Long
    MaskFromCidr = CLng(2 ^ ((32 - CIDR)) - 1) Xor 4294967295L
End Function
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download