PCAP_NEXT_EX()从不设置指向原始数据包的指针

pcap_next_ex() never sets the pointer to the raw packet?

本文关键字:原始 原始数据 指针 数据包 EX NEXT PCAP 设置      更新时间:2023-10-16

我试图用libpcap在原始数据包中阅读(Centos 6上的1.4.0)。

但是,由于某些原因,rawpacket始终是null,pcap_next_ex()。

但是,pcap_next_ex()确实返回1,尽管这可能意味着超时到期(在哪里设置了超时?)。

首先,我认为我传递到PCAP_COMPILE()的过滤器字符串是错误的。但是我尝试将相同的字符串复制到tcpdump,效果很好 - 我看到预期的数据包被捕获。


    struct pcap_pkthdr *pHeader;
    const u_char* rawPacket = NULL;
    int rc = 0;
    while (1) {
        rc = pcap_next_ex(pDevice, &pHeader, &rawPacket);
        if (-1 != rc && NULL != rawPacket) {
            // process
            struct ether_header* eptr = (struct ether_header *) rawPacket;
            if (ntohs (eptr->ether_type) == ETHERTYPE_IP) {
                    printf("Ethernet type hex:%x dec:%d is an IP packetn",
                            ntohs(eptr->ether_type),
                            ntohs(eptr->ether_type));
            }
        }
    }

有什么想法吗?

预先感谢。

实际上, pcap_next_ex() man页面所说的是

   pcap_next_ex() returns 1 if the packet was read without problems, 0  if
   packets are being read from a live capture, and the timeout expired, -1
   if an error occurred while reading the packet, and -2  if  packets  are
   being  read  from a ``savefile'', and there are no more packets to read
   from the savefile.  If -1 is returned, pcap_geterr()  or  pcap_perror()
   may be called with p as an argument to fetch or display the error text.

我需要对其进行编辑以删除"实时捕获"answers"超时到期"之间的注释,因为这意味着pcap_next_ex()返回:

  • 1,如果读取或捕获数据包,则应将指针设置为原始数据包;
  • 0,如果这是一个实时捕获,并且超时(如pcap_open_live()中指定,或者,如果您使用pcap_create()pcap_activate()pcap_set_timeout())在等待数据包时到期null;
  • -1,如果在阅读或捕获时发生错误,在这种情况下,没有读取数据包,并且指针将设置为null;
  • -2,如果这是一个正在读取的文件,并且没有更多的数据包要读取,在这种情况下,没有读取数据包,并且指针将设置为null。

因此,在pcap_next_ex()呼叫之后,您应该做的是:

    if (1 == rc) {
        // process
        struct ether_header* eptr = (struct ether_header *) rawPacket;
        if (ntohs (eptr->ether_type) == ETHERTYPE_IP) {
                printf("Ethernet type hex:%x dec:%d is an IP packetn",
                        ntohs(eptr->ether_type),
                        ntohs(eptr->ether_type));
        }
    } else if (0 == rc) {
        // do nothing here - this isn't an error, but you have no packet
        ;
    } else if (-1 == rc) {
        // error
        fprintf(stderr, "Error capturing or reading: %sn", pcap_geterr(pDevice));
        // quit trying to read or capture packets here
    } else if (-2 == rc) {
        // end of file if you're reading from a file
        // this isn't an error, but there are no more packets to read
        // so quit trying to read packets here
    }