batch-fileping

Ping Test Using Bat File - Trouble with errorlevel


I am working on setting up a LAN ping test using a batch file. The code i have works great for websites but it acts strange for local IPs. I am running the ping test on 3 computers that i know the IPs of. No matter which one i unplug, when i run the code below, the %errorlevel% is always 0 on all three computers. It never equals to 1 like it does on a website. How can i resolve this?

@echo off
cls
Set IPaddress=www.google.com
PING %IPaddress% -n 1
 call :PingTest

Set IPaddress=www.yahoo.com
PING %IPaddress% -n 1
 call :PingTest

Set IPaddress=www.unabletoping.com
PING %IPaddress% -n 1
 call :PingTest

pause > null
exit

:PingTest
IF %errorlevel% EQU 1 (echo "Server is Offline") else (GOTO:EOF)

Solution

  • When you ping an non accesible address in your subnet, you get an "unreachable" answer, with 1 packet sent, 1 packed received, 0 packets lost. Errorlevel is not set.

    When you ping an non accesible address out of your subnet, you get a "timeout" answer, with 1 packet sent, 0 packet received, 1 packet lost. Errorlevel is set.

    And, you can ping an active machine, lost packets and get an errorlevel

    And, you can ping an active/inactive machine, get TTL expired and get no errorlevel

    Better, check for content of ping response.

    ping -n 1 192.168.1.1 | find "TTL=" >nul
    if errorlevel 1 (
        echo host not reachable
    ) else (
        echo host reachable
    )