libpcap/save_packet_to_file.c

libpcap可以將封包儲存到檔案內,可以再由Wireshark(當然囉,一樣都是libpcap開發的)。

Source Code

//
//  save_packet_to_file.c
//  功能:將封包儲存到檔案。
//  Created by 聲華 陳 on 2016/01/05.
//

#include <stdio.h>
#include <stdlib.h>
#include <pcap.h>

void pcap_callback(u_char *arg, const struct pcap_pkthdr *header, const u_char *content);

int main(int argc, const char * argv[]) {
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t *handle = NULL;
    pcap_dumper_t *dumper = NULL;

    //open interface
    handle = pcap_open_live("en0", 65535, 1, 1, errbuf);
    if(!handle) {
        fprintf(stderr, "pcap_open_live: %s\n", errbuf);
        exit(1);
    }//end if

    //open file handler
    dumper = pcap_dump_open(handle, "./packet.pcap");
    if(!dumper) {
        fprintf(stderr, "pcap_dump_open: %s\n", pcap_geterr(handle));
        pcap_close(handle);
        exit(1);
    }//end if

    //start capture loop
    if(0 != pcap_loop(handle, 100, pcap_callback, (u_char *)dumper)) {
        fprintf(stderr, "pcap_loop: %s\n", pcap_geterr(handle));
    }//end if

    //flush and close
    pcap_dump_flush(dumper);
    pcap_dump_close(dumper);

    //free
    pcap_close(handle);

    return 0;
}

void pcap_callback(u_char *arg, const struct pcap_pkthdr *header, const u_char *content) {
    pcap_dumper_t *dumper = (pcap_dumper_t *)arg;

    //dump to file
    pcap_dump(arg, header, content);

    //flush
    pcap_dump_flush(dumper);
}

結果

libpcap % ./save_packet_to_file 
libpcap % ls packet.pcap 
packet.pcap

這個程式不會輸出任何結果,但是會在執行程式的目錄下產生packet.pcap檔案,裡面會有100個封包。

分析

    //open interface
    handle = pcap_open_live("en0", 65535, 1, 1, errbuf);
    if(!handle) {
        fprintf(stderr, "pcap_open_live: %s\n", errbuf);
        exit(1);
    }//end if

打開en0


    //open file handler
    dumper = pcap_dump_open(handle, "./packet.pcap");
    if(!dumper) {
        fprintf(stderr, "pcap_dump_open: %s\n", pcap_geterr(handle));
        pcap_close(handle);
        exit(1);
    }//end if

利用pcap_dump_open()打開一個處理檔案的handle,第二個參數表示說檔案儲存在哪。


    //start capture loop
    if(0 != pcap_loop(handle, 100, pcap_callback, (u_char *)dumper)) {
        fprintf(stderr, "pcap_loop: %s\n", pcap_geterr(handle));
    }//end if

這邊抓100個封包就好,第四個參數把檔案的handle傳入。


    //flush and close
    pcap_dump_flush(dumper);
    pcap_dump_close(dumper);

    //free
    pcap_close(handle);

抓完封包後,強迫把所有封包清入檔案,以及釋放資源。


void pcap_callback(u_char *arg, const struct pcap_pkthdr *header, const u_char *content) {
    pcap_dumper_t *dumper = (pcap_dumper_t *)arg;

    //dump to file
    pcap_dump(arg, header, content);

    //flush
    pcap_dump_flush(dumper);
}

使用pcap_dump()每個封包丟到檔案內(實際上先丟到buffer),每丟完封包就呼叫pcap_dump_flush()強迫把buffer內的封包丟到檔案內。

結語

libpcap可以將封包丟到檔案內,可再使用Wireshark做更進階的分析。

results matching ""

    No results matching ""