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

时间:2013-08-31 16:22:11

标签: 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

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

1 个答案:

答案 0 :(得分:7)

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

您将handle分配给NULLhandle在此分配后的某些其他功能中使用if(handle == NULL)。因此,取消引用这会导致seg-fault。

将其更改为{{1}}并检查。