最直接可靠的方法是使用socket模块尝试连接外部服务(如8.8.8.8:53)或用requests库发送HTTP请求,成功则表示网络通畅,失败则存在连接问题。

在Python中检查网络连接状态,最直接且可靠的方法是尝试与一个已知且稳定的外部服务建立连接,例如Google的DNS服务器(8.8.8.8)或一个公共网站。如果连接成功,通常意味着你的设备具有基本的网络访问能力;如果失败,则表明存在连接问题。
说实话,在Python里检查网络连接,我们通常不是在问“网线插没插”,而是更关心“我能不能访问到外部世界?”。所以,核心思路就是主动出击,尝试去“摸”一下外面的世界。
我个人觉得,最底层、最原生的方式是使用Python的
socket
import socket
def check_internet_connectivity_socket(host="8.8.8.8", port=53, timeout=3):
"""
通过尝试建立socket连接来检查网络连通性。
默认尝试连接Google的DNS服务器。
"""
try:
# 创建一个socket对象,AF_INET表示IPv4,SOCK_STREAM表示TCP
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout) # 设置超时时间,避免长时间等待
s.connect((host, port)) # 尝试连接目标主机和端口
s.close() # 连接成功后关闭socket
print(f"成功连接到 {host}:{port},网络连接正常。")
return True
except socket.error as e:
print(f"无法连接到 {host}:{port}。网络连接可能存在问题或目标不可达。错误: {e}")
return False
except Exception as e:
print(f"发生未知错误: {e}")
return False
# 示例调用
# check_internet_connectivity_socket()
# check_internet_connectivity_socket(host="www.baidu.com", port=80) # 也可以尝试连接网站当然,如果你的应用更关注HTTP/HTTPS层面的连通性,比如你需要确保能访问到某个API或者网页,那么使用
requests
立即学习“Python免费学习笔记(深入)”;
import requests
def check_internet_connectivity_http(url="http://www.google.com", timeout=5):
"""
通过发送HTTP请求来检查网络连通性。
默认尝试访问Google。
"""
try:
# 尝试发送一个GET请求,设置超时时间
response = requests.get(url, timeout=timeout)
# 检查HTTP状态码,200表示成功
if response.status_code == 200:
print(f"成功访问 {url},HTTP连接正常。")
return True
else:
print(f"访问 {url} 失败,HTTP状态码: {response.status_code}。")
return False
except requests.exceptions.ConnectionError:
print(f"无法连接到 {url}。网络连接可能存在问题或目标不可达。")
return False
except requests.exceptions.Timeout:
print(f"访问 {url} 超时。网络连接可能缓慢或不稳定。")
return False
except requests.exceptions.RequestException as e:
print(f"访问 {url} 时发生请求错误: {e}")
return False
except Exception as e:
print(f"发生未知错误: {e}")
return False
# 示例调用
# check_internet_connectivity_http()
# check_internet_connectivity_http(url="https://www.baidu.com")我个人在实际项目中,如果只是想快速判断有没有“网”,通常会优先选择
socket
requests
很多初学者可能会想,既然命令行有
ping
首先,
ping
subprocess
ping
其次,性能和资源消耗也是个问题。每次调用
ping
socket
再者,权限问题。在某些操作系统或网络环境下,执行
ping
所以,尽管
subprocess.run(['ping', '-c', '1', '8.8.8.8'])
socket
requests
这是一个很关键的问题,因为“有网”和“能上网”是两回事。你的电脑可能连接到了一个局域网(比如公司内网或家庭WiFi),但这个局域网本身可能并没有连接到外部互联网。
要区分这两种情况,核心思路就是测试不同的目标。
检查本地网络连接: 你可以尝试连接到你局域网内的某个已知设备,最常见的就是你的路由器。大多数路由器的默认IP地址是
192.168.1.1
192.168.0.1
def check_local_network(router_ip="192.168.1.1", port=80, timeout=1):
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(timeout)
s.connect((router_ip, port))
s.close()
print(f"成功连接到本地路由器 {router_ip}:{port},本地网络正常。")
return True
except socket.error as e:
print(f"无法连接到本地路由器 {router_ip}:{port}。本地网络可能存在问题。错误: {e}")
return False检查外部互联网连接: 这就是我们前面解决方案里提到的,尝试连接到一个公共的、稳定的外部IP地址(如8.8.8.8)或公共网站(如
www.google.com
你可能会遇到这样一种情况:
check_local_network()
check_internet_connectivity_socket()
check_internet_connectivity_http()
所以,在实际应用中,你可能需要组合使用这两种检查方式。先确认本地网络是否正常,再判断是否能访问外部互联网。这能帮助你更准确地诊断网络问题出在哪里。
随着Python异步编程(
asyncio
socket
requests
asyncio
aiohttp
使用
asyncio
import asyncio
import socket
async def async_check_internet_connectivity_socket(host="8.8.8.8", port=53, timeout=3):
"""
通过异步socket连接检查网络连通性。
"""
try:
# asyncio.open_connection会返回reader和writer对象,但我们这里只关心连接是否成功
_reader, _writer = await asyncio.wait_for(
asyncio.open_connection(host, port),
timeout=timeout
)
_writer.close() # 连接成功后关闭
await _writer.wait_closed()
print(f"异步:成功连接到 {host}:{port},网络连接正常。")
return True
except (asyncio.TimeoutError, ConnectionRefusedError, OSError) as e:
print(f"异步:无法连接到 {host}:{port}。错误: {e}")
return False
except Exception as e:
print(f"异步:发生未知错误: {e}")
return False
# 示例运行方式
# async def main():
# await async_check_internet_connectivity_socket()
# await async_check_internet_connectivity_socket(host="www.baidu.com", port=80)
#
# if __name__ == "__main__":
# asyncio.run(main())使用
aiohttp
import aiohttp
import asyncio
async def async_check_internet_connectivity_http(url="http://www.google.com", timeout=5):
"""
通过异步HTTP请求检查网络连通性。
"""
try:
# 使用aiohttp.ClientSession来发送请求
async with aiohttp.ClientSession() as session:
async with session.get(url, timeout=aiohttp.ClientTimeout(total=timeout)) as response:
if response.status == 200:
print(f"异步:成功访问 {url},HTTP连接正常。")
return True
else:
print(f"异步:访问 {url} 失败,HTTP状态码: {response.status}。")
return False
except aiohttp.ClientConnectorError as e:
print(f"异步:无法连接到 {url}。错误: {e}")
return False
except asyncio.TimeoutError:
print(f"异步:访问 {url} 超时。")
return False
except Exception as e:
print(f"异步:发生未知错误: {e}")
return False
# 示例运行方式
# async def main():
# await async_check_internet_connectivity_http()
# await async_check_internet_connectivity_http(url="https://www.baidu.com")
#
# if __name__ == "__main__":
# asyncio.run(main())在异步环境中,这些非阻塞的检查方法能让你在等待网络响应的同时,执行其他的任务,比如更新UI、处理其他事件,这对于需要保持高响应性的应用来说至关重要。我个人觉得,当你踏入异步编程的世界,这些工具就是你的“新常态”,它们让你的应用在面对网络延迟时也能保持优雅。
以上就是python中怎么检查网络连接状态?的详细内容,更多请关注php中文网其它相关文章!
python怎么学习?python怎么入门?python在哪学?python怎么学才快?不用担心,这里为大家提供了python速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号