最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

python - socket.connect() freezing when there is no internet - Stack Overflow

programmeradmin4浏览0评论

I want to check if Google is reachable or not. I'm using this 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", 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 a VPN, and when there is no internet then the code freezes on this line:

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

Is this the best way to check if Google is reachable (or any other site)?

How to solve the freezing issue? I don't want it to get stuck. I want the line to either throw an error or return any value meaning Google is not reachable.

发布评论

评论列表(0)

  1. 暂无评论