我正在使用pcap来监控http请求和响应。我已经设置了pcap_loop并且我在回调函数中收到数据包,但我不知道如何读取数据包内容。这是我的回调函数:
void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet)
{
printf("%sn", packet);
}
输出总是看起来像一系列反斜杠和后面的三个数字
200\205\300
我想知道如何使内容可读,以便查找和处理 http 请求和响应?
更新:
我的目标是读取HTTP请求和响应,是否有任何适当而整洁的方法可以做到这一点?
这是因为输出是原始二进制数据,而不是 ascii 字符串,因此 printf 仅输出它直到第一个 0 字节。要打印数据包中的所有可读内容,请使用以下内容:
for (int i = 0; i < header->caplen; ++i) {
if (isascii(packet[i])) {
putchar(packet[i]);
} else {
putchar('.');
}
Libpcap 会给你一个原始数据包,包括所有标头。您需要从中提取所需的数据,我建议将其转换为表示数据包的标准结构。像这样,
/* Start with the ether header */
ethernet = (struct ether_header *) packet;
/* Do a couple of checks to see what packet type we have */
if (ntohs (ethernet->ether_type) == ETHERTYPE_IP)
{
// Cast it to an IP packet struct
ip_hdr = (struct ip*)(packet + sizeof(struct ether_header));
//If TCP...
if(ip_hdr->ip_p == 6)
{
packet_info.tcp_hdr = *(struct tcphdr*)((char*)ip_hdr + sizeof(struct ip));
// Work on extracting the actual data for HTTP stuff over here