本文目录导读:
我来教你用Python编写一个网络延迟检测工具,这里有几种实现方案,从简单到复杂:
使用 ping3 库(推荐)
import ping3
import time
import sys
def ping_host(host, count=4):
"""检测单个主机的延迟"""
print(f"正在检测 {host} 的延迟...")
print("-" * 50)
success_count = 0
total_time = 0
for i in range(count):
try:
# ping3.ping() 返回延迟时间(秒),失败返回 None
delay = ping3.ping(host, timeout=2)
if delay is not None:
delay_ms = round(delay * 1000, 2) # 转换为毫秒
print(f"第 {i+1} 次: {delay_ms} ms")
success_count += 1
total_time += delay_ms
else:
print(f"第 {i+1} 次: 超时")
except Exception as e:
print(f"第 {i+1} 次: 错误 - {e}")
if i < count - 1:
time.sleep(1) # 每次ping间隔1秒
# 显示统计信息
print("-" * 50)
if success_count > 0:
avg_time = round(total_time / success_count, 2)
print(f"成功: {success_count}/{count}")
print(f"平均延迟: {avg_time} ms")
print(f"丢包率: {round((1 - success_count/count) * 100, 1)}%")
else:
print(f"全部超时,无法连接到 {host}")
def main():
"""主函数"""
print("网络延迟检测工具 v1.0")
print("=" * 50)
# 预设一些常见网站
hosts = {
"1": "baidu.com",
"2": "google.com",
"3": "github.com",
"4": "bing.com"
}
print("请选择要检测的目标:")
for key, host in hosts.items():
print(f"{key}. {host}")
print("0. 自定义目标")
choice = input("\n请输入选项 (0-4): ").strip()
if choice == "0":
host = input("请输入要检测的域名或IP: ").strip()
elif choice in hosts:
host = hosts[choice]
else:
print("无效选项,使用默认目标 baidu.com")
host = "baidu.com"
try:
count = int(input("请输入测试次数 (默认4次): ") or "4")
if count < 1:
count = 4
except ValueError:
count = 4
print("\n" + "=" * 50)
ping_host(host, count)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\n\n程序已终止")
sys.exit(0)
使用系统 ping 命令(跨平台)
import subprocess
import platform
import re
import time
def ping_with_system(host, count=4):
"""使用系统ping命令检测延迟"""
print(f"正在检测 {host} 的延迟...")
print("-" * 50)
# 根据操作系统设置ping参数
system = platform.system().lower()
if system == "windows":
cmd = ["ping", "-n", str(count), host]
else: # Linux和MacOS
cmd = ["ping", "-c", str(count), host]
try:
# 执行ping命令
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
print(result.stdout)
# 解析结果
if "time=" in result.stdout or "时间=" in result.stdout or "TTL=" in result.stdout:
print("检测完成:连接正常")
else:
print("检测完成:连接异常或超时")
except subprocess.TimeoutExpired:
print("错误:ping命令超时")
except Exception as e:
print(f"错误:{e}")
def main():
"""主函数"""
print("网络延迟检测工具 (系统ping)")
print("=" * 50)
host = input("请输入要检测的域名或IP (默认: baidu.com): ").strip()
if not host:
host = "baidu.com"
try:
count = input("请输入测试次数 (默认4次): ").strip()
count = int(count) if count else 4
if count < 1:
count = 4
except ValueError:
count = 4
ping_with_system(host, count)
if __name__ == "__main__":
main()
实时监测工具(高级版)
import ping3
import time
import sys
import threading
from datetime import datetime
class NetworkMonitor:
"""网络延迟监测器"""
def __init__(self, host="baidu.com", interval=1):
self.host = host
self.interval = interval
self.running = False
self.delays = []
def ping_once(self):
"""单次ping检测"""
try:
delay = ping3.ping(self.host, timeout=2)
if delay is not None:
return round(delay * 1000, 2)
return None
except Exception:
return None
def monitor(self):
"""开始监测"""
self.running = True
print(f"开始监测 {self.host}...")
print("按 Ctrl+C 停止监测\n")
print(f"{'时间':<20} {'延迟(ms)':<15} {'状态'}")
print("-" * 50)
try:
while self.running:
delay = self.ping_once()
timestamp = datetime.now().strftime("%H:%M:%S")
if delay is not None:
status = "✓" if delay < 200 else "!"
print(f"{timestamp:<20} {delay:<15} {status}")
self.delays.append(delay)
else:
print(f"{timestamp:<20} {'超时':<15} ✗")
self.delays.append(None)
time.sleep(self.interval)
except KeyboardInterrupt:
self.stop()
def stop(self):
"""停止监测并显示统计"""
self.running = False
print("\n\n" + "=" * 50)
print("监测统计")
print("=" * 50)
if self.delays:
valid_delays = [d for d in self.delays if d is not None]
timeout_count = self.delays.count(None)
total_count = len(self.delays)
if valid_delays:
print(f"总次数: {total_count}")
print(f"成功: {len(valid_delays)}")
print(f"超时: {timeout_count}")
print(f"丢包率: {round(timeout_count/total_count*100, 1)}%")
print(f"最小延迟: {min(valid_delays)} ms")
print(f"最大延迟: {max(valid_delays)} ms")
print(f"平均延迟: {round(sum(valid_delays)/len(valid_delays), 2)} ms")
else:
print("全部超时")
def main():
print("实时网络延迟监测工具")
print("=" * 50)
# 预设目标
print("常用目标:")
targets = {
"1": {"name": "百度", "host": "baidu.com"},
"2": {"name": "谷歌", "host": "google.com"},
"3": {"name": "GitHub", "host": "github.com"},
"4": {"name": "本地测试", "host": "127.0.0.1"}
}
for key, target in targets.items():
print(f"{key}. {target['name']} ({target['host']})")
choice = input("\n请选择 (1-4) 或输入自定义地址: ").strip()
if choice in targets:
host = targets[choice]["host"]
print(f"选择: {targets[choice]['name']}")
else:
host = choice
if not host:
host = "baidu.com"
try:
interval = float(input("请输入检测间隔(秒) (默认1秒): ") or "1")
if interval < 0.5:
interval = 0.5
except ValueError:
interval = 1
monitor = NetworkMonitor(host, interval)
monitor.monitor()
if __name__ == "__main__":
main()
安装依赖
对于方法一和方法三,需要安装 ping3 库:
pip install ping3
使用建议
- 方法一:适合大多数场景,代码简洁,功能完整
- 方法二:不需要额外安装库,但输出格式因系统而异
- 方法三:适合需要实时监控的场景
运行示例
保存代码为 ping_test.py,然后运行:
python ping_test.py
这些工具可以帮您:
- 检测网络连接是否正常
- 测试到特定服务器的延迟
- 监控网络稳定性
- 检查丢包率
选择最适合您需求的版本即可!