Emsniffer(还没完成,正在做)

来源:互联网 发布:微博短文情感数据集 编辑:程序博客网 时间:2024/04/28 19:58

Emsniffer作用如下,能够抓包并存到文件里(实现);存储包文件的大小能够设定(为实现现阶段)。

源码如下,有相关需求的同志们共同学习,如果可以的话,提出建议更好。

 

/**********************************************************************
* file: emsniffer.c
* date: 2010,7,19
* Author: yujiliang
* Last Modified:2010,7,21 ,yujiliang
*
* To sniffer all the packets from a Network Interface Card, and save them
* to a file.
* Use libpcap 0.5.2 or version after
**********************************************************************/
#include <pcap.h>
#include <stdio.h>
#include <stdlib.h>
#include <signal.h> 
#include <sys/stat.h>
#include <string.h>

#define NIC_NAME "eth0"  /* the NIC to grab */
char errbuf[PCAP_ERRBUF_SIZE]; /* for writting pcap error */
pcap_t * descr;        /* pointer to NIC */
pcap_dumper_t * p;     /* pointer to pcap dump file for writing */
char filepath[20];  /* file for save dump packets */

 struct stat dumpfile_info;

/* do this after press Ctrl-c or some other reasons cause program to stop */
void cleanup()
{
  
    /* Close the pcap device */
    pcap_close(descr);
  
    /* close dump file */
    pcap_dump_close(p);

    stat(filepath, &dumpfile_info);   /* compute dumpfile's size */

    printf("Dumpfile's size is %d kbytes/n", dumpfile_info.st_size);
  
    fprintf(stderr,"dump over/n");
  
    exit( 0 );
}

/* sniffer & save packets to dumpfile */
void emsniffer(char *dump_file_path, int limit_storage_space) /* limit_storage kbytes function not OK yet */
{
 /* find the WAN NIC device */
    /* open device for reading and set it in promiscuous mode */
    descr = pcap_open_live(NIC_NAME ,BUFSIZ,1,-1,errbuf);
    if(descr == NULL)
    {
 fprintf(stderr,"pcap_open_live(): %s/n",errbuf); exit(1);
    }
   
    /* exit & close dumpfile & left promiscuous mode when got ctrl-c */
    signal(SIGTERM, cleanup);
    signal(SIGINT, cleanup);
    signal(SIGQUIT, cleanup);
    signal(SIGABRT, cleanup);

    /* open the dumpfile for writting packets */
    p = pcap_dump_open(descr, dump_file_path);
    if (p == NULL)
    {
 fprintf(stderr,"pcap_dump_open: %s", pcap_geterr(descr)); exit(1);
    }
   
 fprintf(stderr,"dump packets begin/n");

    /* write all the packets into the dumpfile until press ctrl-c */ /*HAVE BETTER SOLUTION ,TIME NEEDED */
    if(pcap_loop(descr, -1, pcap_dump, (u_char *)p) < 0)
    {
 fprintf(stderr,"pcap_loop: %s", pcap_geterr(descr)); exit(1);
    }
}


int main(int argc, char* argv[]) /* ./emsniffer  [dump_file_path]  [limit_storage_space]  */
{
   
       int limitstoragespace;     
       strcpy(filepath,argv[1]);
    limitstoragespace = atoi(argv[2]);
       emsniffer(filepath,limitstoragespace);
       return 0;
}

 

以后limit_storage_space的功能做好会加上。

原创粉丝点击