我正在使用pcap来监控http请求和响应。我已经设置了pcap_loop并且我在回调函数中获取数据包但我不知道如何读取数据包内容。 这是我的回调函数:
void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet)
{
printf("%s\n", packet);
}
输出总是看起来像一系列backslashe和之后的三个数字
\ 200 \ 205 \ 300
我想知道如何才能使内容可读,以便找到并处理http请求和响应?
更新
我的目标是阅读HTTP请求和响应是否有任何正确和巧妙的方法来执行此操作?
答案 0 :(得分:4)
这是因为输出是原始二进制数据,而不是ascii字符串,所以printf只输出它直到前0字节。要打印数据包中所有可读的内容,请使用以下内容:
for (int i = 0; i < header->caplen; ++i) {
if (isascii(packet[i])) {
putchar(packet[i]);
} else {
putchar('.');
}
答案 1 :(得分:2)
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