12

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

13 Answers 13

32

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.

3
  • 4
    ms is also translated in other languages(e.g. Russian).
    – littleguga
    Commented Oct 28, 2016 at 8:55
  • Hmm. "ms" worked on French Windows. It would be great if anyone could look into, and post, the specifics of this, notably on which languages "ms" would fail on.
    – BuvinJ
    Commented Jan 15, 2021 at 21:23
  • /r and /c for me doesn't work for some reason, and it seems /c is the default AFAIK. I was looking for certain keywords when WiFi disconnects, then, reconnect. The correct syntax was 'ping -n 1 google.cl | findstr "Compruebe agotado"' in my case. Commented Aug 16, 2022 at 5:43
4

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"
1
  • I saw something about using "TTL" on another post, but wanted to avoid it because someone said it can return a false positive. Commented Feb 17, 2012 at 16:35
4

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.

3

Another variation without using any variable

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

:pingerror
echo Host down
goto eof

:eof
exit /b
2

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.

2
  • Thanks for your help! [This] (stackoverflow.com/questions/3050898/…) link was where I started this project, and its example used FIND. Commented Feb 17, 2012 at 16:41
  • 3
    It may not works. e.g. I got %0 loss when get response like Host unreachable
    – moteus
    Commented Oct 9, 2017 at 8:01
1

Yes ping fails to return the correct errorlevel. To check the network connection and the computer I used "net view computername" then checked %errorlevel% - simple and easy

1
  • OP intended to implement a sort of connection quality test - therefore a ping with several answers and checking for 0% loss. net viewwon't do that.
    – Stephan
    Commented Jun 24, 2015 at 6:38
0

First of all

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

Does not work. If it won't fail, it will detect 0%, because it has 0%. If it fails, does not work either, because it will have 100% loss, which means, it found the 0% loss part behind the 10 10(0% loss)

Have it detect for 100% loss like so:

>for /f %%i in ('ping  -n 1 -l 1 %pc% ^| find /c "(100%% loss)"') do SET check=%%i

Errorlevel might be a bit messed up, but it works like a charm:

>if '%check%'=='1' goto fail
>if '%check%'=='0' echo %pc% is online.&goto starting

1 means it failed 0 means it succeeded

In my script is use links. Goto fail will go to :fail in my script which will message me that %pc% (which I'll have the user input in the beginning) is offline and will go for another run.

>:fail
>color 0c
>title %pc% is offline
>echo %pc% is offline
>PING -n 6 127.0.0.1>nul
>goto choice

I hope this helps.

0

The most simple solution to this I can think of:

set error=failure
ping racer -n 1 -w 100>nul 2>&1 && set error=success

Of course, -w needs to be adjusted if on a slow link (100ms might be too short over Dialup ;-))

regards

0

ping has an errorlevel output value. Success is 0, failure is 1. Just do this:

C:\>ping 4.2.2.2

Pinging 4.2.2.2 with 32 bytes of data:

Reply from 4.2.2.2: bytes=32 time=28ms TTL=57
Reply from 4.2.2.2: bytes=32 time=29ms TTL=57
Reply from 4.2.2.2: bytes=32 time=30ms TTL=57
Reply from 4.2.2.2: bytes=32 time=29ms TTL=57

Ping statistics for 4.2.2.2:
    Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 28ms, Maximum = 30ms, Average = 29ms

C:\>echo %errorlevel%
0

C:\>ping foo.bar
Ping request could not find host foo.bar. Please check the name and try again.

C:\>echo %errorlevel%
1

As you can see there is no need for all this scripting overkill.

2
  • 7
    problem with this is the errorlevel is only set to 1 if the host is unknown - if you ping an ip address which doesn't respond it still returns 0
    – l0ft13
    Commented Mar 26, 2014 at 12:22
  • Agree. Here's the situation described further: C:\>ping -n 1 172.25.0.1 Pinging 172.25.0.1 with 32 bytes of data: Reply from 172.25.1.1: Destination host unreachable. Ping statistics for 172.25.0.1: Packets: Sent = 1, Received = 1, Lost = 0 (0% loss), C:\>echo %errorlevel% 0
    – jdw
    Commented Oct 31, 2015 at 12:42
0

Based on Alex K's note, this works for me on Windows 7:

@echo off
setlocal enableextensions enabledelayedexpansion

for /f %%i in (PCS.TXT) do (
   SET bHOSTUP=0
   ping -n 2 %%i |find "TTL=" > NUL && SET bHOSTUP=1
   IF !bHOSTUP! equ 1 (
      CALL :HOSTUP %%i
   ) else (
      CALL :HOSTDOWN %%i 
   )
)
GOTO EOF

:HOSTUP
echo Host UP %1
GOTO EOF

:HOSTDOWN
echo Host DOWN %1
GOTO EOF

:EOF
exit /B
0
ping 198.168.57.98 && echo Success || echo failed
3
  • 2
    Please provide more information when you give an answer. See How to Answer Commented Mar 3, 2017 at 14:57
  • 1
    Very neat method, I've seen a lot of batch but have never seen that. However, I'd modify it to be more like 'ping 198.168.57.98 -n 1 > nul 2>&1 && echo Success || echo failed'. Kudos
    – jacktrader
    Commented Jun 28, 2017 at 16:00
  • Does not work in Windows as the ping command seem to return 0 on both success and timeout
    – norq
    Commented Sep 19, 2022 at 12:21
0

I liked the concept of the FIND in the ping results but why not just FIND the Reply from the Address being pinged?

In the example below I enter an IP address as a variable, PING that IP, then look for that variable in the reply string, using the FIND Command. If the Reply String contains anything other than the correct IP it reports failure.

If you want you can just read the value of ERRORLEVEL from the FIND. That will give you a reliable value to work with.

@echo off
Set /P IPAdd=Enter Address:
cls
ping %IPAdd% | find "Reply from %IPAdd%:"
if not errorlevel 1 set error=success
if errorlevel 1 set error=failure
cls
echo Result: %error%
pause
1
  • Note: this is language dependent (my ping says Anwort von ...) Also it only works with IP-Addresses, not with hostnames (as requested by the question).
    – Stephan
    Commented Apr 24, 2019 at 17:47
0

I needed to reset a wifi connection because it has issues. This was my quick solution.

@echo off
Rem Microsoft Windows 10 ping test to gateway.
Rem Run batch file from an administrative command prompt.

cls
:starting
Rem Send one ping to the gateway.  Write the results to a file.
ping 192.168.1.1 -n 1 > pingtest.txt

Rem Search for unreachable in the file. 
c:\windows\system32\findstr.exe "unreachable" pingtest.txt

Rem errorlevel 0 reset the adapter if 1 then wait 10 minutes and test again
if %errorlevel%==1 goto waiting

Rem unreachable was found reset the adapter.

Rem write the date and time the reset was done.
echo Reset date: %date% time: %time% >> resettimes.txt

Rem issue netsh interface show interface to find your adapter's name to reset
Rem my adapter is "wi-fi"

netsh interface set interface "wi-fi" disable
timeout /t  5
netsh interface set interface "wi-fi" enable
:waiting
echo "It is online waiting 10 minutes"
timeout /t  600
goto starting
1
  • 1
    does not (try to) answer the question.
    – Stephan
    Commented Apr 24, 2019 at 17:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.