Better Windows Batch (.bat) File for Testing Internet Connections

I wrote a post yesterday about testing your internet connectivity using a Windows batch file, but since I cannot leave well-enough alone, I decided to keep working on it.

A few things to keep in mind…

  • The line “set ESC=” ends with a non-printable ASCII ESC character (ASCII 27; Hexadecimal 0x1B) that may not be visible in your browser. Editors like¬†Notepad++¬†show non-printable characters.
  • If you add “hosts” you should also add “names” – hosts entry will be displayed otherwise.
  • hosts index should start at zero with no sequence gaps
  • The “for” loop’s “end” should match count(hosts + 1)

Here is my finished code…

@echo off

rem ANSI Colors
set ESC=
set red=%ESC%[31m
set green=%ESC%[32m
set default=%ESC%[0m

rem Domain names or IPs
set hosts[0]=
set hosts[1]
set hosts[2]

rem Human-friendly names (optional)
set names[0]=Router
set names[1]=Google
set names[2]=Bing  

set /p "hosts[0]=Router IP address or [ENTER] for default (%hosts[0]%): "

echo Checking hosts...
for /l %%i in (0,1,3) do ( 
   call :pinghost %%i
choice /M "Check hosts again?"
if %errorlevel% == 1 goto :startover
exit /B %errorlevel%

setlocal EnableDelayedExpansion
set j=%~1
@ping !hosts[%j%]! -n 1 -w 1000 | FIND "TTL=" >nul
if %errorlevel% == 0 (
	if "!names[%j%]!" == "" (
		echo !hosts[%j%]!: %green%Online%default%
	) else (
		echo !names[%j%]!: %green%Online%default%
) else (
	if "!names[%j%]!" == "" (
		echo !hosts[%j%]!: %red%OFFLINE%default%
	) else (
		echo !names[%j%]!: %red%OFFLINE%default%
exit /B 0

Leave a Reply

Your email address will not be published. Required fields are marked *