c - 运行一个简单的 libpcap 示例时出错

标签 c network-programming pcap libpcap tcpdump

我正在尝试编译一个简单的 libpcap 示例,

#include<stdio.h>
#include<pcap.h>

int main(int argc, char *argv[])
{
  char *dev;
  char errbuf[PCAP_ERRBUF_SIZE];
  struct bpf_program fp;

  char filter_exp[] = "port 23";
  bpf_u_int32 mask;
  bpf_u_int32 net;
  dev = pcap_lookupdev(errbuf);
  if (dev == NULL )
  {
    fprintf(stderr, "couldn't find default device: %s\n", errbuf);
    return (2);
  }
  printf("Device: %s\n", dev);

  //LOOKUP NETMASK and IP
  if (pcap_lookupnet(dev, &net, &mask, errbuf) == -1)
  {
    fprintf(stderr, "can't get netmask for device %s\n", dev);
    net = 0;
    mask = 0;
  }

  printf("lookup\n");

  pcap_t *handle;
  printf("handle defined\n");
  handle = pcap_open_live(dev, BUFSIZ, 1, 1000, errbuf);
  printf("opened\n");
  if (handle = NULL )
  {
    fprintf(stderr, "Couldn't open device %s: %s\n", dev, errbuf);
    return (2);
  }

  printf("pcap_open\n");

  if ((pcap_compile(handle, &fp, filter_exp, 1, net)) == -1)
  {
    printf("compile error block entered\n");
    fprintf(stderr, "Couldn't parse filter %s: %s\n", filter_exp,
        pcap_geterr(handle));
    return (2);
  }

  printf("compiled\n");
  if (pcap_setfilter(handle, &fp) == -1)
  {
    fprintf(stderr, "couldn't install filter %s: %s\n", filter_exp,
        pcap_geterr(handle));
    return (2);
  }

  printf("after filter\n");
  return (0);
}

它编译没有错误,但是当我尝试运行它时,我收到段错误消息,或者如果我尝试以 root 权限运行它,我没有收到消息但程序在打印后停止

Device: eth0
lookup
handle defined
opened
pcap_open

你能帮我解决这个问题吗,我很困惑为什么会发生这个错误。 提前致谢。

最佳答案

if (handle = NULL) 这就是罪魁祸首。

您正在将 handle 分配给 NULL 并且 handle 在此分配后用于其他一些函数。因此,取消引用它会导致段错误。

将其更改为 if(handle == NULL) 并检查。

关于c - 运行一个简单的 libpcap 示例时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18550208/

相关文章:

c - 上游维护者的工具?用于发布前的测试(Debian等)

c - 如何查看 "char *str = "yoo 的内存"; "

c - 为什么我不能通过pcap从外部设备接收GVSP/UDP数据?

ruby - 如何在 Windows 上为 ruby​​ 安装 PCAP

ios - 如何将 URLSessionStreamTask 与 URLSession 一起用于分块编码传输

c++ - 如何将多个参数传递给 pcap_loop()/pcap_handler()?

c - 删除数组中的重复项并用未使用的值替换它们

c++ - 如何将 void* 转换为 foo* 以符合 C++?

c++ - gethostbyname 替换 IPv6 地址

java - 无法为我的 Java 应用程序选择正确的网络解决方案