How to check a valid IP Address

Another idea to check an IP Address format

The Code:

'will make the text black if its a valid IP address
'or red if its not

Private Sub Text1_Change()
Text1.ForeColor = 255
If IsIP(Text1.Text) Then Text1.ForeColor = 0
End Sub



'place this part in a module
Public Function IsIP(TestAddress As String) As Boolean

Dim IPt As String
Dim TQ As Long
Dim TT As Long
Dim TW As Long
Dim IPTemp As Long

IsIP = False 'Set return value as false

On Error GoTo cockup
'if an error occures the string is not valid

If Left(TestAddress, 1) = "." Then Exit Function
If Right(TestAddress, 1) = "." Then Exit Function
'check first and last are not "."

For TQ = 1 To Len(TestAddress) 'test all chars
IPt = Mid(TestAddress, TQ, 1)
If IPt <> "." Then 'if its not a "." it must be 0-9
If Asc(IPt) > 57 Or Asc(IPt) < 48 Then Exit Function
End If
Next TQ

TQ = InStr(1, TestAddress, ".", vbTextCompare)
'find the three dots
TT = InStr(TQ + 1, TestAddress, ".", vbTextCompare)
TW = InStr(TT + 1, TestAddress, ".", vbTextCompare)
If InStr(TW + 1, TestAddress, ".", vbTextCompare) <> 0 Then Exit Function
'if there is a fourth then the string is invalid

'test each number is between 0 and 255
IPTemp = Val(Left(TestAddress, TQ - 1))
If IPTemp > 255 Or IPTemp < 0 Then Exit Function

IPTemp = Val(Mid(TestAddress, TQ + 1, TT - TQ - 1))
If IPTemp > 255 Or IPTemp < 0 Then Exit Function

IPTemp = Val(Mid(TestAddress, TT + 1, TW - TT - 1))
If IPTemp > 255 Or IPTemp < 0 Then Exit Function

IPTemp = Val(Right(TestAddress, Len(TestAddress) - TW))
If IPTemp > 255 Or IPTemp < 0 Then Exit Function

IsIP = True 'it has passed all tests so make it true

cockup:
End Function

0 comments:

Post a Comment