0

我正在尝试编译一个简单的 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

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

4

1 回答 1

7

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

handle在此分配之后,您正在分配NULLhandle用于其他一些功能。因此,取消引用会导致段错误。

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

于 2013-08-31T16:26:41.387 回答