【发布时间】:2020-08-04 15:56:53
【问题描述】:
我在c 中使用libpcap 来编写数据包嗅探器。如何打印数据包中的全部数据?
我试过这种方式:
#include <pcap.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
void packet_process(u_char *args,const struct pcap_pkthdr *header,const u_char *packet){
struct ether_header *eh;
const u_char *ip_header;
ip_header = packet + 14;
u_char proto = *(ip_header+9);
eh=(struct ether_header *) packet;
const u_char *ptr = packet;
int bytes = 0;
char packet_content[1000];
static int i=0;
fprintf(stdout, "%d) len: %d\n", ++i, header->len);
while(bytes ++ < 1000){
packet_content[bytes-1] = *ptr;
ptr ++;
}
fprintf(stdout, "%s\n\n", packet_content);
fflush(stdout);
}
int main(int argc, char *argv[]){
char error[PCAP_ERRBUF_SIZE];
pcap_t *handle = pcap_open_live(argv[1], BUFSIZ, 0, -2, error);
pcap_loop(handle, atoi(argv[2]),packet_process, NULL );
pcap_close(handle);
return 0;
}
但是这段代码没有显示数据包中的全部数据,这段代码的输出是这样的:
[amirreza@localhost tmp]$ sudo ./a.out enp3s0 5
1) len: 118
0���:T����
2) len: 145
T����0���:
3) len: 118
0���:T����
4) len: 145
T����0���:
5) len: 117
0���:T����
我不知道如何使它们具有人类可读性并在数据包中打印整个数据。
【问题讨论】:
-
类似
for (int j = 0; j < header->len; j++) printf("%02X ", ptr[j]);?你想要什么打印格式? -
@MikeCAT 我想用 ASCII 打印数据包。
-
为此,您必须确切知道数据包中的哪些字节实际上是 ASCII 数据。
-
@LeeDanielCrocker 我怎样才能找到这个?我查看数据包数据的目的是区分 dns 数据包的类型。但我不知道如何找到 dns 数据包。
-
DNS 数据包位于端口 53。
标签: c networking libpcap