【问题标题】:pcap_loop function is not "reactive". Why?pcap_loop 函数不是“反应性的”。为什么?
【发布时间】:2012-06-22 01:48:00
【问题描述】:

为什么调用 pcap_loop 函数后,我必须等待几秒钟才能捕获第一个数据包?

void print_packet(u_char *, const struct pcap_pkthdr *, const u_char *);

int main(int argc, char * argv[])
{
    pcap_t * handle;
    char dev_name[] = "en0";
    char err_buf[PCAP_ERRBUF_SIZE];

    handle = pcap_open_live(dev_name, 4096, 1, 0, err_buf);

    if (handle == NULL) {
        fprintf(stderr, "Couldn't open device %s: %s\n" , dev_name , err_buf);
        exit(1);
    }

    pcap_loop(handle, 1, print_packet, NULL);
    pcap_close(handle);

    exit(0);
}

void print_packet(u_char * args, const struct pcap_pkthdr * hdr, const u_char * buff)
{
    /* ... */
}

【问题讨论】:

  • tcpdump -i eth0 立即开始给我数据包;我假设tcpdump 使用pcap_loop()。你能准备一个简短的演示程序来展示延迟吗?

标签: c macos unix libpcap


【解决方案1】:

我通过阅读pcap_open_live 文档发现了问题:

pcap_t *pcap_open_live(const char *device, int snaplen, int promisc, int to_ms, char *errbuf)

[...] to_ms 以毫秒为单位指定读取超时。读 超时用于安排读取不一定在看到数据包时立即返回, 但它会等待一段时间以允许更多数据包到达并读取多个数据包 从操作系统内核一次操作。并非所有平台都支持读取超时;在平台上 不要,读取超时被忽略。在支持读取时间的平台上,to_ms 的值为零 - out,将导致读取永远等待以允许足够的数据包到达,没有超时。 [...]

Source.

【讨论】:

  • 感谢您分享解决方案。最近,我在 python/pcapy 中遇到了类似的延迟问题
猜你喜欢
  • 1970-01-01
  • 2021-02-27
  • 2017-12-27
  • 2018-12-01
  • 2018-08-24
  • 2011-05-12
  • 2020-09-24
  • 2010-11-04
  • 2021-12-09
相关资源
最近更新 更多