Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch ERRORLEVEL ping response

I'm trying to use a batch file to confirm a network connection using ping. I want to do batch run and then print if the ping was successful or not. The problem is that it always displays 'failure' when run as a batch. Here is the code:

@echo off
cls
ping racer | find "Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),"
if not errorlevel 1 set error=success
if errorlevel 1 set error=failure
cls
echo Result: %error%
pause

'racer' is the name of my computer. I'm having my computer ping itself so I can eliminate the variable of a poor connection. As I said before, the batch always results in failure. Oddly enough, the program works fine if I copy the code into the command prompt. Does anyone know why the program works fine in the command prompt but doesn't work as a batch? Thanks

like image 594
LastStar007 Avatar asked Feb 17 '12 14:02

LastStar007


People also ask

What is Errorlevel in batch file?

Batch file error level: %ERRORLEVEL% is an environment variable that contains the last error level or return code in the batch file – that is, the last error code of the last command executed. Error levels may be checked by using the %ERRORLEVEL% variable as follows: IF %ERRORLEVEL% NEQ 0 ( DO_Something )

How do I know if my ping is successful?

You can use the ping command to test name resolution services, too. If you ping a destination by IP address, and the ping succeeds, you know you have basic connectivity. If you ping the same destination by hostname, and it fails, you know name resolution is not working.

What does ping do in batch?

Here is a simple ping command in a batch file that allows you to add servers/addresses to ping and it will return the ping time for all at once. An aspect of a ping check is when you get the time (latency) that it takes to send and then receive data.


2 Answers

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.

like image 101
Jelle Geerts Avatar answered Sep 21 '22 06:09

Jelle Geerts


Another variation without using any variable

ping racer -n 1 -w 100>nul || goto :pingerror
...

:pingerror
echo Host down
goto eof

:eof
exit /b
like image 31
Toni Lazazzera Avatar answered Sep 21 '22 06:09

Toni Lazazzera