Sign in to follow this  
Followers 0
Raestlin

Function To Verify Valid Ip Input...

9 posts in this topic

Here's a little something I created to validate whether an input is in valid IP notation.

I'm trying to rewrite it using "StringRegExp" instead, but this works for now at least. :-)

Enjoy!!!

; Function to validate whether an input is in a valid IP address notation
Func ValidateIP($ipaddr)
   Local $validip, $dummy, $d1
   $validip = 0
   $dummy = StringSplit($ipaddr, ".")
   If $dummy[0] = 4 Then; String at least has 4 octets
      If (Int($dummy[1]) > 0) And (Int($dummy[1]) < 256) Then; Check 1st octet = 1-255
         For $d1 = 2 to 4
            If (Int($dummy[$d1]) > -1) And (Int($dummy[$d1]) < 256) Then; Check 2nd, 3rd, 4th octet = 0-255
               $validip = 1
            EndIf
         Next
      EndIf
   EndIf
   If $validip Then
      Return 1
   Else
      MsgBox(48,"Invalid IP","The IP address you entered is not in a valid format. Please check it and try again.")
      Return 0
   EndIf
EndFunc

Share this post


Link to post
Share on other sites



I've done several tests on this and it seems to work. Let me know if you find an exception.

$test = verifyIP("10.1.1.1")

If $test == 1 Then
    MsgBox(0, "Verified", "That is a valid IP address.")
Else
    MsgBox(48, "Error", "This is not a valid IP address.")
EndIf

Func verifyIP($o_IP)
    
    Local $IPArray, $pattern, $thisSegment, $error
    $IPArray = StringSplit($o_IP, ".")
    $pattern = StringRegExp($o_IP, "(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})")
    
    If $pattern == 1 Then
        If $IPArray[0] > 4 Then
            $error = 1
        Else
            If $o_IP == "255.255.255.255" Then
                $error = 1
            Else
                For $i = 1 To 4
                    $thisSegment = $IPArray[$i]
                    If $thisSegment > 255 Then
                        $error = 1
                        ExitLoop
                    ElseIf $i == 1 And $thisSegment == 255 Or $thisSegment == 0 Then
                        $error = 1
                        ExitLoop
                    EndIf
                Next
            EndIf
        EndIf
    Else
        $error = 1
    EndIf
    If $error == 1 Then
        Return 0
    Else
        Return 1
    EndIf
    
EndFunc  ;==>verifyIP

Share this post


Link to post
Share on other sites

I've done several tests on this and it seems to work. Let me know if you find an exception.

$test = verifyIP("10.1.1.1")

If $test == 1 Then
    MsgBox(0, "Verified", "That is a valid IP address.")
Else
    MsgBox(48, "Error", "This is not a valid IP address.")
EndIf

Func verifyIP($o_IP)
    
    Local $IPArray, $pattern, $thisSegment, $error
    $IPArray = StringSplit($o_IP, ".")
    $pattern = StringRegExp($o_IP, "(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})")
    
    If $pattern == 1 Then
        If $IPArray[0] > 4 Then
            $error = 1
        Else
            If $o_IP == "255.255.255.255" Then
                $error = 1
            Else
                For $i = 1 To 4
                    $thisSegment = $IPArray[$i]
                    If $thisSegment > 255 Then
                        $error = 1
                        ExitLoop
                    ElseIf $i == 1 And $thisSegment == 255 Or $thisSegment == 0 Then
                        $error = 1
                        ExitLoop
                    EndIf
                Next
            EndIf
        EndIf
    Else
        $error = 1
    EndIf
    If $error == 1 Then
        Return 0
    Else
        Return 1
    EndIf
    
EndFunc ;==>verifyIP
The only thing I see wrong with it, is that it appears that it would mark

valid subnet mask entries as invalid.

If you input "255.255.0.0" as a subnet mask entry, the code would fail because

$i = 1 and $thissegment = 255. Although, that would be a valid subnet mask.

~ Chris (Taz)

Share this post


Link to post
Share on other sites

Here's a little something I created to validate whether an input is in valid IP notation.

I'm trying to rewrite it using "StringRegExp" instead, but this works for now at least. :-)

Enjoy!!!

