0

I am able to run a simple batch file (thanks to here) which will ping an ip and if it is successful it will go to SUCCESS and if it fails it will go to FAILS.

However, this works for constant success or constant failure, I want it to point at an unsteady connection and only go to FAILS if more than 50% (so, >5) pings fail. Is there any way to do this?

@echo off
ECHO Checking connection, please wait...
PING -n 10 HOST_IP|find "Reply from" > NUL
IF NOT ERRORLEVEL 1 goto :SUCCESS
IF     ERRORLEVEL 1 goto :FAILS

:FAILS
Echo FAIL!
@echo off

:SUCCESS
Echo Success!
@echo off

Thanks

joshnik
  • 438
  • 1
  • 5
  • 15
  • can't do it like this. ping will block and you won't reach the `if not` line until AFTER ping exits. you'd have to run single pings in a loop, and do the statistics there. – Marc B Feb 24 '15 at 18:42
  • I was thinking - could I run the ping command, use FIND /F for the "Packets..." line at the end, extract the token which shows packets lost, put it in a variable and then end the first block with IF variable > 5 goto... – joshnik Feb 24 '15 at 18:46
  • sure. but you'd have to wait for all 10 packets to be done first. you couldn't do a realtime "have we hit 5 lost packets yet" check. – Marc B Feb 24 '15 at 18:51
  • You really shouldn't use Reply from because you can get Reply from messages even when the ping fails. Use "TTL=" instead. – Matt Williamson Feb 24 '15 at 18:51
  • the better-ish method would be (pseudo-code) `while (loss <= 50%) { ping -n 1 -> loss++ }` type thing. do a single packet ping. check if it was lost or successful, and update your counters. as soon as you reach 50% loss, you can abort the loop. – Marc B Feb 24 '15 at 18:52

1 Answers1

0

For ipv4 you can use

for /f %%a in ('
    ping -n 10 www.google.es ^| find /c "TTL="
') do if %%a lss 5 ( echo Fail ) else ( echo Sucess )

that will count the number of output lines with the TTL= string, that will be present in packets that reach the host.

But ipv6 does not include the TTL in its output, so, we can directly retrieve the percentage loss

for /f "tokens=2 delims=()" %%a in ('ping -n 10 www.google.com'
) do for /f "tokens=1 delims=%%" %%b in ("%%a"
) do if %%b gtr 50 ( echo Fail ) else ( echo Sucess )

Why not to use the second method for both versions? Because in ipv4 pinging an inactive machine in the same vlan will not loss any packet. For each packet sent you will receive a packet from the same machine that sends it.

You can find more information here on ping behaviour and usage in batch files.

Community
  • 1
  • 1
MC ND
  • 69,615
  • 8
  • 84
  • 126