工作流程
打開網路接口
這一步需要告訴程式我們的網卡接口,或者讓程式自己檢測。
下面這段程式檢測系統中所有可用的網卡接口並且逐一列印名稱和描述信息。
注意:由於是底層的系統調用,所以需要root許可權。否則系統會檢測不到網卡。
pcap_findalldevs();
代碼:
#include <pcap.h>
#include <stdlib.h>
#include <stdio.h>
int main(int argc, char *argv[])
{
pcap_if_t *alldevs;
pcap_if_t *device;
char errbuf[PCAP_ERRBUF_SIZE];
if(pcap_findalldevs(&alldevs, errbuf) == -1)
{
fprintf(stderr, "Error in pcap_findalldevs: %s\n", errbuf);
exit(EXIT_FAILURE);
}
device = alldevs;
for(; device != NULL; device = device->next)
{
printf("Device name: %s\n", device->name);
printf("Description: %s\n", device->description);
}
/* 不再需要設備列表了,釋放它 */
pcap_freealldevs(alldevs);
return 0;
}
個人不推薦用,官方也不推薦用pcap_lookupdev()來找網卡,windows 環境推薦 pcap_findalldevs_ex() 。
捕獲規則
打開檔案句柄使用
pcap_t *handle;
handle = pcap_open_live(device, 1000, 1, 1000, errbuf);
if(handle == NULL)
{
fprintf(stderr, "Open device : %s failed: %s\n", device, errbuf);
exit(EXIT_FAILURE);
}
sprintf(filter_exp, "ether dst//這裡是mac地址: %02x:%02x:%02x:%02x:%02x:%02x"
" and ether proto 0x8812//這裡是protocol協定",
mac[0],mac[1],
mac[2], mac[3],
mac[4], mac[5]);
編制規則
if (pcap_compile(handle, &fp, filter_exp, 0, 0) == -1) {
fprintf(stderr, "Couldn't parse filter %s: %s\n",
filter_exp, pcap_geterr(handle));
exit(EXIT_FAILURE);
}
套用規則
if (pcap_setfilter(handle, &fp) == -1) {
fprintf(stderr, "Couldn't install filter %s: %s\n",
filter_exp, pcap_geterr(handle));
exit(EXIT_FAILURE);
}
pcap_freecode(&fp);
pcap_freealldevs(alldevs);
pcap_setfilter();
關閉會話
pcap_close();