So at work we have some Computers that we have to load softwares onto and usually when I connect my laptop to the computer by an ethernet cable i have to set my IPv4 adress to 10.10.1.99
because the computer usually has 10.10.1.101
as IP adress then I load the software onto that computer.
Now sometimes the computer has a wrong IP preset for example 10.41.246.70
or 10.42.246.71
.
Since we dont have an easy and fast way to check for what ip the computer has i have written a little scrip that changes the IPv4 of my laptop to the most common IP's the Computers usually have and let it ping those IP's: The code looks like this and it goes through around 8 IP's that it checks:
cls
echo Searching.
netsh interface ip set address "Ethernet" static 10.10.1.99 255.255.255.0 >nul: 2>nul:
ping -w 4 -n 3 10.10.1.101
if !errorlevel!==0 (
set activeip=10.10.1.101
goto :ipfound
)
Now this code usually works just fine, in 99% of the cases its one of the 8 IP's that we know. The problem is that sometimes instead of "Request timed out" I get "Destination Host unreachable" which for some reason seems to not be an error and when I do get Destination Host unreachable the script thinks it has found the right IP. Now is there a way to go around this for example by adding some kind of:
if output == Destination Host Unreachable (goto next IP)
or is there a way to tell the script that destination host unreachable is also an error.
Thanks to everyone who can help in any way.
Because Reply from xx.xx.xx.xx: Destination Host Unreachable
is technically still a reply.. :)
You can use findstr
to manipulate your errorlevel
ping -w 4 -n 3 10.10.1.101 | findstr /i "TTL"
if "%errorlevel%"=="0" echo Success
if "%errorlevel%"=="0" echo Failed
Keep in mind that the errorlevel
here is set based on the result of findstr
(whether your findstr
string matched what you asked it to find).
To demonstrate, this will return errorlevel
of 0
because the search string was met:
ping -w 4 -n 3 10.10.1.101 | findstr /i "Destination Host Unreachable"
echo %errorlevel%
So finally, to ammend your script to always check for actual reply from
and not destination host unreachable
, and move to the next IP until we find the active IP, simply do:
set "ips=10.10.1.101 10.10.1.102 10.10.1.103 10.10.1.104"
for %%i in (%ips%) do (
ping -w 4 -n 3 %%i | findstr /i "TTL"
if "!errorlevel!"=="0" (
set "activeip=%%i"
goto :ipfound
)
)
You have to just change the list of IP's you want where I set
my IP's.
Also, I am assuming that you have EnableDelayedExpansion
set somewhere already, seeing that you are using it.