pythonoperating-systempingicmp

How to ping a web server in Python 3.10


Alrighty, time to ask a very stupid/obvious question. I need to ping a webserver/website to see if it's valid, using the ICMP protocol. You know...ping facebook.com. My code generates a bunch of TLD's, and subdomain's to a user-inputted domain name. I plan on pinging all of them (it's about 6 usually) to see if they're actually valid before doing what I need to do with them. However, all the tutorials and questions similar to mine are from like 2010 and don't work anymore. The one thing I have got to work printed out the results of the ping, which I don't want. So maybe some sort of function that like below, it just returns or prints out whether or not it's online not actual responses if that makes sense:

def website_checker():
     
     if os.system("ping facebook.com"):
           
          print("facebook.com is valid")
     
     else:
    
          print("facebook.com is not valid")

I'm not sure if that helps but I can't put it into any better words. Please, I'm pulling my hair out


Solution

  • I figured it out thanks to the help of @Moanos! Here is the code:

    from icmplib import ping
    
    def host_up(hostname:str):
        host = ping(hostname, count=5, interval=0.2)
        return host.packets_sent == host.packets_received
    
    hosts = "facebook.gov"
    
    try:
        if host_up(hosts):
            print(f"{hosts} is valid")
    except:
        print(f"{hosts} is not valid")
    

    So to the function is @Moanos's code, but the rest is mine. The reason I am using a try, except block is to prevent the NameLookupError from printing out! So when it's valid, it says only that it's valid and same case for when it is not a valid domain.