1.Libpcap簡介
Libpcap是Packet Capture Libray的英文縮寫,即資料包捕獲函數庫。該庫提供的C函數接口用于捕捉經過指定網絡接口的資料包,該接口應該是被設為混雜模式。這個在原始套接子中有提到。
著名的軟體TCPDUMP就是在Libpcap的基礎上開發而成的。Libpcap提供的接口函數實作和封裝了與資料包截獲有關的過程。
Libpcap提供了使用者級别的網絡資料包捕獲接口,并充分考慮到應用程式的可移植性。Libpcap可以在絕大多數Linux平台上運作。在Windows平台上,也有一款與其功能類似的開發庫:Wincap。
它的工作在上層應用程式與網絡接口之間。
主要功能:
- 資料包捕獲:捕獲流經網卡的原始資料包
- 自定義資料包發送:構造任何格式的原始資料包
- 流量采集與統計:采集網絡中的流量資訊
- 規則過濾:提供自帶規則過濾功能,按需要選擇過濾規則
它的應用範圍非常廣泛,典型應用包括玩羅協定分析器,網絡流量發生器,網絡入侵檢測系統,網絡掃描器和其他安全工具。
2.Libpcap的安裝
Libpcap的下載下傳位址:點選
切換到下載下傳目錄,解壓壓縮檔案,配置,編譯,安裝
cd ****
tar zxvf ****
./configure
make
make install
配置中如果出現錯誤,請檢視你是否安裝了所有的依賴包bison, m4, GNU, flex以及libpcap-dev(安裝方法 sudo apt-get ****)
注意運作時候,是需要root權限的 sudo ./***
測試程式:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
#include <pcap.h>
#include <stdio.h>
int main()
{
char errBuf[PCAP_ERRBUF_SIZE], * device;
device = pcap_lookupdev(errBuf);
if(device)
{
printf("success: device: %s\n", device);
}
else
{
printf("error: %s\n", errBuf);
}
return 0;
}
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
makefile檔案:
test: test.c
gcc -Wall -o test test.c -lpcap
clean:
rm -rf *.o test
3.Libpcap的工作原理
作為捕捉網絡資料包的庫,它是一個獨立于系統的使用者級的API接口,為底層網絡檢測提供了一個可移植的架構。
一個包的捕捉分為三個主要部分,包括面向底層包捕獲、面向中間層的資料包過濾和面向應用層的使用者接口。這與Linux作業系統對資料包的處理流程是相同的(網卡->網卡驅動->資料鍊路層->IP層->傳輸層->應用程式)。包捕獲機制是在資料鍊路層增加一個旁路處理(并不幹擾系統自身的網絡協定棧的處理),對發送和接收的資料包通過Linux核心做過濾和緩沖處理,最後直接傳遞給上層應用程式。
下面介紹Libpcap的抓包流程:
- 查找網絡裝置:目的是發現可用的網卡,實作的函數為pcap_lookupdev(),如果目前有多個網卡,函數就會傳回一個網絡裝置名的指針清單。
- 打開網絡裝置:利用上一步中的傳回值,可以決定使用哪個網卡,通過函數pcap_open_live()打開網卡,傳回用于捕捉網絡資料包的秒數字。
- 獲得網絡參數:這裡是利用函數pcap_lookupnet(),可以獲得指定網絡裝置的IP位址和子網路遮罩。
- 編譯過濾政策:Lipcap的主要功能就是提供資料包的過濾,函數pcap_compile()來實作。
- 設定過濾器:在上一步的基礎上利用pcap_setfilter()函數來設定。
- 利用回調函數,捕獲資料包:函數pcap_loop()和pcap_dispatch()來抓去資料包,也可以利用函數pcap_next()和pcap_next_ex()來完成同樣的工作。
- 關閉網絡裝置:pcap_close()函數關系裝置,釋放資源。
4.函數功能具體介紹與分析
1.擷取網絡接口
char * pcap_lookupdev(char * errbuf)
//上面這個函數傳回第一個合适的網絡接口的字元串指針,如果出錯,則errbuf存放出錯資訊字元串,errbuf至少應該是PCAP_ERRBUF_SIZE個位元組長度的
int pcap_lookupnet(const char * device, bpf_u_int32 * netp, bpf_u_int32 * maskp, char * errbuf)
//可以擷取指定裝置的ip位址,子網路遮罩等資訊
//netp:傳出參數,指定網絡接口的ip位址
//maskp:傳出參數,指定網絡接口的子網路遮罩
//pcap_lookupnet()失敗傳回-1
//net,mask的轉換方式,inet_ntoa可以把他轉換成10機制字元串 頭檔案 arpa/inet.h
addr.s_addr=netp;
net=inet_ntoa(addr);
addr.s_addr=maskp;
mask=inet_ntoa(addr);
舉例:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
#include <stdio.h>
#include <pcap.h>
#include <time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
void show_ip_mask(char* dev)
{
char errbuf[1024];
struct in_addr addr;
char *net,*mask;
bpf_u_int32 netp,maskp;
int err=pcap_lookupnet(dev,&netp,&maskp,errbuf);
if(err==-1){
printf("couldn't detect the ip and maskp: %s\n",errbuf);
return;
}
addr.s_addr=netp;
net=inet_ntoa(addr);
if(net==NULL){
printf("ip error\n");
return;
}
printf("ip: %s\n",net);
addr.s_addr=maskp;
mask=inet_ntoa(addr);
if(mask==NULL){
printf("mask errorn");
return;
}
printf("mask: %s\n",mask);
}
int main()
{
char *dev, errbuf[1024];
char select='a';
printf("select(dispaly the packet in detail)/n:( Y/N ?))");
scanf("%c",&select);
while(select!='Y'&&select!='y'&&select!='n'&&select!='N'){
printf("input the error!\nplease input the Y/N/y/n:");
scanf("%c",&select);
}
//look for the net device
dev=pcap_lookupdev(errbuf);
if(dev==NULL){
printf("couldn't find default device: %s\n",errbuf);
return 1;
}
else{
printf("fidn success: device :%s\n",dev);
}
//ip mask display
show_ip_mask(dev);
return 0;
}
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
2.釋放網絡接口
void pcap_close(pcap_t * p)
//該函數用于關閉pcap_open_live()擷取的pcap_t的網絡接口對象并釋放相關資源。
3.打開網絡接口
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
pcap_t * pcap_open_live(const char * device, int snaplen, int promisc, int to_ms, char * errbuf)
//上面這個函數會傳回指定接口的pcap_t類型指針,後面的所有操作都要使用這個指針。
//第一個參數是第一步擷取的網絡接口字元串,可以直接使用寫死。
//第二個參數是對于每個資料包,從開頭要抓多少個位元組,我們可以設定這個值來隻抓每個資料包的頭部,而不關心具體的内容。典型的以太網幀長度是1518位元組,但其他的某些協定的資料包會更長一點,但任何一個協定的一個資料包長度都必然小于65535個位元組。
//第三個參數指定是否打開混雜模式(Promiscuous Mode),0表示非混雜模式,任何其他值表示混合模式。如果要打開混雜模式,那麼網卡必須也要打開混雜模式,可以使用如下的指令打開eth0混雜模式:ifconfig eth0 promisc
//第四個參數指定需要等待的毫秒數,超過這個數值後,第3步擷取資料包的這幾個函數就會立即傳回。0表示一直等待直到有資料包到來。
//第五個參數是存放出錯資訊的數組。
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
4.擷取資料包
u_char * pcap_next(pcap_t * p, struct pcap_pkthdr * h)
//如果傳回值為NULL,表示沒有抓到包
//第一個參數是第2步傳回的pcap_t類型的指針
//第二個參數是儲存收到的第一個資料包的pcap_pkthdr類型的指針
pcap_pkthdr類型的定義如下:
struct pcap_pkthdr
{
struct timeval ts; /* time stamp */
bpf_u_int32 caplen; /* length of portion present */
bpf_u_int32 len; /* length this packet (off wire) */
};
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
int pcap_loop(pcap_t * p, int cnt, pcap_handler callback, u_char * user)
//第一個參數是第2步傳回的pcap_t類型的指針
//第二個參數是需要抓的資料包的個數,一旦抓到了cnt個資料包,pcap_loop立即傳回。負數的cnt表示pcap_loop永遠循環抓包,直到出現錯誤。
//第三個參數是一個回調函數指針,它必須是如下的形式:
void callback(u_char * userarg, const struct pcap_pkthdr * pkthdr, const u_char * packet)
//第一個參數是pcap_loop的最後一個參數,當收到足夠數量的包後pcap_loop會調用callback回調函數,同時将pcap_loop()的user參數傳遞給它
//第二個參數是收到的資料包的pcap_pkthdr類型的指針
//第三個參數是收到的資料包資料
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
int pcap_dispatch(pcap_t * p, int cnt, pcap_handler callback, u_char * user)
//這個函數和pcap_loop()非常類似,隻是在超過to_ms毫秒後就會傳回(to_ms是pcap_open_live()的第4個參數)
來試試這幾個函數,一個簡單的例子:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
#include <stdio.h>
#include <pcap.h>
#include <time.h>
void capture_packet1(pcap_t* device)
{
struct pcap_pkthdr packet;
char errbuf[1024];
//capture the packet
const u_char* pkt=pcap_next(device,&packet);
if(!pkt){
printf("couldn't capture packet: %s\n",errbuf);
return;
}
//output the pacaket length byte and time
printf("Packet length: %d\n", packet.len);
printf("Number of bytes: %d\n", packet.caplen);
printf("Recieved time: %s\n", ctime((const time_t*)&packet.ts.tv_sec));
}
void getPacket(u_char * arg, const struct pcap_pkthdr * pkthdr, const u_char * packet)
{
int * id = (int *)arg;
printf("id: %d\n", ++(*id));
printf("Packet length: %d\n", pkthdr->len);
printf("Number of bytes: %d\n", pkthdr->caplen);
printf("Recieved time: %s\n", ctime((const time_t *)&pkthdr->ts.tv_sec));
//print packet
int i;
for(i=0; i<pkthdr->len; ++i) {
printf(" %02x", packet[i]);
if( (i + 1) % 16 == 0 )
printf("\n");
}
printf("\n\n");
}
void capture_packet2(pcap_t* device)
{
struct pcap_pkthdr packet;
int id = 0;
//capture the packet
pcap_loop(device,-1,getPacket,(u_char*)&id);
}
int main()
{
char *dev, errbuf[1024];
char select='a';
printf("select(dispaly the packet in detail)/n:( Y/N ?))");
scanf("%c",&select);
while(select!='Y'&&select!='y'&&select!='n'&&select!='N'){
printf("input the error!\nplease input the Y/N/y/n:");
scanf("%c",&select);
}
//look for the net device
dev=pcap_lookupdev(errbuf);
if(dev==NULL){
printf("couldn't find default device: %s\n",errbuf);
return 1;
}
else{
printf("fidn success: device :%s\n",dev);
}
//open the finded device(must set :ifconfig eth0 promisc)
pcap_t* device=pcap_open_live(dev,65535,1,0,errbuf);
if(!device){
printf("couldn't open the net device: %s\n",errbuf);
return 1;
}
if(select=='Y')
capture_packet2(device);
else
while(1)//由于pcap_next()函數隻傳回下一個資料包的指針
capture_packet1(device);
return 0;
}
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
5.分析資料包
根據不同的網絡協定,來設計不同的資料包分析方法,具體參考相關協定的說明。
6.過濾資料包(這部分是非常重要的)
libpcap利用BPF來過濾資料包。
過濾資料包需要完成3件事:
a) 構造一個過濾表達式
b) 編譯這個表達式
c) 應用這個過濾器
a)Lipcap已經把BPF語言封裝成為了更進階更容易的文法了。
舉例:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
src host 127.0.0.1
//選擇隻接受某個IP位址的資料包
dst port 8000
//選擇隻接受TCP/UDP的目的端口是80的資料包
not tcp
//不接受TCP資料包
tcp[13]==0x02 and (dst port ** or dst port **)
//隻接受SYN标志位置(TCP首部開始的第13個位元組)且目标端口号是22或23的資料包
icmp[icmptype]==icmp-echoreply or icmp[icmptype]==icmp-echo
//隻接受icmp的ping請求和ping響應的資料包
ehter dst 00:00:00:00:00:00
//隻接受以太網MAC位址為00:00:00:00:00:00的資料包
ip[8]==5
//隻接受ip的ttl=5的資料包(ip首位第八的位元組為ttl)
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
b)構造完過濾表達式後,就可以使用pcap_compile()函數來編譯。
int pcap_compile(pcap_t * p, struct bpf_program * fp, char * str, int optimize, bpf_u_int32 netmask)
//fp:這是一個傳出參數,存放編譯後的bpf
//str:過濾表達式
//optimize:是否需要優化過濾表達式
//metmask:簡單設定為0即可
c)最後通過函數pcap_setfilter()來設定這個規則
int pcap_setfilter(pcap_t * p, struct bpf_program * fp)
//參數fp就是pcap_compile()的第二個參數,存放編譯後的bpf
舉例:
可以在抓包前,也就是pcap_next()或pcap_loop之前,加入下面的代碼:
//design filter
struct bpf_program filter;
pcap_compile(device, &filter, "dst port 80", 1, 0); //隻接受80端口的TCP/UDP資料包
pcap_setfilter(device, &filter);
5.基于Libpcap實作一個網絡資料包嗅探器
基本功能就是來捕獲所有流經本網卡的資料包。
實作流程:
- 查找網絡裝置
- 打開網絡裝置
- 查找裝置資訊
- 輸入過濾規則
- 編譯輸入規則
- 設定輸入規則
- 開始捕獲資料包
- 調用資料包分析子產品
- 輸出MAC,IP,協定以及資料幀
- 結束
具體實作代碼:
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
#include <stdio.h>
#include <pcap.h>
#include <time.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <errno.h>
#include <string.h>
//鍊路層資料包格式
typedef struct {
u_char DestMac[6];
u_char SrcMac[6];
u_char Etype[2];
}ETHHEADER;
//IP層資料包格式
typedef struct {
int header_len:4;
int version:4;
u_char tos:8;
int total_len:16;
int ident:16;
int flags:16;
u_char ttl:8;
u_char proto:8;
int checksum:16;
u_char sourceIP[4];
u_char destIP[4];
}IPHEADER;
//協定映射表
char *Proto[]={
"Reserved","ICMP","IGMP","GGP","IP","ST","TCP"
};
//回調函數
void pcap_handle(u_char* user,const struct pcap_pkthdr* header,const u_char* pkt_data)
{
ETHHEADER *eth_header=(ETHHEADER*)pkt_data;
printf("---------------Begin Analysis-----------------\n");
printf("----------------------------------------------\n");
printf("Packet length: %d \n",header->len);
//解析資料包IP頭部
if(header->len>=14){
IPHEADER *ip_header=(IPHEADER*)(pkt_data+14);
//解析協定類型
char strType[100];
if(ip_header->proto>7)
strcpy(strType,"IP/UNKNWN");
else
strcpy(strType,Proto[ip_header->proto]);
printf("Source MAC : %02X-%02X-%02X-%02X-%02X-%02X==>",eth_header->SrcMac[0],eth_header->SrcMac[1],eth_header->SrcMac[2],eth_header->SrcMac[3],eth_header->SrcMac[4],eth_header->SrcMac[5]);
printf("Dest MAC : %02X-%02X-%02X-%02X-%02X-%02X\n",eth_header->DestMac[0],eth_header->DestMac[1],eth_header->DestMac[2],eth_header->DestMac[3],eth_header->DestMac[4],eth_header->DestMac[5]);
printf("Source IP : %d.%d.%d.%d==>",ip_header->sourceIP[0],ip_header->sourceIP[1],ip_header->sourceIP[2],ip_header->sourceIP[3]);
printf("Dest IP : %d.%d.%d.%d\n",ip_header->destIP[0],ip_header->destIP[1],ip_header->destIP[2],ip_header->destIP[3]);
printf("Protocol : %s\n",strType);
//顯示資料幀内容
int i;
for(i=0; i<(int)header->len; ++i) {
printf(" %02x", pkt_data[i]);
if( (i + 1) % 16 == 0 )
printf("\n");
}
printf("\n\n");
}
}
int main(int argc, char **argv)
{
char *device="eth0";
char errbuf[1024];
pcap_t *phandle;
bpf_u_int32 ipaddress,ipmask;
struct bpf_program fcode;
int datalink;
if((device=pcap_lookupdev(errbuf))==NULL){
perror(errbuf);
return 1;
}
else
printf("device: %s\n",device);
phandle=pcap_open_live(device,200,0,500,errbuf);
if(phandle==NULL){
perror(errbuf);
return 1;
}
if(pcap_lookupnet(device,&ipaddress,&ipmask,errbuf)==-1){
perror(errbuf);
return 1;
}
else{
char ip[INET_ADDRSTRLEN],mask[INET_ADDRSTRLEN];
if(inet_ntop(AF_INET,&ipaddress,ip,sizeof(ip))==NULL)
perror("inet_ntop error");
else if(inet_ntop(AF_INET,&ipmask,mask,sizeof(mask))==NULL)
perror("inet_ntop error");
printf("IP address: %s, Network Mask: %s\n",ip,mask);
}
int flag=1;
while(flag){
//input the design filter
printf("Input packet Filter: ");
char filterString[1024];
scanf("%s",filterString);
if(pcap_compile(phandle,&fcode,filterString,0,ipmask)==-1)
fprintf(stderr,"pcap_compile: %s,please input again....\n",pcap_geterr(phandle));
else
flag=0;
}
if(pcap_setfilter(phandle,&fcode)==-1){
fprintf(stderr,"pcap_setfilter: %s\n",pcap_geterr(phandle));
return 1;
}
if((datalink=pcap_datalink(phandle))==-1){
fprintf(stderr,"pcap_datalink: %s\n",pcap_geterr(phandle));
return 1;
}
printf("datalink= %d\n",datalink);
pcap_loop(phandle,-1,pcap_handle,NULL);
return 0;
}
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsIiZpdmLlR2bjlHcvN2LcNXZnFWbp9CXt92YuM3ZvxmYuNmLu9Wbt92Yvw1LcpDc0RHaiojIsJye.gif)
參考資料:Linux c程式基礎與執行個體講解
http://blog.csdn.net/htttw/article/details/7521053
轉載自: cococo點點 http://www.cnblogs.com/coder2012