網絡數據包捕獲函數庫Libpcap安裝與使用

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 ./***

測試程序:

複製代碼
#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;
}
複製代碼

makefile文件:

test: test.c
    gcc -Wall -o test test.c -lpcap
clean:
    rm -rf *.o test

3.Libpcap的工作原理

  作爲捕捉網絡數據包的庫,它是一個獨立於系統的用戶級的API接口,爲底層網絡檢測提供了一個可移植的框架。

  一個包的捕捉分爲三個主要部分,包括面向底層包捕獲、面向中間層的數據包過濾和麪嚮應用層的用戶接口。這與Linux操作系統對數據包的處理流程是相同的(網卡->網卡驅動->數據鏈路層->IP層->傳輸層->應用程序)。包捕獲機制是在數據鏈路層增加一個旁路處理(並不干擾系統自身的網絡協議棧的處理),對發送和接收的數據包通過Linux內核做過濾和緩衝處理,最後直接傳遞給上層應用程序。

  

  下面介紹Libpcap的抓包流程:

  1. 查找網絡設備:目的是發現可用的網卡,實現的函數爲pcap_lookupdev(),如果當前有多個網卡,函數就會返回一個網絡設備名的指針列表。
  2. 打開網絡設備:利用上一步中的返回值,可以決定使用哪個網卡,通過函數pcap_open_live()打開網卡,返回用於捕捉網絡數據包的秒數字。
  3. 獲得網絡參數:這裏是利用函數pcap_lookupnet(),可以獲得指定網絡設備的IP地址和子網掩碼。
  4. 編譯過濾策略:Lipcap的主要功能就是提供數據包的過濾,函數pcap_compile()來實現。
  5. 設置過濾器:在上一步的基礎上利用pcap_setfilter()函數來設置。
  6. 利用回調函數,捕獲數據包:函數pcap_loop()和pcap_dispatch()來抓去數據包,也可以利用函數pcap_next()和pcap_next_ex()來完成同樣的工作。
  7. 關閉網絡設備: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);

舉例:

複製代碼
#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;
}
複製代碼

 

2.釋放網絡接口

void pcap_close(pcap_t * p)
//該函數用於關閉pcap_open_live()獲取的pcap_t的網絡接口對象並釋放相關資源。

3.打開網絡接口

複製代碼
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表示一直等待直到有數據包到來。
//第五個參數是存放出錯信息的數組。
複製代碼

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) */
};
複製代碼
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類型的指針
//第三個參數是收到的數據包數據
複製代碼
int pcap_dispatch(pcap_t * p, int cnt, pcap_handler callback, u_char * user)
//這個函數和pcap_loop()非常類似,只是在超過to_ms毫秒後就會返回(to_ms是pcap_open_live()的第4個參數)

   

  來試試這幾個函數,一個簡單的例子:

複製代碼
#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;
}
複製代碼

5.分析數據包

  根據不同的網絡協議,來設計不同的數據包分析方法,具體參考相關協議的說明。

6.過濾數據包(這部分是非常重要的)

  libpcap利用BPF來過濾數據包。
  過濾數據包需要完成3件事:
  a) 構造一個過濾表達式
  b) 編譯這個表達式
  c) 應用這個過濾器

  a)Lipcap已經把BPF語言封裝成爲了更高級更容易的語法了。

  舉例:

複製代碼
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)
複製代碼

 

  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實現一個網絡數據包嗅探器

  基本功能就是來捕獲所有流經本網卡的數據包。

  實現流程:

  1. 查找網絡設備
  2. 打開網絡設備
  3. 查找設備信息
  4. 輸入過濾規則
  5. 編譯輸入規則
  6. 設置輸入規則
  7. 開始捕獲數據包
  8. 調用數據包分析模塊
  9. 輸出MAC,IP,協議以及數據幀
  10. 結束 

具體實現代碼:

複製代碼
#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;
}
複製代碼

 

參考資料:Linux c程序基礎與實例講解

     http://blog.csdn.net/htttw/article/details/7521053 

轉載自:cococo點點 http://www.cnblogs.com/coder2012
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章