Opengist

Explore

  • All gists
  • Topics
  • Users
Give feedback on the new UI Powered by Opengist ⋅ 27ms

user:thomas gists created by user

title:mygist gists with given title

description:sync gists with given description

filename:myfile.txt gists having files with given name

extension:yml gists having files with given extension

language:go gists having files with given language

topic:homelab gists with given topic

all:systemctl search all fields

Login
g

google-dns

Recently created Least recently created Recently updated Least recently updated

timmy / 網路連線檢查工具

Last active 5 hours ago connectivity google-dns internet-check network-monitoring networking python socket system-automation

這段程式碼透過嘗試建立與 Google DNS 伺服器(8.8.8.8 的 53 埠)的 TCP 連線,來檢查網路是否正常連接,成功連線表示網路通暢,否則則視為網路有問題。

0 0 0 1
1 import socket
2
3 def is_connected(host='8.8.8.8', port=53, timeout=3):
4 """
5 嘗試連線到指定的 host 與 port,預設為 Google 的 DNS 伺服器。
6 """
7 try:
8 socket.setdefaulttimeout(timeout)
9 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
10 s.connect((host, port))