😏1. ping介绍
PING
是一种常用的网络工具,用于测试计算机之间的连接状况和测量网络时延。它发送一个小的数据包到目标计算机,并等待接收响应。通过测量从发送到接收的时间差,可以得出网络延迟或往返时间(Round-Trip Time, RTT
),即从发送请求到获取响应的时间。
PING测试主要用途如下:
- 连通性测试:PING用于测试计算机与目标主机之间是否可以互相进行通信。它能够快速检查网络连接是否正常,以及是否存在丢包、延迟或其他网络问题。
- 网络性能评估:通过测量PING的往返时间,可以评估网络的性能和响应速度。根据PING的结果,可以确定网络连接的稳定性和吞吐量。
- 故障排除:当发生网络故障时,PING可以帮助识别问题所在。如果PING测试失败,可能表明目标主机不可达或相关网络设备存在故障。
- 监控网络质量:通过定期执行PING测试,并记录RTT值的变化情况,可以监控网络质量的稳定性和变化趋势,帮助网络管理员及时发现和解决潜在的问题。
PING的结果通常包括以下关键信息:
- 目标主机的IP地址或域名。
- 发送数据包的字节数和TTL(Time To Live)值。
- 往返时间(RTT):表示从发送PING请求到接收响应的时间。通常以毫秒为单位。
- 丢包率:表示在PING过程中丢失的数据包的百分比。
PING baidu.com (110.242.68.66) 56(84) bytes of data. 64 bytes from 110.242.68.66 (110.242.68.66): icmp_seq=1 ttl=49 time=24.9 ms
--- baidu.com ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 24.859/24.859/24.859/0.000 ms
😊2. C++示例
#include <iostream>
#include <fstream>
#include <sstream>using namespace std;
int getPingTime(const std::string& ip)
{
std::ostringstream commandStream;
commandStream << "ping -c 1 " << ip << " > ping_tmp.txt";
std::system(commandStream.str().c_str());std::ifstream file("ping_tmp.txt"); if (!file.good()) { std::cerr << "Failed to open ping result file" << std::endl; return 0; } std::string line; while (std::getline(file, line)) { if (line.find("time=") != std::string::npos) { int startIndex = line.find("time=") + 5; int endIndex = line.find(" ms", startIndex); // std::cout << startIndex << " " << endIndex << std::endl; return std::stoi(line.substr(startIndex, endIndex - startIndex)); } } return 0;
}
int main()
{
std::string ipAddress = "baidu.com";int pingTime = getPingTime(ipAddress); std::cout << "Ping time: " << pingTime << " ms" << std::endl; return 0;
}
😊3. Qt示例
Qt示例:
QString MainWindow::getPingTime()
{
QStringList pingCommand;
pingCommand << "-n" << "1" << "www.baidu.com";QProcess process; process.start("ping", pingCommand); process.waitForFinished(); QString output = process.readAllStandardOutput(); QStringList lines = output.split("\r\n"); for (QString line : lines) { if (line.contains("时间")) { int start = line.indexOf("时间=") + 3; int end = line.indexOf("ms", start); if (end != -1) { QString timeStr = line.mid(start, end - start); qDebug() << "Time:" << timeStr << "ms"; } } else if (line.contains("time=")) { int start = line.indexOf("time=") + 5; int end = line.indexOf("ms", start); if (end != -1) { QString timeStr = line.mid(start, end - start); qDebug() << "Time:" << timeStr << "ms"; } } }
}
😆4. python及shell示例
python示例:
import subprocess
from datetime import datetime, timedelta
import timedef ping_host(host):
# 提供subprocess模块执行ping命令
try:
output = subprocess.check_output(["ping", "-c", "1", host])
result = str(output).split("time=")[1].split(" ")[0]
return float(result)
except subprocess.CalledProcessError:
return Nonedef write_to_log(filename, data):
with open(filename, 'a') as f:
f.write(data + '\n')def delete_old_logs(filename):
today = datetime.now()
yesterday = today - timedelta(days=1)
formatted_date = yesterday.strftime("%Y-%m-%d")
# 逐行检查日期是否是前一天的
try:
with open(filename, 'r') as f:
lines = f.readlines()
with open(filename, 'w') as f:
for line in lines:
if not line.startswith(formatted_date):
f.write(line)
except FileNotFoundError:
passfilename = 'ping_logs.txt'
host = 'baidu.com'
interval = 1 # 每隔1秒进行一次ping操作
while True:
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
latency = ping_host(host)
log_entry = f"{current_time} - Ping Latency: {latency} ms"
write_to_log(filename, log_entry)
delete_old_logs(filename)
print(log_entry) # 打印延迟结果到终端
time.sleep(interval)
shell示例:
#!/bin/bash
net_path="./network/"
target_host="baidu.com" # need configif folder exist
if [ ! -d "$net_path" ]; then
mkdir -p "$net_path"
echo "folder not exist: $net_path"
else
echo "folder exist: $net_path"
figet timestamp
get_timestamp() {
date +"%Y-%m-%d %H:%M:%S"
}autoclean
if [ -d "${net_path}" ]; then
echo start delete log 1 days ago...
find "${net_path}"/* -name '*.txt' -mtime +0 -exec rm -rf {} ;
echo end delete log ...
figet ping value
filename_prefix="${net_path}ping"
timestamp=$(get_timestamp)
filename="{filename_prefix}_{timestamp}.txt"while true; do
ping_result=(ping -c 1 target_host | grep time= | awk -F 'time=' '{print $2}' | cut -d ' ' -f 1)echo "$timestamp - Ping: $ping_result ms" # display echo "$timestamp - Ping: $ping_result ms" >> "$filename" # log sleep 1
done