Question

Here is my code:

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

void pcapdump(u_char* argument,const struct pcap_pkthdr* packet_header,const u_char*   packet_content);

int main()
{
    int i=0, devid,ret;
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t *handle;
    bpf_u_int32 mask;
    bpf_u_int32 net;
    int num_packets=500;
    pcap_dumper_t *p;
    pcap_if_t *alldevs;
    pcap_if_t *pdev; 
    const struct pcap_pkthdr *packet_header;
    const u_char *packet_content;

    ret=pcap_findalldevs(&alldevs,errbuf);
    if(ret=-1)
    {
        printf("%s",errbuf);
    };

    for (pdev = alldevs;pdev;pdev=pdev->next)  
        printf("#%d: %s %s %s\n",++i,pdev->name,pdev->description,pdev->description);

    printf("select a device: "); 
    scanf("%d", &devid);  
    pdev=alldevs; 
    while (--devid)
    pdev=pdev->next;  
    printf("Selected %s \n", pdev->name);  


   if (pcap_lookupnet(pdev->name,&net,&mask,errbuf)==-1)
   {
        printf("Couldn't get netmask for device %s: %s\n", pdev->name, errbuf);
        net = 0;
        mask = 0;
    };

    handle=pcap_open_live(pdev->name,BUFSIZ,1,0,errbuf);
    printf("Number of packets: %d\n", num_packets);
    pcap_dump_open(handle,"/home/jiangzhongbai/capturefiles/10.pcapng");
    pcap_loop(handle,num_packets,pcap_dump,NULL);
    pcap_dump_close(p);
    pcap_freealldevs(alldevs); 
    pcap_close(handle);
    printf("\nCapture complete.\n");
    return 0;
}

The result is

  • eth0 (null) (null)
  • wlan0 (null) (null)
  • nflog Linux netfilter log (NFLOG) interface Linux netfilter log (NFLOG) interface
  • nfqueue Linux netfilter queue (NFQUEUE) interface Linux netfilter queue (NFQUEUE) interface
  • any Pseudo-device that captures on all interfaces Pseudo-device that captures on all interfaces
  • lo (null) (null)

select a device: 2 Selected wlan0 Number of packets: 500 Segmentation fault (core dumped)

I think there is something wrong with the functionpcap_dump_open.But I don't know how to solve the problem of Segmentation fault (core dumped).Please help me.

Was it helpful?

Solution

How to solve Segmentation fault (core dumped)

  1. If pcap_findalldevs() returns -1, don't just print an error message, quit, because alldevs isn't necessarily set to a valid value or to NULL.

  2. Do not assume that pdev->description is non-null - only print it if it's non-null.

  3. Assign the result of pcap_dump_open() to the variable p.

  4. Pass p, rather than NULL, as the fourth argument to pcap_loop().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top