Answer the question
In order to leave comments, you need to log in
How to check if a host is alive using Python?
Hello. Wrote a program to check open ports. And ran into a problem.
I need to check if a host exists on the network.
It doesn't have to be a website.
So that the host address can be entered as both a website address and an ip address.
subprocess or os in conjunction with ping is not suitable, since the output from ping goes to the console of the program that checks the ports. You need to somehow remove the output of ping or use another method.
Answer the question
In order to leave comments, you need to log in
subprocess or os in conjunction with ping is not suitable, since the output from ping goes to the program console
>>> import requests
>>> r = requests.get('http://httpbin.org/get')
>>> r.status_code
200
With the socket module , you can check the host and port on it. Here is an example, add a timeout to taste and handle it in case the host is not available:
import socket
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = 'toster.ru'
port = 80
conn.connect((host, port))
print(conn)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question