Validate IP function: Difference between revisions

From NSIS Wiki
Jump to navigationJump to search
No edit summary
 
 
Line 19: Line 19:
Section
Section


   Push "192.168.0.1"
   Push "192.168.2.124"
   Call ValidateIP
   Call ValidateIP
   ${If} ${Errors}
   ${If} ${Errors}

Latest revision as of 04:32, 9 September 2011

Author: kichik (talk, contrib)


Description

Checks is a given IP address is valid and sets the error flag accordingly. The test is done in four steps. First, the given string is filtered to validate it contains only numbers and dots. Next, the number of dots is counted to validate it's 3 and the number of numbers is counted to validate it's 4. Finally, each number is validated by checking it's not out of range.

Usage Example

!include LogicLib.nsh
!include ValidateIP.nsh
 
Name "Validate IP test"
OutFile test.exe
 
XPStyle on
 
ShowInstDetails show
 
Section
 
  Push "192.168.2.124"
  Call ValidateIP
  ${If} ${Errors}
    DetailPrint "invalid IP"
  ${Else}
    DetailPrint "IP is ok"
  ${EndIf}
 
SectionEnd

Function Code

Put this code in a file named ValidateIP.nsh.

!include LogicLib.nsh
!include WordFunc.nsh
 
!insertmacro WordFind
!insertmacro StrFilter
 
Function ValidateIP
 
  Exch $0
  Push $1
  Push $2
 
  ${StrFilter} $0 1 "." "" $1
  ${If} $0 != $1
    # invalid charcaters used
    #   example: a127.0.0.1
    Goto error
  ${EndIf}
 
  ${WordFind} $0 . "#" $1
  ${If} $1 != 4
    # wrong number of numbers
    #   example: 127.0.0.
    Goto error
  ${EndIf}
 
  ${WordFind} $0 . "*" $1
  ${If} $1 != 3
    # wrong number of dots
    #   example: 127.0.0.1.
    Goto error
  ${EndIf}
 
  ${For} $2 1 4
    ${WordFind} $0 . +$2 $1
 
    ${If} $1 > 255
    ${OrIf} $1 < 0
      # invalid number
      #   example: 500.0.0.1
      Goto error
    ${EndIf}
  ${Next}
 
  Pop $2
  Pop $1
  Pop $0
 
  ClearErrors
 
  Return
 
  error:
 
    Pop $2
    Pop $1
    Pop $0
 
    SetErrors
 
FunctionEnd