概述
libpcap 是一個網絡資料包捕獲函數庫,功能非常強大,Linux 下著名的 tcpdump 就是以它為基礎的。
libpcap主要的作用
1)捕獲各種資料包,列如:網絡流量統計。
2)過濾網絡資料包,列如:過濾掉本地上的一些資料,類似防火牆。
3)分析網絡資料包,列如:分析網絡協定,資料的采集。
4)存儲網絡資料包,列如:儲存捕獲的資料以為将來進行分析。
libpcap 的安裝
libpcap 的抓包架構
pcap_lookupdev():函數用于查找網絡裝置,傳回可被 pcap_open_live() 函數調用的網絡裝置名指針。
pcap_lookupnet():函數獲得指定網絡裝置的網絡号和掩碼。
pcap_open_live(): 函數用于打開網絡裝置,并且傳回用于捕獲網絡資料包的資料包捕獲描述字。對于此網絡裝置的操作都要基于此網絡裝置描述字。
pcap_compile(): 函數用于将使用者制定的過濾政策編譯到過濾程式中。
pcap_setfilter():函數用于設定過濾器。
pcap_loop():函數 pcap_dispatch() 函數用于捕獲資料包,捕獲後還可以進行處理,此外 pcap_next() 和 pcap_next_ex() 兩個函數也可以用來捕獲資料包。
pcap_close():函數用于關閉網絡裝置,釋放資源。
利用 libpcap 函數庫開發應用程式的基本步驟:
1、打開網絡裝置
2、設定過濾規則
3、捕獲資料
4、關閉網絡裝置
抓包詳細步驟
首先要使用 libpcap,我們必須包含 pcap.h 頭檔案,可以在 /usr/local/include/pcap/pcap.h 找到,其中包含了每個類型定義的詳細說明。
1、擷取網絡接口裝置名
char *pcap_lookupdev(char *errbuf);
功能:
得到可用的網絡裝置名指針
參數:
errbuf:存放出錯資訊字元串,裡面有個宏定義:PCAP_ERRBUF_SIZE,為錯誤緩沖區大小
傳回值:
成功傳回裝置名指針(第一個合适的網絡接口的字元串指針);
失敗傳回 NULL,同時,errbuf 存放出錯資訊字元串。
執行個體如下:
char error_content[PCAP_ERRBUF_SIZE] = {0}; // 出錯資訊
char *dev = pcap_lookupdev(error_content);
if(NULL == dev)
{
printf(error_content);
exit(-1);
}
2、擷取網絡号(ip 位址)和掩碼
int pcap_lookupnet( char *device,
bpf_u_int32 *netp,
bpf_u_int32 *maskp,
char *errbuf );
功能:
擷取指定網卡的 ip 位址,子網路遮罩
參數:
device:網絡裝置名,為第一步擷取的網絡接口字元串(pcap_lookupdev() 的傳回值 ),也可人為指定,如“eth0”。
netp:存放 ip 位址的指針,bpf_u_int32 為 32 位無符号整型
maskp:存放子網路遮罩的指針,bpf_u_int32 為 32 位無符号整型
errbuf:存放出錯資訊
傳回值:
成功傳回 0,失敗傳回 -1
執行個體如下:
char error_content[PCAP_ERRBUF_SIZE] = {0}; // 出錯資訊
char *dev = pcap_lookupdev(error_content);
if(NULL == dev)
{
printf(error_content);
exit(-1);
}
bpf_u_int32 netp = 0, maskp = 0;
pcap_t * pcap_handle = NULL;
int ret = 0;
//獲得網絡号和掩碼
ret = pcap_lookupnet(dev, &netp, &maskp, error_content);
if(ret == -1)
{
printf(error_content);
exit(-1);
}
3、打開網絡接口
pcap_t *pcap_open_live( const char *device,
int snaplen,
int promisc,
int to_ms,
char *ebuf );
功能
:
打開一個用于捕獲資料的網絡接口
參數:
device:網絡接口的名字,為第一步擷取的網絡接口字元串(pcap_lookupdev() 的傳回值 ),也可人為指定,如“eth0”。
snaplen:捕獲資料包的長度,長度不能大于 65535 個位元組。
promise:“1” 代表混雜模式,其它非混雜模式。什麼為混雜模式,請看《原始套接字程式設計》。
to_ms:指定需要等待的毫秒數,超過這個數值後,擷取資料包的函數就會立即傳回(這個函數不會阻塞,後面的抓包函數才會阻塞)。0 表示一直等待直到有資料包到來。
ebuf:存儲錯誤資訊。
傳回值:
傳回 pcap_t 類型指針,後面的所有操作都要使用這個指針。
執行個體如下:
char error_content[PCAP_ERRBUF_SIZE] = {0}; // 出錯資訊
char *dev = pcap_lookupdev(error_content); // 擷取網絡接口
if(NULL == dev)
{
printf(error_content);
exit(-1);
}
// 打開網絡接口
pcap_t * pcap_handle = pcap_open_live(dev, 1024, 1, 0, error_content);
if(NULL == pcap_handle)
{
printf(error_content);
exit(-1);
}
4、擷取資料包
a)
const u_char *pcap_next(pcap_t *p, struct pcap_pkthdr *h);
功能:
捕獲一個網絡資料包,收到一個資料包立即傳回
參數:
p:pcap_open_live()傳回的 pcap_t 類型的指針
h:資料標頭
pcap_pkthdr 類型的定義如下:
struct pcap_pkthdr
{
struct timeval ts; // 抓到包的時間
bpf_u_int32 caplen; // 表示抓到的資料長度
bpf_u_int32 len; // 表示資料包的實際長度
}
len 和 caplen的差別:
因為在某些情況下你不能保證捕獲的包是完整的,例如一個包長 1480,但是你捕獲到 1000 的時候,可能因為某些原因就中止捕獲了,是以 caplen 是記錄實際捕獲的包長,也就是 1000,而 len 就是 1480。
傳回值:
成功傳回捕獲資料包的位址,失敗傳回 NULL
執行個體如下:
const unsigned char *p_packet_content = NULL; // 儲存接收到的資料包的起始位址
pcap_t *pcap_handle = NULL;
struct pcap_pkthdr protocol_header;
pcap_handle = pcap_open_live("eth0", 1024, 1, 0,NULL);
p_packet_content = pcap_next(pcap_handle, &protocol_header);
//p_packet_content 所捕獲資料包的位址
printf("Capture Time is :%s",ctime((const time_t *)&protocol_header.ts.tv_sec)); // 時間
printf("Packet Lenght is :%d\n",protocol_header.len); // 資料包的實際長度
// 分析以太網中的 源mac、目的mac
struct ether_header *ethernet_protocol = NULL;
unsigned char *p_mac_string = NULL; // 儲存mac的位址,臨時變量
ethernet_protocol = (struct ether_header *)p_packet_content; //struct ether_header 以太網幀頭部
p_mac_string = (unsigned char *)ethernet_protocol->ether_shost;//擷取源mac
printf("Mac Source Address is %02x:%02x:%02x:%02x:%02x:%02x\n",*(p_mac_string+0),*(p_mac_string+1),*(p_mac_string+2),*(p_mac_string+3),*(p_mac_string+4),*(p_mac_string+5));
p_mac_string = (unsigned char *)ethernet_protocol->ether_dhost;//擷取目的mac
printf("Mac Destination Address is %02x:%02x:%02x:%02x:%02x:%02x\n",*(p_mac_string+0),*(p_mac_string+1),*(p_mac_string+2),*(p_mac_string+3),*(p_mac_string+4),*(p_mac_string+5));
b)
int pcap_loop( pcap_t *p,
int cnt,
pcap_handler callback,
u_char *user );
功能:
循環捕獲網絡資料包,直到遇到錯誤或者滿足退出條件。每次捕獲一個資料包就會調用 callback 指定的回調函數,是以,可以在回調函數中進行資料包的處理操作。
參數:
p:pcap_open_live()傳回的 pcap_t 類型的指針。
cnt:指定捕獲資料包的個數,一旦抓到了 cnt 個資料包,pcap_loop 立即傳回。如果是 -1,就會永無休止的捕獲,直到出現錯誤。
callback:回調函數,名字任意,根據需要自行起名。
user:向回調函數中傳遞的參數。
callback 回調函數的定義:
void callback( u_char *userarg,
const struct pcap_pkthdr * pkthdr,
const u_char * packet )
userarg:pcap_loop() 的最後一個參數,當收到足夠數量的包後 pcap_loop 會調用callback 回調函數,同時将pcap_loop()的user參數傳遞給它
pkthdr:是收到資料包的 pcap_pkthdr 類型的指針,和 pcap_next() 第二個參數是一樣的。
packet :收到的資料包資料
傳回值:
成功傳回0,失敗傳回負數
執行個體如下:
if( pcap_loop(pcap_handle, -1, ethernet_protocol_callback, NULL) < 0 )
{
perror("pcap_loop");
}
/*******************************回調函數************************************/
void ethernet_protocol_callback(unsigned char *argument,const struct pcap_pkthdr *packet_heaher,const unsigned char *packet_content)
{
unsigned char *mac_string; //
struct ether_header *ethernet_protocol;
unsigned short ethernet_type; //以太網類型
printf("----------------------------------------------------\n");
printf("%s\n", ctime((time_t *)&(packet_heaher->ts.tv_sec))); //轉換時間
ethernet_protocol = (struct ether_header *)packet_content;
mac_string = (unsigned char *)ethernet_protocol->ether_shost;//擷取源mac位址
printf("Mac Source Address is %02x:%02x:%02x:%02x:%02x:%02x\n",*(mac_string+0),*(mac_string+1),*(mac_string+2),*(mac_string+3),*(mac_string+4),*(mac_string+5));
mac_string = (unsigned char *)ethernet_protocol->ether_dhost;//擷取目的mac
printf("Mac Destination Address is %02x:%02x:%02x:%02x:%02x:%02x\n",*(mac_string+0),*(mac_string+1),*(mac_string+2),*(mac_string+3),*(mac_string+4),*(mac_string+5));
ethernet_type = ntohs(ethernet_protocol->ether_type);//獲得以太網的類型
printf("Ethernet type is :%04x\n",ethernet_type);
switch(ethernet_type)
{
case 0x0800:printf("The network layer is IP protocol\n");break;//ip
case 0x0806:printf("The network layer is ARP protocol\n");break;//arp
case 0x0835:printf("The network layer is RARP protocol\n");break;//rarp
default:break;
}
usleep(800*1000);
}
c)
int pcap_dispatch(pcap_t * p, int cnt, pcap_handler callback, u_char * user);
這個函數和 pcap_loop() 非常類似,隻是在超過 to_ms 毫秒後就會傳回( to_ms 是pcap_open_live() 的第4個參數 )
5、釋放網絡接口
void pcap_close(pcap_t *p);
功能:
關閉 pcap_open_live() 打開的網絡接口(即其傳回值,pcap_t 類型指針),并釋放相關資源。注意,操作完網絡接口,應該釋放其資源。
參數:
p:需要關閉的網絡接口,pcap_open_live() 的傳回值(pcap_t 類型指針)
傳回值:
無
執行個體如下:
// 打開網絡接口
pcap_t * pcap_handle = pcap_open_live("eth0", 1024, 1, 0, error_content);
if(NULL == pcap_handle)
{
printf(error_content);
exit(-1);
}
……
……
pcap_close(pcap_handle); //釋放網絡接口
例子1(接收一個資料包):
#include <stdio.h>
#include <pcap.h>
#include <arpa/inet.h>
#include <time.h>
#include <stdlib.h>
struct ether_header
{
unsigned char ether_dhost[6]; //目的mac
unsigned char ether_shost[6]; //源mac
unsigned short ether_type; //以太網類型
};
#define BUFSIZE 1514
int main(int argc,char *argv[])
{
pcap_t * pcap_handle = NULL;
char error_content[100] = ""; // 出錯資訊
const unsigned char *p_packet_content = NULL; // 儲存接收到的資料包的起始位址
unsigned char *p_mac_string = NULL; // 儲存mac的位址,臨時變量
unsigned short ethernet_type = 0; // 以太網類型
char *p_net_interface_name = NULL; // 接口名字
struct pcap_pkthdr protocol_header;
struct ether_header *ethernet_protocol;
//獲得接口名
p_net_interface_name = pcap_lookupdev(error_content);
if(NULL == p_net_interface_name)
{
perror("pcap_lookupdev");
exit(-1);
}
//打開網絡接口
pcap_handle = pcap_open_live(p_net_interface_name,BUFSIZE,1,0,error_content);
p_packet_content = pcap_next(pcap_handle,&protocol_header);
printf("------------------------------------------------------------------------\n");
printf("capture a Packet from p_net_interface_name :%s\n",p_net_interface_name);
printf("Capture Time is :%s",ctime((const time_t *)&protocol_header.ts.tv_sec));
printf("Packet Lenght is :%d\n",protocol_header.len);
/*
*分析以太網中的 源mac、目的mac
*/
ethernet_protocol = (struct ether_header *)p_packet_content;
p_mac_string = (unsigned char *)ethernet_protocol->ether_shost;//擷取源mac
printf("Mac Source Address is %02x:%02x:%02x:%02x:%02x:%02x\n",*(p_mac_string+0),*(p_mac_string+1),*(p_mac_string+2),*(p_mac_string+3),*(p_mac_string+4),*(p_mac_string+5));
p_mac_string = (unsigned char *)ethernet_protocol->ether_dhost;//擷取目的mac
printf("Mac Destination Address is %02x:%02x:%02x:%02x:%02x:%02x\n",*(p_mac_string+0),*(p_mac_string+1),*(p_mac_string+2),*(p_mac_string+3),*(p_mac_string+4),*(p_mac_string+5));
/*
*獲得以太網的資料包的位址,然後分析出上層網絡協定的類型
*/
ethernet_type = ntohs(ethernet_protocol->ether_type);
printf("Ethernet type is :%04x\t",ethernet_type);
switch(ethernet_type)
{
case 0x0800:printf("The network layer is IP protocol\n");break;//ip
case 0x0806:printf("The network layer is ARP protocol\n");break;//arp
case 0x0835:printf("The network layer is RARP protocol\n");break;//rarp
default:printf("The network layer unknow!\n");break;
}
pcap_close(pcap_handle);
return 0;
}
注意:gcc 編譯時需要加上 -lpcap,運作時需要使用超級權限
例子2(接收多個資料包):
#include <stdio.h>
#include <pcap.h>
#include <arpa/inet.h>
#include <time.h>
#include <stdlib.h>
#define BUFSIZE 1514
struct ether_header
{
unsigned char ether_dhost[6]; //目的mac
unsigned char ether_shost[6]; //源mac
unsigned short ether_type; //以太網類型
};
/*******************************回調函數************************************/
void ethernet_protocol_callback(unsigned char *argument,const struct pcap_pkthdr *packet_heaher,const unsigned char *packet_content)
{
unsigned char *mac_string; //
struct ether_header *ethernet_protocol;
unsigned short ethernet_type; //以太網類型
printf("----------------------------------------------------\n");
printf("%s\n", ctime((time_t *)&(packet_heaher->ts.tv_sec))); //轉換時間
ethernet_protocol = (struct ether_header *)packet_content;
mac_string = (unsigned char *)ethernet_protocol->ether_shost;//擷取源mac位址
printf("Mac Source Address is %02x:%02x:%02x:%02x:%02x:%02x\n",*(mac_string+0),*(mac_string+1),*(mac_string+2),*(mac_string+3),*(mac_string+4),*(mac_string+5));
mac_string = (unsigned char *)ethernet_protocol->ether_dhost;//擷取目的mac
printf("Mac Destination Address is %02x:%02x:%02x:%02x:%02x:%02x\n",*(mac_string+0),*(mac_string+1),*(mac_string+2),*(mac_string+3),*(mac_string+4),*(mac_string+5));
ethernet_type = ntohs(ethernet_protocol->ether_type);//獲得以太網的類型
printf("Ethernet type is :%04x\n",ethernet_type);
switch(ethernet_type)
{
case 0x0800:printf("The network layer is IP protocol\n");break;//ip
case 0x0806:printf("The network layer is ARP protocol\n");break;//arp
case 0x0835:printf("The network layer is RARP protocol\n");break;//rarp
default:break;
}
usleep(800*1000);
}
int main(int argc, char *argv[])
{
char error_content[100]; //出錯資訊
pcap_t * pcap_handle;
unsigned char *mac_string;
unsigned short ethernet_type; //以太網類型
char *net_interface = NULL; //接口名字
struct pcap_pkthdr protocol_header;
struct ether_header *ethernet_protocol;
//擷取網絡接口
net_interface = pcap_lookupdev(error_content);
if(NULL == net_interface)
{
perror("pcap_lookupdev");
exit(-1);
}
pcap_handle = pcap_open_live(net_interface,BUFSIZE,1,0,error_content);//打開網絡接口
if(pcap_loop(pcap_handle,-1,ethernet_protocol_callback,NULL) < 0)
{
perror("pcap_loop");
}
pcap_close(pcap_handle);
return 0;
}
運作情況如下:
過濾資料包
我們抓到的資料包往往很多,如何過濾掉我們不感興趣的資料包呢?
幾乎所有的作業系統( BSD, AIX, Mac OS, Linux 等)都會在核心中提供過濾資料包的方法,主要都是基于 BSD Packet Filter( BPF ) 結構的。libpcap 利用 BPF 來過濾資料包。
1)設定過濾條件
BPF 使用一種類似于彙編語言的文法書寫過濾表達式,不過 libpcap 和 tcpdump 都把它封裝成更進階且更容易的文法了,具體可以通過 man tcpdump檢視:
以下是一些例子:
src host 192.168.1.177
隻接收源 ip 位址是 192.168.1.177 的資料包
dst port 80
隻接收 tcp/udp 的目的端口是 80 的資料包
not tcp
隻接收不使用 tcp 協定的資料包
tcp[13] == 0x02 and (dst port 22 or dst port 23)
隻接收 SYN 标志位置位且目标端口是 22 或 23 的資料包( tcp 首部開始的第 13 個位元組)
icmp[icmptype] == icmp-echoreply or icmp[icmptype] == icmp-echo
隻接收 icmp 的 ping 請求和 ping 響應的資料包
ehter dst 00:e0:09:c1:0e:82
隻接收以太網 mac 位址是 00:e0:09:c1:0e:82 的資料包
ip[8] == 5
隻接收 ip 的 ttl=5 的資料包(ip首部開始的第8個位元組)
2)編譯 BPF 過濾規則
int pcap_compile( pcap_t *p,
struct bpf_program *fp,
char *buf,
int optimize,
bpf_u_int32 mask );
功能:
編譯 BPF 過濾規則
參數:
p:pcap_open_live() 傳回的 pcap_t 類型的指針
fp:存放編譯後的 bpf,應用過濾規則時需要用到這個指針
buf:過濾條件
optimize:是否需要優化過濾表達式
mask:指定本地網絡的網絡掩碼,不需要時可寫 0
傳回值:
成功傳回 0,失敗傳回 -1
3)應用 BPF 過濾規則
int pcap_setfilter( pcap_t * p, struct bpf_program * fp );
功能:
應用 BPF 過濾規則,簡單了解為讓過濾生效
參數:
p:pcap_open_live() 傳回的 pcap_t 類型的指針
fp:pcap_compile() 的第二個參數
傳回值:
成功傳回 0,失敗傳回 -1
這個編譯應用過程,有點類似于,我們寫一個 C 程式,先編譯,後運作的過程。
應用完過濾表達式之後我們便可以使用 pcap_loop() 或 pcap_next() 等抓包函數來抓包了。
下面的程式示範了如何過濾資料包,我們隻接收目的端口是 80 的資料包:
#include <pcap.h>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
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", ctime((const time_t *)&pkthdr->ts.tv_sec));
int i;
for(i=0; i<pkthdr->len; ++i)
{
printf(" %02x", packet[i]);
if( (i + 1) % 16 == 0 )
{
printf("\n");
}
}
printf("\n\n");
}
int main()
{
char errBuf[PCAP_ERRBUF_SIZE], * devStr;
/* get a device */
devStr = pcap_lookupdev(errBuf);
if(devStr)
{
printf("success: device: %s\n", devStr);
}
else
{
printf("error: %s\n", errBuf);
exit(1);
}
/* open a device, wait until a packet arrives */
pcap_t * device = pcap_open_live(devStr, 65535, 1, 0, errBuf);
if(!device)
{
printf("error: pcap_open_live(): %s\n", errBuf);
exit(1);
}
/* construct a filter */
struct bpf_program filter;
pcap_compile(device, &filter, "dst port 80", 1, 0);
pcap_setfilter(device, &filter);
/* wait loop forever */
int id = 0;
pcap_loop(device, -1, getPacket, (u_char*)&id);
pcap_close(device);
return 0;
}