Identify the Network Interface

To capture packets from a network interface, we need to supply libpcap with a network interface to use for packet capture. We have a number of different options, including specifying a network interface, asking libpcap to automatically find an appropriate interface, obtaining a list of the available interfaces, and in recent versions of libpcap, using all available interfaces to capture traffic.

Tip

libpcap does not support all network interfaces. Most Ethernet cards will work, as will most wireless cards while capturing packets on the network you are associated to. libpcap generates an error for any network interface supplied to it that it cannot determine how to open.

The easiest way is to let libpcap choose a suitable interface:

#include <pcap.h>

char *device;                         /* device to sniff on */
char errbuf[PCAP_ERRBUF_SIZE];        /* pcap error messages buffer */

device = pcap_lookupdev (errbuf);     /* let pcap find a compatible device */

if (device == NULL)                   /* there was an error */
  {
    fprintf (stderr, "%s", errbuf);
    exit (1);
  }

To use the libpcap functions, we are including the pcap.h header file. This contains the libpcap function definitions as well as other handy, predefined values, such as PCAP_ERRBUF_SIZE.

The prototype for pcap_lookupdev is as follows:

char *pcap_lookupdev(char *errbuf)

This function returns the name of an appropriate interface to be used for packet capture. For Linux this is typically eth0 or something similar, but this might be different for other ...

Get Network Security Tools now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.