2012-09-27 117 views
0

我正在使用pcap来监视http请求和响应。我设置了pcap_loop,并且在回调函数中获取数据包,但我不知道如何读取数据包内容。 这是我的回调函数:使用libpcap读取数据包数据

void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet) 
{ 
    printf("%s\n", packet); 
} 

输出看起来总是喜欢系列backslashe和三个数字后

\ 200 \ 205 \ 300

我不知道我该怎么做内容可读,所以我可以找到并处理http请求和响应?

UPDATE:

我的目标是读取HTTP请求和响应是有这样做的任何适当的和简洁的方式?

回答

4

这是因为输出是原始二进制数据,而不是ascii字符串,所以printf只输出它直到第一个0字节。要打印数据包中所有可读的东西,请使用类似于:

for (int i = 0; i < header->caplen; ++i) { 
    if (isascii(packet[i])) { 
     putchar(packet[i]); 
    } else { 
     putchar('.'); 
    } 
+0

谢谢你的回答,但我正在寻找一种方法来分离HTTP内容。 –

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 
+0

我试过了,但没有奏效。 –