[Python] socket.connect freezing when there is no internet

Discussão em 'Python' iniciado por Stack, Março 18, 2025.

  1. Stack

    Stack Membro Participativo

    I want to check if google is reachable or not and I'm using his code:

    import socket

    def google_is_reachable():
    try:
    sck = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sck.settimeout(2)
    print("------------------------ 1 --------------------------------")
    sck.connect(("google.com", 80))
    print("------------------------ 2 --------------------------------")
    sck.shutdown(socket.SHUT_RDWR)
    sck.close()
    return True
    except Exception as e:
    return False

    res = google_is_reachable()
    print(res)


    I'm using VPN. And when there is no internet, the code freezes at line:

    sck.connect(("google.com", 80))


    First question: Is this the best way to check if google is reachable (or any other site)?

    Second question: How to solve the issue? I don't want it to get stuck, i want the line to either throw the error or return any value meaning google is not reachable.

    Continue reading...

Compartilhe esta Página