使用libcap实现抓包 并保存为wireshark格式(linux环境)

代码只有一个简单的骨架。 是我最近做一个项目时,用来自测的小工具。
做得很简陋,需要的自己拿去改改。

#include 
#include 
#include 

#include 
#include 
#include 

#define MAXLINE 65535
#define DO_PROMISC 1

pcap_dumper_t *dumper = NULL;
char* savename = NULL;
void printPacket(u_char *agrs, const struct pcap_pkthdr *header, const u_char *packet);

void openFile(const char *fname)
{
    dumper = pcap_dump_open(pcap_open_dead(DLT_EN10MB, 1600), fname);
    if (NULL == dumper)
    {
        printf("dumper is NULL\n");
        return;
    }
}

void dumpFile(const u_char *pkt, int len, time_t tv_sec, suseconds_t tv_usec)
{
    if (NULL == dumper)
    {
        openFile(savename);
    }
    
    struct pcap_pkthdr hdr;
    hdr.ts.tv_sec = tv_sec;
    hdr.ts.tv_usec = tv_usec;
    hdr.caplen = len;
    hdr.len = len; 
    
    pcap_dump((u_char*)dumper, &hdr, pkt); 
    pcap_dump_flush(dumper);  
}

int main(int argc, char *argv[])
{
    char errBuf[PCAP_ERRBUF_SIZE], *devstr;
    pcap_t *fd;
    
    if (argc <= 2)
    {
        printf("arg1 device name, arg2 save file name\n");
        return -1;
    }
    savename = argv[2];
    
    fd = pcap_open_live(argv[1], MAXLINE, DO_PROMISC, 0, errBuf);
    unsigned int id = 0;
    while(1)
    {
        pcap_loop(fd, -1, printPacket, (u_char *)&id);
    }
    
    perror("pcap_loop:");
    pcap_close(fd);
    return 0;
}


void printPacket(u_char *agrs, const struct pcap_pkthdr *header, const u_char *packet)
{
    unsigned int *pk;
    pk = (unsigned int*)agrs;
    printf("id \t=%d\n", ++(*pk));
    printf("caplen \t= %d\n", header->caplen);
    
    dumpFile(packet, header->caplen, header->ts.tv_sec, header->ts.tv_usec);
}

你可能感兴趣的:(使用libcap实现抓包 并保存为wireshark格式(linux环境))