import subprocess import platform import time def ping_once(host): """ 使用系統的 ping 指令對指定 host 發送一次封包, 回傳 True 代表 ping 成功,False 代表失敗。 """ # 根據作業系統決定參數:Windows 用 -n,其他平台用 -c param = '-n' if platform.system().lower() == 'windows' else '-c' command = ['ping', param, '1', host] try: # 不顯示輸出 result = subprocess.run(command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) return result.returncode == 0 except Exception as e: print(f"呼叫 ping 指令發生例外:{e}") return False def is_network_connected(host='8.8.8.8', attempts=5, success_threshold=3, delay=1): """ 透過連續 ping 嘗試判斷網路連線狀態: - attempts: ping 嘗試次數 - success_threshold: 成功次數達此值才視為連線正常 - delay: 每次 ping 之間的等待秒數 """ success_count = 0 for i in range(attempts): if ping_once(host): success_count += 1 print(f"[{i+1}/{attempts}] Ping 成功") else: print(f"[{i+1}/{attempts}] Ping 失敗") # 避免連續發送太快 time.sleep(delay) return success_count >= success_threshold if __name__ == '__main__': if is_network_connected(): print("網路連線正常") else: print("網路連線有問題")