; Function to validate whether an input is in a valid IP address notation
Func ValidateIP($ipaddr)
   Local $validip, $dummy, $d1
   $validip = 0
   $dummy = StringSplit($ipaddr, ".")
   If $dummy[0] = 4 Then; String at least has 4 octets
      If (Int($dummy[1]) > 0) And (Int($dummy[1]) < 256) Then; Check 1st octet = 1-255
         For $d1 = 2 to 4
            If (Int($dummy[$d1]) > -1) And (Int($dummy[$d1]) < 256) Then; Check 2nd, 3rd, 4th octet = 0-255
               $validip = 1
            EndIf
         Next
      EndIf
   EndIf
   If $validip Then
      Return 1
   Else
      MsgBox(48,"Invalid IP","The IP address you entered is not in a valid format. Please check it and try again.")
      Return 0
   EndIf
EndFunc

I came here looking for a script to do just this.  However, this one was not tested very well.  For example, as you can see by the code, he is resetting the VALID IP flag on every loop.  Therefore only the last octet has to be correct for the IP to come back successful.  I modified it so that if any are WRONG, it will come back as failed.  Its still not perfect, but better.

; Function to validate whether an input is in a valid IP address notation from autoit community. Edited by Chip Means to correct errors
Func ValidateIP($ipaddr)
   Local $validip, $dummy, $d1
   $validip = 0
   $dummy = StringSplit($ipaddr, ".")
   If $dummy[0] = 4 Then; String at least has 4 octets
      $validip = 1
      If (Int($dummy[1]) > 0) And (Int($dummy[1]) < 256) Then; Check 1st octet = 1-255
         For $d1 = 2 to 4
            If (Int($dummy[$d1]) < 0) or (Int($dummy[$d1]) > 256) Then; Check 2nd, 3rd, 4th octet = 0-255
               $validip = 0
            EndIf
         Next
      EndIf
   EndIf
   If $validip Then
      Return 1
   Else
      MsgBox(48,"Invalid IP","The IP address you entered is not in a valid format. Please check it and try again.")
      Return 0
   EndIf
EndFunc

Share this post


Link to post
Share on other sites

There are several examples that aren't 9 years old that would fit your purpose, the wiki has a few of them, and there was a thread posted within the last 2 weeks discussing this as well.


If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Share this post


Link to post
Share on other sites

I don't completely understand what you are trying to do here. Are you trying to find valid I.P.'s? Wouldn't it be easier to use ping and display your results based on the outcome?

Share this post


Link to post
Share on other sites

Brewman, I know the post is old.  However, it was also the top result on google, which is how I found it.  Perhaps next time I will search the forum itself.  I wanted to update it a bit in case anyone else stumbled across it.  Sorry for ressurecting.

Stim - the purpose is to verify that the string COULD be an IP.  4 octets, greater than 0, less than 256, that sort of thing.  So that if I have an input box for an IP, you can check against it and throw an error.

Share this post


Link to post
Share on other sites

#9 ·  Posted (edited)

Here's something I wrote many moons ago when I was learning networking... maybe some code will be of use to you. It's not fully finished as far as I remember, it wasn't calculating correct results for single Addresses (that is, addresses with a subnet mask of 32) 

#include <EditConstants.au3>
#include <GUIConstantsEx.au3>
#include <StaticConstants.au3>
#include <WindowsConstants.au3>
#include <WinAPI.au3>
#include <Array.au3>
#include <Misc.au3>

Dim $ipadd[4], $activebox, $pressedbackspaceonce = False
Dim $netmaskcalc[2][32]
For $i = 0 to Ubound($netmaskcalc, 2) - 1
    If $i >= Ubound($netmaskcalc, 2) - 1 Then ExitLoop
    $netmaskcalc[1][$i] = 128
    $netmaskcalc[1][$i+1] = 64
    $netmaskcalc[1][$i+2] = 32
    $netmaskcalc[1][$i+3] = 16
    $netmaskcalc[1][$i+4] = 8
    $netmaskcalc[1][$i+5] = 4
    $netmaskcalc[1][$i+6] = 2
    $netmaskcalc[1][$i+7] = 1
    $i += 7
Next
Dim $subnetmask[4]

