Validating IP Addresses
by Miles Forrest - Independent Developer
This little routine has only one purpose in life - to check whether an IP Address is valid.
It checks two things - that the address is in the form xxx.xxx.xxx.xxx and that each xxx is between 1 and 3 numeric digits, and its numeric value is in the range 0-255.
It looks a bit hairy (and is a bit hairy!) but it's fast - which was important because when I first developed it I had to process thousands of IP Addresses.
I hope it's of use to someone out there.
Public Function IsIPAddress(ByVal zvIPAddressID As String) As Boolean
Dim ipLengthOfGroup As Integer
Dim ipPosition As Integer
Dim ipNoOfGroups As Integer
IsIPAddress = False
ipNoOfGroups = 0
ipLengthOfGroup = 0
For ipPosition = 1 To Len(zvIPAddressID)
Select Case Asc(Mid$(zvIPAddressID, ipPosition, 1))
Case 48 To 57
ipLengthOfGroup = ipLengthOfGroup + 1
If ipLengthOfGroup = 4 Then
Exit Function
End If
Case 46
ipNoOfGroups = ipNoOfGroups + 1
If ((ipNoOfGroups = 4) Or (ipLengthOfGroup = 0)) Or _
(Val(Mid$(zvIPAddressID, ipPosition - ipLengthOfGroup, ipLengthOfGroup)) > 256) Then
Exit Function
End If
ipLengthOfGroup = 0
Case Else
Exit Function
End Select
Next ipPosition
IsIPAddress = (ipNoOfGroups = 3) And (ipLengthOfGroup > 0) And _
(Val(Mid$(zvIPAddressID, ipPosition - ipLengthOfGroup, ipLengthOfGroup)) < 256)
End Function