How can I verify that a string is a valid IPv4 or IPv6 address in batch?

Check for valid IPv4:

@if (@X)==(@Y) @end /* JScript comment
    @echo off
    cscript //E:JScript //nologo "%~f0"  %*
    exit /b %errorlevel%
@if (@X)==(@Y) @end JScript comment */
WScript.Quit(ValidateIPaddress(WScript.Arguments.Item(0)));
function ValidateIPaddress(ipaddress) {
 return !(/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(ipaddress))
}

For valid IPv6 address:

@if (@X)==(@Y) @end /* JScript comment
    @echo off
    cscript //E:JScript //nologo "%~f0"  %*
    exit /b %errorlevel%
@if (@X)==(@Y) @end JScript comment */
WScript.Quit(ValidateIPaddress(WScript.Arguments.Item(0)));
function ValidateIPaddress(ipaddress) {
 return !(/(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))/gm.test(ipaddress))
}

Both are relying on the exit code, so here’s how they can be used:

call validIPV4.bat 12.12.12.12 && (
   echo valid ipv4 
) || (
   echo invalid ipv4
)

call validIPV4.bat 12.12.12.6000 && (
  echo valid ipv4 
) || (
  echo invalid ipv4
)

The first will print valid ipv4 the second invalid ipv4.

Or you can check the errorlevel:

call validIPV6.bat "1200:0000:AB00:1234:0000:2552:7777:1313"
if %errorlevel% equ 0 ( 
  echo valid ipv6 
) else (
  echo invalid ipv6
)

Leave a Comment

tech