IP verification in batch script - first match by findstr, secondly verify by for loops (only using windows built in functinallity?

前端 未结 4 1965
没有蜡笔的小新
没有蜡笔的小新 2021-01-06 23:36

This is a question for the batch pro\'s i guess. Seems a lot of people do stumble over IP veriffication while batching, while just using windows built in functinallity, but

4条回答
  •  不知归路
    2021-01-07 00:25

    Basic structure for ip validation. Adapt as needed

    @echo off
        setlocal enableextensions enabledelayedexpansion
    
        rem try some ip addresses 
        for %%i in ("1.1.1.1" "0.1.1.1" "250.1024.1.1" "10.0.2.1" "something" "" ) do (
    
            echo --------------------------------------------
    
            rem call with a variable to get return value
            call :validateIP %%~i ret 
            echo %%~i : return value : !ret! 
    
            rem call with or without variable to get errorlevel
            call :validateIP %%~i  && echo %%i is valid || echo %%i is invalid
    
        )   
    
        exit /b 
    
    :validateIP ipAddress [returnVariable]
        rem prepare environment
        setlocal 
    
        rem asume failure in tests : 0=pass 1=fail : same for errorlevel
        set "_return=1"
    
        rem test if address conforms to ip address structure
        echo %~1^| findstr /b /e /r "[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*\.[0-9][0-9]*" >nul
    
        rem if it conforms to structure, test each octet for rage values
        if not errorlevel 1 for /f "tokens=1-4 delims=." %%a in ("%~1") do (
            if %%a gtr 0 if %%a lss 255 if %%b leq 255 if %%c leq 255 if %%d gtr 0 if %%d leq 254 set "_return=0"
        )
    
    :endValidateIP
        rem clean and return data/errorlevel to caller
        endlocal & ( if not "%~2"=="" set "%~2=%_return%" ) & exit /b %_return%
    

提交回复
热议问题