@echo off :: This batch file uses Microsoft's PortQry utility to detect when :: there is no application listening on a given port. It returns 0 :: if an application is listening and 1 if not. :: It is intended for use with AlwaysUp :: (https://www.coretechnologies.com/products/AlwaysUp/) :: or Service Protector :: (https://www.coretechnologies.com/products/ServiceProtector/). :: Copyright © Core Technologies Consulting, LLC. All :: rights reserved. :: Here are a few variables that you should adjust. :: ** Please specify the IP address (or hostname) of the machine :: you wish to check, the port to be checked, and the full path to :: the PortQry executable on your system ** SET machine-name=127.0.0.1 SET port-number=80 SET portqry-exe-path="C:\PortQry\PortQry.exe" :: num-times-to-check == The number of times to check. The :: default of 5 is probably OK, but you can increase it if :: errors are frequent (but tolerable). SET num-times-to-check=5 :: num-seconds-between-checks == The time to wait between checks. :: Increase this to give your server more time to get back on its :: feet after an error. SET num-seconds-between-checks=10 SET /A nummilliseconds=%num-seconds-between-checks% * 1000 :: Loop "num-times-to-check" times. FOR /L %%X IN (1,1,%num-times-to-check%) DO CALL :loopbody %%X :: If we get here, then all checks failed. echo All %num-times-to-check% attempts of PortQry failed^! ^ Exiting with 1. exit 1 :loopbody :: Check the port once with PortQry, which returns: :: 0 if the port is listening :: 1 if the port is not listening :: 2 if the port is listening or filtered %portqry-exe-path% -n %machine-name% -e %port-number% -p TCP :: React to the code returned. IF %ERRORLEVEL% EQU 0 ( echo On attempt #%1, PortQry returned %ERRORLEVEL% - port is ^ listening. Exiting with 0. exit 0 ) else IF %ERRORLEVEL% EQU 2 ( echo On attempt #%1, PortQry returned %ERRORLEVEL% - port is ^ listening or filtered. Exiting with 0. exit 0 ) else IF %ERRORLEVEL% EQU 1 ( echo On attempt #%1, PortQry returned %ERRORLEVEL% - port is ^ NOT listening. ) else ( echo On attempt #%1, PortQry returned %ERRORLEVEL% - an ^ unexpected value. ) :: If this was not the last attempt, pause before trying again. :: Since DOS doesn't have a "sleep" command, use ping with an :: invalid address and a timeout (in milliseconds) to wait for :: a while. You can adjust the timeout value :: (num-seconds-between-checks) above. IF %1 LSS %num-times-to-check% ( echo Pausing for %num-seconds-between-checks% second^(s^)^ before the next attempt... ping 1.1.1.1 -n 1 -w %nummilliseconds% > nul )