# Batch file problems. check ip for up/down state



## ibbignerd (Jul 14, 2011)

I have a batch file that is supposed to check the "lost" value to see if the ping was successful or not. Text will be displayed depending on the outcome.


```
@setlocal enableextensions enabledelayedexpansion
@echo off
:loop
set ipaddr=%1
set state=down
for /f "tokens=5,7" %%a in ('ping -n 3 !ipaddr!') do (
    if "x%%a"=="xlost" if "x%%b"=="x0," set state=up
)
echo.Link is !state!
ping Google.com -n 3 >nul: 2>nul:
cls
goto :loop
endlocal
```
I'm sure that I'm just missing like 1 thing. Please help.

Thanks, ibbignerd


----------



## Squashman (Apr 4, 2003)

Does this need to be done in a batch file. I have always preferred to this with a program like Hosts Alive.
http://www.hostalive.net/hostalive.html

The way you have your batch file setup it will constantly ping the ip address given from the cmd line and it will also ping Google. It will keep doing that until you kill the batch file. This is extremely frowned upon in the real world.


----------



## Squashman (Apr 4, 2003)

I believe this is what you are trying to extract though. I am just echoing the variables for simplicity.

```
for /f "tokens=6,7 delims=:=, " %%a in ('ping -n 3 yahoo.com ^| find "Packets"') do echo %%a %%b
```
Output

```
Lost 0
```


----------



## ibbignerd (Jul 14, 2011)

Thank you.


----------



## Squashman (Apr 4, 2003)

In Theory if you only want to check state being up by the packets lost equaling zero you wouldn't even need a for loop. 
You could just do this.

```
ping -n 3 yahoo.com | find "Lost = 0" && set state=up
```


----------



## Squashman (Apr 4, 2003)

In your original batch file you really don't need delayed expansion at all so you really don't need to use the exclamations. You could also use the %1 variable inside the for loop as well but not a big deal if you want to assign it to another variable.


```
@echo off
set ipaddr=%1
set state=down
for /f "tokens=6,7 delims=:=, " %%a in ('ping -n 3 %ipaddr% ^| find "Packets"') do if "%%a"=="Lost" if "%%b"=="0" set state=up
```


----------

