最終更新 10 months ago

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

timmy revised this gist 10 months ago. Go to revision

No changes

timmy revised this gist 10 months ago. Go to revision

No changes

timmy revised this gist 10 months ago. Go to revision

No changes

timmy revised this gist 10 months ago. Go to revision

1 file changed, 20 insertions

network_status.py(file created)

@@ -0,0 +1,20 @@
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))
11 + s.close()
12 + return True
13 + except socket.error:
14 + return False
15 +
16 + if __name__ == '__main__':
17 + if is_connected():
18 + print("網路連線正常")
19 + else:
20 + print("網路連線有問題")
Newer Older