As a continuation of my comment above, that errorlevel
cannot be trusted as a true indicator whether the ping worked because of how it is set when the ping returns Destination host unreachable.
Here's an example of what I mean:
c:\>ping -n 1 192.168.0.238&echo ERRORLEVEL = !errorlevel!
Pinging 192.168.0.238 with 32 bytes of data:
Request timed out.
Ping statistics for 192.168.0.238:
Packets: Sent = 1, Received = 0, Lost = 1 (100% loss),
ERRORLEVEL = 1
c:\>ping -n 1 192.168.0.238&echo ERRORLEVEL = !errorlevel!
Pinging 192.168.0.238 with 32 bytes of data:
Reply from x.x.x.x: Destination host unreachable.
Ping statistics for 192.168.0.238:
Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
ERRORLEVEL = 0
c:\>ping -n 1 192.168.0.238&echo ERRORLEVEL = !errorlevel!
Pinging 192.168.0.238 with 32 bytes of data:
Request timed out.
Ping statistics for 192.168.0.238:
Packets: Sent = 1, Received = 0, Lost = 1 (100% loss),
ERRORLEVEL = 1
This code seems to work a lot better:
@echo off
setlocal enableextensions enabledelayedexpansion
REM checking the state of the current ip addres
set ipaddr=%1
set oldstate=neither
:loop
set state=down
for /f "skip=2 tokens=6 delims= " %%i in ('ping -n 1 !ipaddr!') do if "%%i"=="TTL=128" set state=up
if not !state!==!oldstate! (
echo.Link is !state!
set oldstate=!state!
)
ping -n 2 127.0.0.1 >nul: 2>nul:
goto :loop
endlocal
When I run checklink 192.168.0.238
, I get link is down
and it never toggles to up
. When I run checklink 127.0.0.1
, I get link is up
.