複製鏈接
請複製以下鏈接發送給好友

pcap

鎖定
這個抓包庫給抓包系統提供了一個高層次的接口。所有網絡上的數據包,甚至是那些發送給其他主機的,通過這種機制,都是可以捕獲的。它也支持把捕獲的數據包保存為本地文件和從本地文件讀取信息。
中文名
過程特性分析軟件包
設置捕獲規則
打開文件句柄使用
關閉會話
pcap_close()
進入抓包循環
pcap_loop()

pcap工作流程

pcap打開網絡接口

這一步需要告訴程序我們的網卡接口,或者讓程序自己檢測。
下面這段程序檢測系統中所有可用的網卡接口並且逐一打印名稱和描述信息。
注意:由於是底層的系統調用,所以需要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捕獲規則

打開文件句柄使用
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]);

pcap編制規則

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);
}

pcap應用規則

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關閉會話

pcap_close();