0

遵循示例http://www.tcpdump.org/pcap.htm并浏览文档后,我看不出我在以下代码中做错了什么

// main.c
void got_packet(u_char *args, struct pcap_pkthdr *header, const u_char *packet);
/// ...snip...
void got_packet(u_char *args, struct pcap_pkthdr *header, const u_char *packet) {
  printf("Received Packet\n");
}
/// ...snip...
pcap_dispatch(handle, 100, got_packet, NULL);

保证我看到的编译器警告:

gcc -g -O3 -I../sensor/   -c -o sensordatad.o sensordatad.c
main.c: In function ‘start_capture’:
main.c:96:27: warning: initialization from incompatible pointer type [enabled by default]
main.c:146:3: warning: passing argument 3 of ‘pcap_dispatch’ from incompatible pointer     
                       type [enabled by default]

可能是我太挑剔了,似乎我见过的所有其他 C 代码在编译时都有一个充满编译器警告的页面,但我想至少在没有警告的情况下完成这段代码!

我也尝试过这样做,以某种方式对函数指针进行类型转换,这是我在任何示例中都没有看到的;但我觉得值得一试:

pcap_handler callback = &got_packet;
/// ...snip...
pcap_dispatch(handle, 100, &callback, NULL);

这导致了同样令人困惑的错误:

main.c: In function ‘start_capture’:
main.c:96:27: warning: initialization from incompatible pointer type [enabled by default]

这是我第一次遇到具有特殊 typedef 类型的函数指针,手册页pcap_{loop,dispatch}如下:

NAME pcap_loop, pcap_dispatch - 处理来自实时捕获或保存文件的数据包

概要#包括

      typedef void (*pcap_handler)(u_char *user, const struct pcap_pkthdr *h,
                                  const u_char *bytes);

      int pcap_loop(pcap_t *p, int cnt,
              pcap_handler callback, u_char *user);
      int pcap_dispatch(pcap_t *p, int cnt,
              pcap_handler callback, u_char *user);
4

1 回答 1

0

解决了

函数签名应该是:

void got_packet(u_char *args, const struct pcap_pkthdr *header, const u_char *packet);

我有:

void got_packet(u_char *args, struct pcap_pkthdr *header, const u_char *packet);

我想在某些方面这个错误是有道理的?!但无论如何解决了。

于 2013-04-08T14:14:37.280 回答