& # 8203 * WinPcap gets the list of devices
Typically, the first thing you do when writing a WinPcap-based application is to get a list of connected network adapters. Both libpcap and WinPcap provide the pcap_findalldevs_ex() function to do this: This function returns a list of pcap_if structures, each of which contains details about an adapter. Notably, the data fields name and description represent an adapter name and a description that people can understand.
First, pcap_findalldevs_ex(), like other libpcap functions, has an errbuf parameter. In case of an error, this parameter will be written by libpcap as a string type error message. Second, keep in mind that not all operating systems support the network programming interface provided by libpcap, so if we want to write a portable application, we must consider when description is null. In this program, when we encounter this situation, we will print the prompt statement "No description available".
Finally, remember that when we're done using the device list, we call the pcap_freealldevs() function to free up the memory resources it occupied.
Let's compile and run our first sample program!
Implementation code:
//aa.cpp: Defines the entry point for the console application.
#include "stdafx.h"
#include "pcap.h"
int _tmain(int argc, _TCHAR* argv[])
{
pcap_if_t *alldevs;
pcap_if_t *d;
int i=0;
char errbuf[PCAP_ERRBUF_SIZE];
/* Get local machine device list */
if (pcap_findalldevs_ex(PCAP_SRC_IF_STRING, NULL /* auth is not needed */, &alldevs, errbuf) == -1)
{
fprintf(stderr,"Error in pcap_findalldevs_ex: %s\n", errbuf);
exit(1);
}
/* Print list */
for(d= alldevs; d != NULL; d= d->next)
{
printf("%d. %s", ++i, d->name);
if (d->description)
printf(" (%s)\n", d->description);
else
printf(" (No description available)\n");
}
if (i == 0)
{
printf("\nNo interfaces found! Make sure WinPcap is installed.\ n");
return 0;
}
/* Device list is no longer needed, release it */
pcap_freealldevs(alldevs);
}