#Region ### START $maingui ###
GUISetFont(14, 400, 0, "MS Sans Serif")
$maingui = GUICreate("Network Calculator", 456, 382, 466, 171)
$ipadd[0] = GUICtrlCreateInput("", 8, 32, 41, 32)
GUICtrlSetFont(-1, 14, 400, 0, "MS Sans Serif")
$ipadd[1] = GUICtrlCreateInput("", 64, 32, 41, 32)
GUICtrlSetFont(-1, 14, 400, 0, "MS Sans Serif")
$ipadd[2] = GUICtrlCreateInput("", 119, 32, 41, 32)
GUICtrlSetFont(-1, 14, 400, 0, "MS Sans Serif")
$ipadd[3] = GUICtrlCreateInput("", 175, 32, 41, 32)
GUICtrlSetFont(-1, 14, 400, 0, "MS Sans Serif")
GUISetFont(18, 400, 0, "MS Sans Serif")
GUICtrlCreateLabel(".", 50, 36, 10, 33, $SS_CENTER)
GUICtrlCreateLabel(".", 107, 36, 10, 33, $SS_CENTER)
GUICtrlCreateLabel(".", 162, 36, 10, 33, $SS_CENTER)
GUICtrlCreateLabel("/", 220, 36, 11, 33, $SS_CENTER)
GUISetFont(14, 400, 0, "MS Sans Serif")
$subnetmaskshortinput = GUICtrlCreateInput("", 236, 33, 41, 32)
GUICtrlSetFont(-1, 14, 400, 0, "MS Sans Serif")
$subnetmask[0] = GUICtrlCreateInput("", 236, 78, 41, 32, $ES_READONLY)
GUICtrlSetFont(-1, 14, 400, 0, "MS Sans Serif")
$subnetmask[1] = GUICtrlCreateInput("", 289, 78, 41, 32, $ES_READONLY)
GUICtrlSetFont(-1, 14, 400, 0, "MS Sans Serif")
$subnetmask[2] = GUICtrlCreateInput("", 344, 78, 41, 32, $ES_READONLY)
GUICtrlSetFont(-1, 14, 400, 0, "MS Sans Serif")
$subnetmask[3] = GUICtrlCreateInput("", 400, 78, 41, 32, $ES_READONLY)
GUICtrlSetFont(-1, 14, 400, 0, "MS Sans Serif")
GUISetFont(18, 400, 0, "MS Sans Serif")
GUICtrlCreateLabel(".", 277, 82, 10, 33, $SS_CENTER)
GUICtrlCreateLabel(".", 332, 82, 10, 33, $SS_CENTER)
GUICtrlCreateLabel(".", 387, 82, 10, 33, $SS_CENTER)
GUICtrlCreateLabel("-", 295, 276, 36, 17, BitOR($SS_CENTER,$SS_CENTERIMAGE))
GUISetFont(14, 400, 0, "MS Sans Serif")
GUICtrlCreateLabel("IP address:", 8, 3, 97, 28)
GUICtrlCreateLabel("Subnet mask:", 237, 3, 118, 28)
GUICtrlCreateLabel("Network address:", 10, 147, 150, 28)
GUICtrlCreateLabel("Broadcast address:", 10, 202, 164, 28)
GUICtrlCreateLabel("IP range:", 10, 250, 79, 28)
GUICtrlCreateLabel("Hosts:", 10, 345, 56, 28)
GUISetFont(14, 400, 0, "MS Sans Serif")
$networkaddinput = GUICtrlCreateInput("0.0.0.0", 176, 143, 270, 32, $ES_READONLY)
GUICtrlSetFont(-1, 14, 400, 0, "MS Sans Serif")
$broadcastaddinput = GUICtrlCreateInput("0.0.0.0", 176, 198, 270, 32, $ES_READONLY)
GUICtrlSetFont(-1, 14, 400, 0, "MS Sans Serif")
$iprangeinput1 = GUICtrlCreateInput("0.0.0.0", 176, 246, 270, 32, $ES_READONLY)
GUICtrlSetFont(-1, 14, 400, 0, "MS Sans Serif")
$iprangeinput2 = GUICtrlCreateInput("0.0.0.0", 176, 296, 270, 32, $ES_READONLY)
GUICtrlSetFont(-1, 14, 400, 0, "MS Sans Serif")
$hostsinput = GUICtrlCreateInput("0", 176, 341, 270, 32, $ES_READONLY)
GUICtrlSetFont(-1, 14, 400, 0, "MS Sans Serif")
GUISetState(@SW_SHOW)
#EndRegion ### END $maingui ###

GUIRegisterMsg($WM_COMMAND, "WM_COMMAND")

