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;
Your filter is wrong (s/b
ip dst host, notip dest host), the reason for the bad messages follows:errbuf– Returns error text and is only set when the pcap_lookupnet subroutine failsUpon 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.