[Tutor] checking return status of 'ping' in windows

Alan Gauld alan.gauld at btinternet.com
Sun Jan 22 00:20:13 CET 2012


On 21/01/12 18:47, Nikunj Badjatya wrote:

> Normal ping operation on windows cmd prompt can give 3 outputs.
> 1) "destination host unreachable
> 2) "request timed out"
> 3) "Reply from 192.168.1.1 <http://192.168.1.1>: bytes=32 time=3ms TTL=64"
>
> Now,
> I was expecting the "status" in above snippet to hold '0' only in case
> of no. 3)
> But even when we have case 1), 'status' is holding '0'.
> i.e. The exit status of ping is 0, even when destination host is
> unreachable.!

The exit status tells you whether the program worked ok,
which could be interpreted, as it apparemtly is in the
case of Windows ping not to include whether it found
a host. If the ping program executed with no errors
you will get no errors. Its kind of arbitrary how you
define an 'error'...

So it seems like you will need to examine the actual output
of ping by looking at the content of stdout/err.

The good news is that this is fairly easy in the case of your ping 
because you can tell from the first word.

def pingStatus(resultString):
     key = resultString.split()[0]
     if key.lower().startswith('rep'): return 0
     elif key.lower().startswith('req'): return 1
     elif key.lower().startswith('des'): return 2
     else: return -1

should give you something like what you were looking for.
Reading Popen stdout I leave as an exercise for the reader :-)

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list