【问题标题】:Reading Packet Data With libpcap使用 libpcap 读取数据包数据
【发布时间】:2012-09-27 19:55:16
【问题描述】:

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

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

输出总是看起来像一系列反斜杠和后面的三个数字

\200\205\300

我想知道如何使内容可读,以便查找和处理 http 请求和响应?

更新:

我的目标是读取 HTTP 请求和响应,是否有任何适当且简洁的方法可以做到这一点?

【问题讨论】:

    标签: c++ c pcap libpcap packets


    【解决方案1】:

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

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

    【讨论】:

    • 感谢您的回答,但我正在寻找一种方法来分离 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-11-20
      • 2014-03-12
      • 2011-02-05
      • 1970-01-01
      • 2013-05-23
      • 1970-01-01
      相关资源
      最近更新 更多