Batch ERRORLEVEL ping response

Testing for 0% loss may give a false positive, in this scenario: Let's say you normally have a network drive on some_IP-address, and you want to find out whether or not it's on.

If that drive is off, and you ping some_IP-address, the IP address from which you ping, will respond:
Answer from your_own_IP-address: target host not reachable
... 0% loss

You might be better off using if exist or if not exist on that network location.


A more reliable ping error checking method:

@echo off
set "host=192.168.1.1"

ping -n 1 "%host%" | findstr /r /c:"[0-9] *ms"

if %errorlevel% == 0 (
    echo Success.
) else (
    echo FAILURE.
)

This works by checking whether a string such as 69 ms or 314ms is printed by ping.

(Translated versions of Windows may print 42 ms (with the space), hence we check for that.)

Reason:

Other proposals, such as matching time= or TTL are not as reliable, because pinging IPv6 addresses doesn't show TTL (at least not on my Windows 7 machine) and translated versions of Windows may show a translated version of the string time=. Also, not only may time= be translated, but sometimes it may be time< rather than time=, as in the case of time<1ms.


If you were to

echo "Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),"

you would see the % is stripped. You need to escape it as % has a special meaning within a batch file:

"Packets: Sent = 4, Received = 4, Lost = 0 (0%% loss),"

However its simpler to use TTL as the indication of success;

.. | find "TTL"

I 'm not exactly sure what the interaction between FIND and setting the error level is, but you can do this quite easily:

@echo off
for /f %%i in ('ping racer ^| find /c "(0%% loss)"') do SET MATCHES=%%i
echo %MATCHES%

This prints 0 if the ping failed, 1 if it succeeded. I made it look for just "0% loss" (not specifically 4 pings) so that the number of pings can be customized.

The percent sign has been doubled so that it's not mistaken for a variable that should be substituted.

The FOR trick serves simply to set the output of a command as the value of an environment variable.