PING
是一种常用的网络工具,用于测试计算机之间的连接状况和测量网络时延。它发送一个小的数据包到目标计算机,并等待接收响应。通过测量从发送到接收的时间差,可以得出网络延迟或往返时间(Round-Trip Time, 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
#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;
}
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";
}
}
}
}
python示例:
import subprocess
from datetime import datetime, timedelta
import time
def 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 None
def 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:
pass
filename = '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 config
# if folder exist
if [ ! -d "$net_path" ]; then
mkdir -p "$net_path"
echo "folder not exist: $net_path"
else
echo "folder exist: $net_path"
fi
# get 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 ...
fi
# get 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