While 1
    $nMsg = GUIGetMsg()
    Switch $nMsg
        Case $GUI_EVENT_CLOSE
            Exit
    EndSwitch
    If _IsPressed('08') And $activebox <= 3 And $activebox <> 0 Then
        If StringStripWS(GUICtrlRead($ipadd[$activebox]), 8) = '' Then
            If $pressedbackspaceonce = False Then
                $pressedbackspaceonce = True
            Else
                _WinAPI_SetFocus(ControlGetHandle('', '', $ipadd[$activebox-1]))
                $pressedbackspaceonce = False
            EndIf
        EndIf
        Sleep(100)
    ElseIf _IsPressed('08') And $activebox = 4 Then
        If StringStripWS(GUICtrlRead($subnetmaskshortinput), 8) = '' Then
            If $pressedbackspaceonce = False Then
                $pressedbackspaceonce = True
            Else
                _WinAPI_SetFocus(ControlGetHandle('', '', $ipadd[3]))
                $pressedbackspaceonce = False
            EndIf
        EndIf
        Sleep(100)
    EndIf
WEnd

Func WM_COMMAND($hWnd, $iMsg, $wParam, $lParam)
    Local $iCode = BitShift($wParam, 16)
    Local $nIDFrom = BitAND($wParam, 0xFFFF)

    Switch $hWnd
        Case $maingui
            Switch $nIDFrom
                Case $ipadd[0] to $ipadd[3]
                    Switch $iCode
                        Case $EN_CHANGE
                            $activebox = _ArraySearch($ipadd, $nIDFrom)
                            $string = GUICtrlRead($nIDFrom)
                            $restrict = "\d."
                            $offset = StringRegExpReplace($string,"["&$restrict&"]","")
                            $restricted = StringRegExpReplace($string,"["&$offset&"]","")
                            GUICtrlSetData($nIDFrom, $restricted)
                            If $string > 255 Then GUICtrlSetData($nIDFrom, '255')
                            If StringInStr($string, '.') Then
                                GUICtrlSetData($nIDFrom, StringReplace($string, '.', ''))
                                If $activebox < 3 Then
                                    _WinAPI_SetFocus(ControlGetHandle('', '', $ipadd[$activebox+1]))
                                ElseIf $activebox = 3 Then
                                    _WinAPI_SetFocus(ControlGetHandle('', '', $subnetmaskshortinput))
                                EndIf
                            EndIf
                            CalculateResults()
                        Case $EN_SETFOCUS
                            $activebox = _ArraySearch($ipadd, $nIDFrom)
                    EndSwitch
                Case $subnetmaskshortinput
                    Switch $iCode
                        Case $EN_CHANGE
                            $activebox = 4
                            $string = GUICtrlRead($nIDFrom)
                            $restrict = "\d"
                            $offset = StringRegExpReplace($string,"["&$restrict&"]","")
                            $restricted = StringRegExpReplace($string,"["&$offset&"]","")
                            GUICtrlSetData($nIDFrom, $restricted)
                            If $string > 32 Then GUICtrlSetData($nIDFrom, '32')
                            If StringStripWS($string, 8) <> '' Then
                                CalculateSubNetMask(GUICtrlRead($nIDFrom))
                            Else
                                For $i = 0 To 3
                                    GUICtrlSetData($subnetmask[$i], '')
                                Next
                            EndIf
                            CalculateResults()
                        Case $EN_SETFOCUS
                            $activebox = 4
                    EndSwitch
            EndSwitch
    EndSwitch

    Return $GUI_RUNDEFMSG
EndFunc  ;==>ED_WM_COMMAND

Func CalculateSubNetMask($prefix)
    Local $netmaskdec[4]
    For $i = 0 to Ubound($netmaskcalc, 2) - 1
        $netmaskcalc[0][$i] = 0
    Next
    For $i = 0 to $prefix - 1
        $netmaskcalc[0][$i] = 1
    Next
    For $i = 0 to 7
        If $netmaskcalc[0][$i] = 1 Then
            $netmaskdec[0] += $netmaskcalc[1][$i]
        EndIf
    Next
    For $i = 8 to 15
        If $netmaskcalc[0][$i] = 1 Then
            $netmaskdec[1] += $netmaskcalc[1][$i]
        EndIf
    Next
    For $i = 16 to 23
        If $netmaskcalc[0][$i] = 1 Then
            $netmaskdec[2] += $netmaskcalc[1][$i]
        EndIf
    Next
    For $i = 24 to 31
        If $netmaskcalc[0][$i] = 1 Then
            $netmaskdec[3] += $netmaskcalc[1][$i]
        EndIf
    Next

    For $i = 0 To 3
        If StringStripWS($netmaskdec[$i], 8) = '' Then $netmaskdec[$i] = 0
    Next

    For $i = 0 To 3
        GUICtrlSetData($subnetmask[$i], $netmaskdec[$i])
    Next

