network_status.py
· 533 B · Python
Eredeti
import socket
def is_connected(host='8.8.8.8', port=53, timeout=3):
"""
嘗試連線到指定的 host 與 port,預設為 Google 的 DNS 伺服器。
"""
try:
socket.setdefaulttimeout(timeout)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.close()
return True
except socket.error:
return False
if __name__ == '__main__':
if is_connected():
print("網路連線正常")
else:
print("網路連線有問題")
| 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("網路連線有問題") |
| 21 |