13,006,002 members (37,490 online)
Tip/Trick
alternative version

#### Stats

9.3K views
2 bookmarked
Posted 29 Dec 2009

# Convert CIDR formatted string to its IPAddress Range representation

, 29 Dec 2009
 Rate this:
''' ''' Converts a CIDR formatted string to the IPAddress-range it represents. (Function handles IPv4 only). ''' ''' CIDR formatted string, example: "209.85.134.0/23" ''' A List(Of IPAddress): (0)=StartIP,...
```
''' <summary>
''' Converts a CIDR formatted string to the IPAddress-range it represents. (Function handles IPv4 only).
''' </summary>
''' <param name="zCIDR">CIDR formatted string, example: "209.85.134.0/23"</param>
''' <returns>A List(Of IPAddress): (0)=StartIP, (1)=EndIP</returns>
''' <remarks>the machine's endianness is not considered by this function! Little Endian is assumed here.</remarks>
Private Function CIDR_to_IPRange(ByVal zCIDR As String) As List(Of IPAddress)

'   zReturn will contain:  zReturn(0) = StartIP, zReturn(1) = EndIP
Dim zReturn As New List(Of IPAddress)

'   Split out the StartIP and /suffix from zCIDR = "255.255.255.255/32"
'   zSAP(0) should then contain the IP prefix = "255.255.255.255"
'   zSAP(1) will contain the suffix = "32"
Dim zSAP As New List(Of String) _
(zCIDR.Trim.Split("/".ToCharArray, 2, StringSplitOptions.RemoveEmptyEntries))

Try

Catch ex As Exception
'   No StartIP found, so return Nothing
Return Nothing

End Try

'   Calculate and add the EndIP
Try
'   NOTE :: the wildcard bits calculation =  2^(32-zSuffix) - 1
'   zPrefix must be in the 0-32 range (a suffix of 32 means the StartIP is the same as EndIP)
Dim zSuffix As Long = Math.Min(32, Math.Max(0, CLng(zSAP(1))))

Catch ex As Exception
'   Either the /suffix wasn't given, or the IPAddress is out of range (maximum: 4294967295)
'   I'm choosing to set the EndIP = StartIP if an error happens

End Try

Return zReturn

End Function

''' <summary>
''' Converts an IPv4 IPAddress, which is just a 32bit Unsigned Integer, to a Long
''' </summary>
''' <param name="zReverse">This allows you to consider the order of the given Byte array.</param>
''' <returns>A Long representing an IPAddress</returns>
''' <remarks></remarks>
Public Function IP_to_Long(ByVal zAddressBytes() As Byte, _
Optional ByRef zReverse As Boolean = False) As Long

If zReverse Then
Return CLng( _

Else
Return CLng( _

End If

End Function
```

## Share

 Belgium
MSDN VB.NET Forums

## You may also be interested in...

 -- There are no messages in this forum --
Web02 | 2.8.170628.1 | Last Updated 29 Dec 2009