burtek
burtek

Reputation: 2675

Checking host reachability on windows command line

How can I check in batch-file if host is reachable or not? The problem is that ping returns 0 not only on success, but also on Destination host unreachable error:

C:\>ping 192.168.1.1 -n 1

Pinging 192.168.1.1 with 32 bytes of data:
Reply from 192.168.1.1: bytes=32 time=3ms TTL=64

Ping statistics for 192.168.1.1:
    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 3ms, Maximum = 3ms, Average = 3ms

C:\>echo %errorlevel%
0

C:\>ping 192.168.1.105 -n 1

Pinging 192.168.1.105 with 32 bytes of data:
Reply from 192.168.1.102: Destination host unreachable.

Ping statistics for 192.168.1.105:
    Packets: Sent = 1, Received = 1, Lost = 0 (0% loss),

C:\>echo %errorlevel%
0

Is there any way to do it with ping or any other build-in-Windows tool? I would prefer not to install anything if that's possible...

Upvotes: 6

Views: 15834

Answers (3)

RGuggisberg
RGuggisberg

Reputation: 4750

Do something like this:

PING 192.168.1.1 -n 1 | FIND /I "Reply from "

Then you can check errorlevel

Edit: To accommodate "Destination host unreachable error you could do this:

PING 192.168.1.1 -n 1 | FIND /I /V "unreachable" | FIND /I "Reply from "

Upvotes: 2

JosefZ
JosefZ

Reputation: 30103

Next code snippet should work:

set "_ip=localhost"
set "_ip=192.168.1.1"
ping %_ip% -n 1 -4 | find /i "TTL=">nul
if errorlevel 1 (
    echo ping %_ip% failure
) else ( 
    echo ping %_ip% success
)
  • -4 to force using IPv4 (as e.g. ping localhost replies IPv6 with no TTL= output)
  • | find /i "TTL=" as find command raises errorlevel well
  • >nul to suppress undesired output

Upvotes: 8

npocmaka
npocmaka

Reputation: 57242

I think tracert is what you need.Sets errorlevel on 1 if cant find the host.And should use the same port as ping.-h 2 is to reduce wait time ,as the complete route is not needed.

tracert -h 2 somehost.com >nul 2>nul && (
  echo reachable host
) || (
  echo unreachable host
)

EDIT: to print correct errorlevel in the brackets you need delayed expansion.Here's more advanced example :

@echo off

setlocal enableDelayedExpansion

echo checking google.com
tracert -h 1 google.com >nul 2>nul && (
  echo reachable host
  echo !errorlevel!
  rem prevent execution of negative condition
  color 22
) || (
  echo unreachable host 
  echo !errorlevel!
)


echo checking asdasdjjakskwkdhasdasd
tracert -h 1 asdasdjjakskwkdhasdasd >nul 2>nul && (
  echo reachable host#
  echo !errorlevel!
   rem prevent execution of negative condition
   color
) || (
  echo unreachable host#
  echo !errorlevel!
)

Upvotes: 2

Related Questions