在Windows下,利用QT编程中点击按钮void MainWindow::on_Delay_test_pushButton_clicked(),对局域网内目标IP设备进行ping测试,并将ping测试的时间延迟显示在 ui->wire_log_2,修改后的完整代码
时间: 2024-10-25 08:18:14 浏览: 52
图片缩放-design_expert8.0响应面中文教程
在Windows环境下,使用Qt进行编程并实现在点击按钮后对局域网内的目标IP设备进行ping测试,并在`ui->wire_log_2`文本框中展示ping时间的延迟,你需要在`MainWindow`类中添加相应的槽函数和网络操作。以下是一个简单的示例代码:
```cpp
#include <QTimer>
#include <QPushButton>
#include <QObject>
#include <QLabel>
#include <QTextEdit>
#include <qglobal.h>
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = nullptr)
: QMainWindow(parent)
{
// 创建一个按钮
QPushButton* delay_test_pushButton = new QPushButton("Ping Test", this);
connect(delay_test_pushButton, &QPushButton::clicked, this, &MainWindow::on_Delay_test_pushButton_clicked);
// 创建一个文本编辑框用于显示ping结果
QLabel* wire_log_label = new QLabel("Ping Time (ms):", this);
ui->wire_log_2 = new QTextEdit(this); // 假设ui->wire_log_2已经存在并且连接到了UI设计中的控件
QVBoxLayout* layout = new QVBoxLayout();
layout->addWidget(wire_log_label);
layout->addWidget(ui->wire_log_2);
setLayout(layout);
}
private slots:
void on_Delay_test_pushButton_clicked()
{
QString targetIp = "192.168.1.1"; // 替换为你需要ping的目标IP地址
qint64 pingTimeMS = ping(targetIp);
if (pingTimeMS > 0) {
ui->wire_log_2->append(QString("Ping to %1 took %2 ms").arg(targetIp).arg(pingTimeMS));
} else {
ui->wire_log_2->append("Failed to ping the device.");
}
}
private:
qint64 ping(const QString& ipAddress)
{
struct sockaddr_in addr;
memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(ipAddress.toUtf8().constData());
addr.sin_port = htons(80); // 假定对方监听的是HTTP端口,如果实际不是,请替换
// 使用Winsock API进行ping
HANDLE hSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (hSocket == INVALID_SOCKET)
{
qWarning() << "Error creating socket";
return -1;
}
unsigned int timeout = 500; // 设置超时时间为500毫秒
DWORD sendBytes = 0, bytesReceived = 0;
OVERLAPPED overlapped;
ZeroMemory(&overlapped, sizeof(overlapped));
int result = WSAIoctl(hSocket,
SIOCTL_SENDTO, // 请求发送数据到指定地址
(LPVOID)&addr, // 地址指针
sizeof(addr),
NULL, // 不发送数据
0, // 发送的数据长度为0
&sendBytes, // 发送字节数
&overlapped, // 超时信息
&timeout);
if (result != 0 || WSAGetLastError() != WSAEWOULDBLOCK)
{
closesocket(hSocket);
qWarning() << "Error sending packet: " << result << ", error code: " << WSAGetLastError();
return -1;
}
result = recvfrom(hSocket, NULL, 0, 0, (SOCKADDR*)&addr, &bytesReceived);
if (result == SOCKET_ERROR)
{
closesocket(hSocket);
qWarning() << "Error receiving response: " << WSAGetLastError();
return -1;
}
closesocket(hSocket);
if (WSAGetLastError() != WSAEWOULDBLOCK)
{
return -1;
}
// 计算往返时间
qint64 elapsedTime = qint64(timeout * 1000);
qint64 latency = elapsedTime / 2;
return latency;
}
};
int main(int argc, char *argv[])
{
QApplication app(argc, argv);
MainWindow mainWindow;
mainWindow.show();
return app.exec();
}
```
请注意,上述代码使用了Winsock API来进行网络通信,Windows平台特有的API。在跨平台应用中,可能需要使用更通用的库,如Boost.Asio。
阅读全文