O'Reilly logo

Python Network Programming Cookbook - Second Edition by Dr. M. O. Faruque Sarker, Pradeeban Kathiravelu

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

How to do it...

You can lazily write a Python script that calls the system ping command-line tool, as follows:

import subprocess 
import shlex 
 
command_line = "ping -c 1 www.google.com" 
args = shlex.split(command_line) 
try: 
      subprocess.check_call(args,stdout=subprocess.PIPE,\ 
stderr=subprocess.PIPE) 
    print ("Google web server is up!") 
except subprocess.CalledProcessError: 
    print ("Failed to get ping.") 

However, in many circumstances, the system's ping executable may not be available or may be inaccessible. In this case, we need a pure Python script to do that ping. Note that this script needs to be run as a superuser or administrator.

Listing 3.2 shows the ICMP ping, as follows:

 #!/usr/bin/env python # Python Network Programming Cookbook -- ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required