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