1

i need to attempt to make a connection to a domain to determine whether a specific server is online

i have tried to use socket to create a connection but it never makes a connection even though the domain is online

import socket


def ConnectionTest():
    domain = "www.something.com/uptimecheck"

    try:
        socket.create_connection((domain, 443))
        return True
    except OSError:
        pass
    return False

even when i know the domain is online the connection test always returns False, when in theory it should return true.

what am i doing wrong here?

3 Answers 3

1

You're connecting the server on 443, that means you're just checking on a TCP socket with the application layer protocol being HTTPS i.e. the remote end socket tuple is (<server_ip>, 443).

So you can get away with using a typical web client e.g. requests is one (install it with pip install requests, if not done already):

import requests

def is_online(url):
    response = requests.get(url)
    return response.status_code == 200

Now, you can do:

url = "https://www.something.com/uptimecheck"
url_is_online = is_online(url)

Notice that I've prepended the protocol (https) to the URL path.

Sign up to request clarification or add additional context in comments.

Comments

0

The address you're using must resolve into an IP address in order to be able to use it with socket, so you need to use only the domain address and port (without the path /uptimecheck):

import socket


def test_alive(domain: str, port: int):
    try:
        with socket.create_connection((domain, port)) as s:
            return True
    except OSError:
        pass
    return False


if __name__ == '__main__':
    domain = "example.com"
    print(test_alive(domain, port=443))

Comments

0

Only to test if URL exists and server is sending some response, it can be any code even 500 as well

try:
    url = 'https://www.youtube.com'
    p_response = requests.get(url, verify=False)

    print(True)
except:
    print(False)

3 Comments

It's a good idea to use p_response.raise_for_status() to handle 400+ status codes. This code will report True even when server is dead and returns 500 responses, for example.
No it will return true for < 300
try it with res = requests.get('https://httpbin.org/status/500') without checking for status code, what do you get?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.