0

When I try to run this function it runs into a wall at the second if statement and printing: cannot set pcap filter: ip dest host 92.40.255.82 ��z]$ (note the odd symbols at the end). I suspect the error lies in the bpf_program filterprog but haven't had any luck in sorting it out. I've checked the relevant man pages and unless I've missed something the functions I've used should be ok... so I'm stumped. Has it got something to do with the symbols at the end of the error message? Why won't it set the filter?

void capture()
{
pcap_t *pd;
bpf_u_int32 netmask;
bpf_u_int32 localnet;
char filterbuf[64];
snprintf(filterbuf, sizeof(filterbuf), "ip dest host %s", dstip); 
char *filter = filterbuf;       
char *dev = NULL;
char errbuf[PCAP_ERRBUF_SIZE];
struct bpf_program filterprog;
int dl = 0, dl_len = 0;

if ((pd = pcap_open_live(dev, 1514, 1, 500, errbuf)) == NULL) 
    {           
        fprintf(stderr, "cannot open device %s: %s\n", dev, errbuf);
        exit(1);
    }

pcap_lookupnet(dev, &localnet, &netmask, errbuf);
pcap_compile(pd, &filterprog, filter, 0, localnet);
if (pcap_setfilter(pd, &filterprog) == - 1)
    {
        fprintf(stderr, "cannot set pcap filter: %s %s\n", filter, errbuf);
        exit(1);
    }

pcap_freecode(&filterprog);
dl = pcap_datalink(pd);

switch(dl) {
    case 1:
        dl_len = 14;
        break;
    default:
        dl_len = 14;
        break;
}       

if (pcap_loop(pd, -1, receive, (u_char *) &dl_len) < 0) 
    {
        fprintf(stderr, "cannot get raw packet: %s\n", pcap_geterr(pd));
        exit(1);
    }
}

edit: these are the other references to dstip:

(in prototypes) char *dstip = 0;

(in main) dstip = optarg;

youjustreadthis
  • 622
  • 3
  • 9
  • 24

1 Answers1

1

Your filter is wrong (s/b ip dst host, not ip dest host), the reason for the bad messages follows:

errbuf - Returns error text and is only set when the pcap_lookupnet subroutine fails

Upon successful completion, the pcap_setfilter subroutine returns 0. If the pcap_setfilter subroutine is unsuccessful, -1 is returned. In this case, the pcap_geterr subroutine can be used to get the error text, and the pcap_perror subroutine can be used to display the text.

KevinDTimm
  • 14,226
  • 3
  • 42
  • 60
  • And `pcap_compile()` is *not* guaranteed to succeed, so you should never ignore its return value. If it returns -1, use `pcap_geterr()` on the `pcap_t *` to get an error message and report it, so you'll get an error such as "syntax error" for "ip dest host" (just as you get from tcpdump). –  Aug 21 '12 at 20:54
  • @GuyHarris - I couldn't agree more. There are so many fundamental errors in the OP's code that I chose to only fix what was asked. This code needs a major rewrite with a plethora of defensive coding added. – KevinDTimm Aug 21 '12 at 20:58