Open a live capture with pcap_open_live
Open a live capture in one call with pcap_open_live: device, snaplen, promiscuous flag, read timeout and an error buffer. libpcap 1.10.
pcap_open_live is the shortest path to a packet source. It takes the device name, the snapshot length, a promiscuous flag, a read timeout in milliseconds and a buffer of at least PCAP_ERRBUF_SIZE bytes for the error text. It returns a pcap_t *, or NULL with the error in the buffer.
#include <pcap/pcap.h>
#include <stdio.h>
int main(void)
{
char err[PCAP_ERRBUF_SIZE];
pcap_t *p = pcap_open_live("eth0", 65535, 1, 1000, err);
if (!p) {
fprintf(stderr, "pcap_open_live: %s\n", err);
return 1;
}
printf("link type %d\n", pcap_datalink(p));
pcap_close(p);
return 0;
}link type 1Build it with cc live.c -lpcap. A link type of 1 is DLT_EN10MB, plain Ethernet. When the process lacks CAP_NET_RAW the call fails, and the buffer holds eth0: You don't have permission to capture on that device.
The timeout is the surprise. On Linux with libpcap 1.10 it is a batching hint, not a guarantee of delivery within that time, and on some platforms a value of 0 means "wait forever for a full buffer". If you need packets as they arrive, use the activation API in the next snippet and ask for immediate mode. pcap_open_live also cannot set the buffer size or timestamp options, which is the reason the longer API exists. Check the pcap_open_live(3pcap) page for the full list of arguments.