qt/ledset/pcapthread.cpp
2022-08-25 18:43:03 +08:00

46 lines
1.6 KiB
C++

#include "pcapthread.h"
#include <QDateTime>
#include <QDebug>
CapThread::CapThread(struct pcap *pcap, QObject *parent) : QThread(parent), pcap(pcap) {
connect(this, &QThread::finished, this, &QThread::deleteLater);
}
void CapThread::run() {
pcap_pkthdr *header;
const u_char *data;
int res;
while((res = pcap_next_ex(pcap, &header, &data)) >= 0) {
if(res == 0) continue; //超时
packet.time = QDateTime::fromSecsSinceEpoch(header->ts.tv_sec).toString("yy-MM-dd HH:mm:ss.")+QString::number(header->ts.tv_usec);
packet.len = header->len;
packet.caplen = header->caplen;
//输出编号、时间戳和包长度
qDebug()<<packet.time<<" len:"<<header->caplen<<"/"<<header->len;
QString data_str;
char line[LINE_LEN + 1];
int l = 0;
for(uint i=0; i<header->caplen; i++) {
data_str.append(QString::asprintf("%.2x ", data[i]));
if(i > 13) {
if(isgraph(data[i]) || data[i] == ' ') line[l] = data[i];
else line[l] = '.';
if(l==15) {
line[16] = '\0';
data_str.append(" ");
data_str.append(line);
data_str.append("\n");
memset(line, 0, LINE_LEN);
l = 0;
} else l++;
} else if(i == 13) {
data_str.append("\n");
}
}
packet.data = data_str;
qDebug()<<packet.data.toUtf8().constData();
emit onMsg();
}
qDebug("Error reading the packets: %s\n", pcap_geterr(pcap));
}