EndFunc

Func CalculateResults()
    Local $calc = True, $broadcastadd, $netadd, $iprange1, $iprange2, $hosts, $ipaddress, $t, $finalhosts
    Local $iparray[4], $netmaskarray[4], $netaddarray[4], $invmaskarray[4], $broadcastaddarray[4]

    For $i = 0 to 3
        If StringStripWS(GUICtrlRead($ipadd[$i]), 8) = '' Or StringStripWS(GUICtrlRead($subnetmask[$i]), 8) = '' Then
            $calc = False
            ExitLoop
        EndIf
    Next

    If $calc = True And GUICtrlRead($subnetmaskshortinput) <> BitAND(32, 0) Then
        For $i = 0 to Ubound($iparray) - 1
            $iparray[$i] = GUICtrlRead($ipadd[$i])
        Next
        For $i = 0 to Ubound($netmaskarray) - 1
            $netmaskarray[$i] = GUICtrlRead($subnetmask[$i])
        Next
        For $i = 0 To 3
           $netaddarray[$i] = BitAND($iparray[$i], $netmaskarray[$i])
           $invmaskarray[$i] = BitNOT($netmaskarray[$i] - 256)
           $broadcastaddarray[$i] = BitOR($netaddarray[$i], $invmaskarray[$i])
        Next
        For $i = 0 To 3
            If $i <> 3 Then
                $netadd &= $netaddarray[$i] & '.'
            Else
                $netadd &= $netaddarray[$i]
            EndIf
        Next
        GUICtrlSetData($networkaddinput, $netadd)
        For $i = 0 To 3
            If $i <> 3 Then
                $broadcastadd &= $broadcastaddarray[$i] & '.'
            Else
                $broadcastadd &= $broadcastaddarray[$i]
            EndIf
        Next
        GUICtrlSetData($broadcastaddinput, $broadcastadd)
        For $i = 0 To 3
            If $i <> 3 Then
                $iprange1 &= $netaddarray[$i] & '.'
            Else
                $iprange1 &= $netaddarray[$i] + 1
            EndIf
        Next
        GUICtrlSetData($iprangeinput1, $iprange1)
        For $i = 0 To 3
            If $i <> 3 Then
                $iprange2 &= $broadcastaddarray[$i] & '.'
            Else
                $iprange2 &= $broadcastaddarray[$i] - 1
            EndIf
        Next
        GUICtrlSetData($iprangeinput2, $iprange2)
        $hosts = ($invmaskarray[0] + 1) * ($invmaskarray[1] + 1) * ($invmaskarray[2] + 1) * ($invmaskarray[3] + 1) - 2
        $hostsarray = StringSplit($hosts, "")
        For $x = $hostsarray[0] to 1 Step -1
            $t = $t +1
            If $t = 4 Then
                $finalhosts = ',' & $finalhosts
                $t = 1
            EndIf
            $finalhosts = $hostsarray[$x] & $finalhosts
        Next
        GUICtrlSetData($hostsinput, $finalhosts)
    ElseIf $calc = True And GUICtrlRead($subnetmaskshortinput) = 32 Then
        For $i = 0 to 3
            If $i <> 3 Then
                $ipaddress &= GUICtrlRead($ipadd[$i]) & '.'
            Else
                $ipaddress &= GUICtrlRead($ipadd[$i])
            EndIf
        Next
        GUICtrlSetData($networkaddinput, $ipaddress)
        GUICtrlSetData($broadcastaddinput, $ipaddress)
        GUICtrlSetData($iprangeinput1, $ipaddress)
        GUICtrlSetData($iprangeinput2, $ipaddress)
        GUICtrlSetData($hostsinput, '1')
    Else
        GUICtrlSetData($networkaddinput, '0.0.0.0')
        GUICtrlSetData($broadcastaddinput, '0.0.0.0')
        GUICtrlSetData($iprangeinput1, '0.0.0.0')
        GUICtrlSetData($iprangeinput2, '0.0.0.0')
        GUICtrlSetData($hostsinput, '0')
    EndIf

EndFunc
Edited by mpower

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0