'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 1:[1]

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.

Solution 2:[2]

You can use ping lib to make the ping.

import ping, socket
try:
    ping.verbose_ping('www.google.com', count=3)
    delay = ping.Ping('www.wikipedia.org', timeout=2000).do()
except socket.error, e:
    print "Ping Error:", e

Solution 3:[3]

You could use icmplib. The following code tries to ping host an returns True if the DNS lookup was successful and the host responds all pings.

from icmplib import ping

from icmplib import ping
from icmplib.exceptions import NameLookupError


def host_up(hostname:str):
    try:
        host = ping(hostname, count=5, interval=0.2)
    except NameLookupError:
        return False
    return host.packets_sent == host.packets_received

host = "facebook.com"
if host_up(host):
    print(f"{host} is valid")
else:
    print(f"{host} is not valid")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 isaiahstanke
Solution 2
Solution 3