static int pcap_sink_open(struct rte_port_sink *port, const char *file_name, uint32_t max_n_pkts) { pcap_t *tx_pcap; pcap_dumper_t *pcap_dumper; /** Open a dead pcap handler for opening dumper file */ tx_pcap = pcap_open_dead(DLT_EN10MB, 65535); if (tx_pcap == NULL) { RTE_LOG(ERR, PORT, "Cannot open pcap dead handler\n"); return -1; } /* The dumper is created using the previous pcap_t reference */ pcap_dumper = pcap_dump_open(tx_pcap, file_name); if (pcap_dumper == NULL) { RTE_LOG(ERR, PORT, "Failed to open pcap file " "\"%s\" for writing\n", file_name); return -1; } port->dumper = pcap_dumper; port->max_pkts = max_n_pkts; port->pkt_index = 0; port->dump_finish = 0; RTE_LOG(INFO, PORT, "Ready to dump packets to file \"%s\"\n", file_name); return 0; }
static pcap_dumper_t* init_pcap_handler(const char *path) { pcap_t *handler; handler = pcap_open_dead(1, 65535); /* 不限制数据包的长度 */ return pcap_dump_open(handler, path); }
int royparse_start(logerr_t* a_logerr) { logerr = a_logerr; if (opt_q) { pcap = pcap_open_dead(DLT_RAW, 65535); q_out = pcap_dump_open(pcap, opt_q); if (q_out == 0) { logerr("%s: %s\n", opt_q, strerror(errno)); exit(1); } } if (opt_r) { r_out = fopen(opt_r, "w"); if (r_out == 0) { logerr("%s: %s\n", opt_r, strerror(errno)); exit(1); } } else { r_out = stdout; } setbuf(r_out, 0); return 0; }
void init_pcap(struct sniffed_packet * packet) { char ftime[256]; time_t rawtime; struct tm *timeinfo; time (&rawtime); timeinfo = localtime(&rawtime); strftime(ftime, sizeof(ftime), "%Y-%m-%d_%H_%M_%S", timeinfo); sprintf(fname, "dump_%s_RFPI_%.2x_%.2x_%.2x_%.2x_%.2x.pcap", ftime, cli.RFPI[0], cli.RFPI[1], cli.RFPI[2], cli.RFPI[3], cli.RFPI[4]); LOG("### dumping to %s\n", fname); cli.pcap = pcap_open_dead(DLT_EN10MB, 73); if (!cli.pcap) { LOG("!!! couldn't pcap_open_dead(\"%s\")\n", fname); } cli.pcap_d = pcap_dump_open(cli.pcap, fname); if (!cli.pcap_d) { LOG("!!! couldn't pcap_dump_open(\"%s\")\n", fname); } }
void PacketDumper::Init(const char *path){ char errbuf[PCAP_ERRBUF_SIZE]; memset(errbuf, 0, PCAP_ERRBUF_SIZE); if (nullptr != path && m_dumpname.empty()){ m_dumpname = std::string(path); } if (m_ifname.empty()){ NetIfManager netIfManager; const pcap_if_t *pcap_if = netIfManager.FindIfByIndex(2); //先写死了,后面需要修改 if (nullptr == pcap_if){ return; } m_ifname = pcap_if->name; } m_pcap_handle = pcap_open_live(m_ifname.c_str(), 65536, 1, 1000, errbuf); if (nullptr == m_pcap_handle){ LOG_ERROR("Unable to open the adapter. " << m_ifname <<" is not supported by WinPcap"); } m_pdumpfile = pcap_dump_open(m_pcap_handle, m_dumpname.c_str()); if (m_pdumpfile == nullptr) { LOG_ERROR("Error opening output file"); return; } }
void PacketDumper::openDump(time_t when, int sampling_rate, unsigned int max_pkts_per_file, unsigned int max_sec_per_file) { char pcap_path[MAX_PATH], hour_path[64]; int len; time_t _when = when; if(dumper) return; sec_start = when; this->sampling_rate = sampling_rate; this->max_pkts_per_file = iface->getDumpTrafficMaxPktsPerFile(); this->max_sec_per_file = iface->getDumpTrafficMaxSecPerFile(); when -= when % 3600; /* Hourly directories */ strftime(hour_path, sizeof(hour_path), "%Y/%m/%d/%H", localtime(&when)); snprintf(pcap_path, sizeof(pcap_path), "%s/%d/pcap/%s", ntop->get_working_dir(), iface->get_id(), hour_path); ntop->fixPath(pcap_path); Utils::mkdir_tree(pcap_path); len = strlen(pcap_path); snprintf(&pcap_path[len], sizeof(pcap_path)-len-1, "/%u_%u.pcap", (unsigned int)when, file_id); if((dumper = pcap_dump_open(pcap_open_dead(iface_type, 16384 /* MTU */), pcap_path)) == NULL) ntop->getTrace()->traceEvent(TRACE_WARNING, "Unable to create pcap file %s", pcap_path); else { dump_end = _when + this->max_sec_per_file, num_dumped_packets = 0, file_id++; ntop->getTrace()->traceEvent(TRACE_INFO, "Created pcap dump %s [max pkts=%u][max duration=%u sec]", \ pcap_path, this->max_pkts_per_file, this->max_sec_per_file); } }
int Generator::generatePackets(string inFileName, string outFileName) { pcap_t *p; pcap_dumper_t *out_file; int packetsSize, amount; if (!parseXmlAndCreateObjects(inFileName)) return 0; packetsSize = (int)packets.size(); p = pcap_open_dead(1, 65536); out_file = pcap_dump_open(p, outFileName.c_str()); for (int i = 0; i < packetsSize; i++) { amount = makeBytesVector(i); //funkcia vrati pocet, kolko ma byt podla xml vygenerovanych paketov (ch) bytesVector2BytesArray(); dumpToFile(p,out_file, amount); bytesVector.clear(); delete[] bytes; } return 1; }
bool SnoopDump::doOpen() { m_pcap = pcap_open_dead(linkType, snoop::DEFAULT_SNAPLEN); if (m_pcap == NULL) { SET_ERROR(SnoopError, "error in pcap_open_dead return NULL", VERR_IN_PCAP_OPEN_DEAD); return false; } if (filePath == "") { SET_ERROR(VFileError, "file name not specified", VERR_FILENAME_NOT_SPECIFIED); return false; } QString _path = QFileInfo(filePath).path(); QString _fileName = QFileInfo(filePath).fileName(); VFile::createFolder(_path); if (_fileName == "") _fileName = DEFAULT_DUMP_FILE_NAME; QDateTime now = QDateTime::currentDateTime(); QString newFileName = qformat(qPrintable(_fileName), now.date().year(), now.date().month(), now.date().day(), now.time().hour(), now.time().minute(), now.time().second(), now.time().msec()); m_pcap_dumper = pcap_dump_open(m_pcap, qPrintable(_path + "/" + newFileName)); if (m_pcap_dumper == NULL) { SET_ERROR(SnoopError, pcap_geterr(m_pcap), VERR_IN_PCAP_DUMP_OPEN); return false; } return true; }
bool GPcapFileWriter::doOpen() { if (fileName_ == "") { SET_ERR(GErr::FILE_NAME_NOT_SPECIFIED, "file name is not specified"); return false; } int dataLink = GPacket::dataLinkTypeToInt(dataLinkType_); pcap_ = pcap_open_dead(dataLink, snapLen_); if (pcap_ == nullptr) { SET_ERR(GErr::RETURN_NULL, QString("pcap_open_dead(%1, %2)) return null").arg(dataLink, snapLen_)); return false; } QString path = QFileInfo(fileName_).path(); QString fileName = QFileInfo(fileName_).fileName(); QDateTime now = QDateTime::currentDateTime(); QString newFileName = now.toString(fileName); if (path != "") { QDir dir; dir.mkpath(path); newFileName = path + QDir::separator() + newFileName; } pcap_dumper_ = pcap_dump_open(pcap_, qPrintable(newFileName)); if (pcap_dumper_ == nullptr) { SET_ERR(GErr::RETURN_NULL, QString("pcap_dump_open(, %1)) return null").arg(newFileName)); pcap_close(pcap_); pcap_ = nullptr; return false; } return true; }
int main(int argc,char *argv[]){ char *dev, errbuf[PCAP_ERRBUF_SIZE]; int i = 0; struct bpf_program filter; char filter_app[] = "src host 192.168.8.144 && arp "; bpf_u_int32 mask; bpf_u_int32 net; pcap_t *handle = NULL; pcap_dumper_t *pcap_dumper = NULL; dev = pcap_lookupdev(errbuf); if(dev == NULL){ fprintf(stderr,"couldn't find default device: %s\n",errbuf); return(2); } prjntf("Device: %s\n",dev); pcap_lookupnet(dev,&net,&mask,errbuf); handle = pcap_open_ljve(dev,BUFSIZ,1,0,errbuf); pcap_compjle(handle,&filter,filter_app,0,net); pcap_setfjlter(handle,&filter); pcap_dumper = pcap_dump_open(handle,"ljbcaptest1.pcap"); prjntf("%d*******\n",i); j = pcap_loop(handle,10,pcap_dump,(u_char *)pcap_dumper); pcap_dump_flush(pcap_dumper); pcap_dump_close(pcap_dumper); prjntf("%d*******\n",i); pcap_close(handle); return(0); }
static void dumper_too_many_open_files(struct shared_dumper **d) { struct session *elt; unsigned int oldest_ten_percent; oldest_ten_percent = sessions_count / 10; if (EMFILE == errno && oldest_ten_percent) { for (elt = first_session; NULL != elt; elt = elt->next) { if (NULL != elt->dumper->filedesc) { pcap_dump_close(elt->dumper->filedesc); elt->dumper->filedesc = NULL; --dumper_fd_count; if (!--oldest_ten_percent) break; } } (*d)->filedesc = pcap_dump_open(nids_params.pcap_desc, (*d)->filename); } if (NULL == (*d)->filedesc) { fprintf(stderr, "pcap_dump_open: %s: %s\n", (*d)->filename, pcap_geterr(nids_params.pcap_desc)); exit(-1); } }
main(int argc, char **argv) { struct uld *uld; struct sk_buff *skb; int i; pcap_t *p; pcap_dumper_t *pd; struct pcap_pkthdr ph; char *ifname; ifname = NULL; if (argc == 2) { ifname = argv[1]; } uld = uld_open(ifname, 0, 0, 0, 0); if (uld == NULL) exit(1); p = pcap_open_dead(DLT_EN10MB, 65535); if (!p) fprintf(stderr, "pcap_open_dead failed\n"); pd = pcap_dump_open(p, "-"); if (!pd) fprintf(stderr, "pcap_dump_open failed\n"); for(;;) { skb = uld_skb_read(uld, 1); if (skb == NULL) continue; ph.ts.tv_sec = skb->tstamp.tv_sec; ph.ts.tv_usec = skb->tstamp.tv_nsec/1000; ph.len = ph.caplen = skb->len; pcap_dump((void *)pd, &ph, skb->data); pcap_dump_flush(pd); skb_free(skb); } }
int init_write_pkts_to_files(const char* out_fpath) { /*create hashtable*/ flow_seqid_hashmap = ht_kf_create(HASH_MAP_SIZE); if (flow_seqid_hashmap == NULL) { printf("FAIL: ht_kf_create flow_seqid_hashmap\n"); return -1; } int node_idx = 0; for (node_idx = 0; node_idx < NUM_SENDERS; ++node_idx) { pd[node_idx] = pcap_open_dead(DLT_EN10MB, 65535 /* snaplen */); if (pd[node_idx] == NULL) { return -1; } /* Create the output file. */ char fname[100]; snprintf(fname, 100, "%s/h%d.pcap", out_fpath, node_idx+1); pdumper[node_idx] = pcap_dump_open(pd[node_idx], fname); if (pdumper[node_idx] == NULL) { return -1; } snprintf(fname, 100, "%s/h%d_trace.csv", out_fpath, node_idx+1); fp[node_idx] = fopen(fname, "w"); if (fp[node_idx] == NULL) { return -1; } } return 0; }
int main(int argc, char *argv[]) { char errbuf[PCAP_ERRBUF_SIZE]; if (argc < 3) { std::cerr << "usage: in.pcap out.pcap" << std::endl; return -1; } char *file_in = argv[1], *file_out = argv[2]; std::cout << "pfq_test: opening " << file_in << " for reading..." << std::endl; in = pcap_open_offline(file_in, errbuf); if (in == nullptr) throw std::runtime_error(errbuf); out = pcap_dump_open(in, file_out); if (out == nullptr) throw std::runtime_error(errbuf); std::cout << "rewriting packets to " << file_out << ':' << std::endl; if (pcap_loop(in, 0, handler, 0) < 0) throw std::runtime_error(pcap_geterr(in)); std::cout << counter << " IP packets written." << std::endl; return 0; }
static void dump_frame(u_char *data, int len, struct shared_dumper *output) { u_char *frame; struct pcap_pkthdr ph; if (!bonus_time && NULL == output) return; frame = malloc(len + nids_linkoffset); memcpy(frame, nids_last_pcap_data, nids_linkoffset); memcpy(frame + nids_linkoffset, data, len); ph.ts = nids_last_pcap_header->ts; ph.caplen = ph.len = len + nids_linkoffset; if (NULL != output) { if (NULL == output->filedesc) { output->filedesc = pcap_dump_open(nids_params.pcap_desc, output->filename); if (NULL == output->filedesc) dumper_too_many_open_files(&output); ++dumper_fd_count; } pcap_dump((u_char *)output->filedesc, &ph, frame); } if (bonus_time) pcap_dump((u_char *)global_dumper, &ph, frame); free(frame); }
/* * capture packet function */ void packet_capture() { pcap_t *handle; char error_content[PCAP_ERRBUF_SIZE]; struct bpf_program bpf_filter; bpf_u_int32 net_mask; bpf_u_int32 net_ip; pcap_lookupnet(select_dev, &net_ip, &net_mask, error_content); handle = pcap_open_live(select_dev, BUFSIZ, 1, 0, error_content); pcap_compile(handle, &bpf_filter, bpf_filter_str, 0, net_ip); pcap_setfilter(handle, &bpf_filter); if (pcap_datalink(handle) != DLT_EN10MB) return; /*initial all the statistics number */ arpn = icmpn = udpn = tcpn = ipn = alln = 0; /*open dump file */ pcapfp = pcap_dump_open(handle, DUMPFILE); /* capture pkt loop */ pcap_loop(handle, -1, ether_callback, NULL); pcap_close(handle); }
/* Open any requested output files */ void open_outfiles() { /* Redirect stdout to the specified output file if requested */ if (use_outfile) { if (daemon_mode && (use_outfile[0] != '/')) LOG_WARN("Output file path is not absolute and may be inaccessible after daemonizing"); if (freopen(use_outfile, "a", stdout) == NULL) LOG_DIE("Cannot reopen output stream to '%s'", use_outfile); PRINT("Writing output to file: %s", use_outfile); printf("# %s version %s\n", PROG_NAME, PROG_VER); print_format_list(); } /* Open pcap binary capture file if requested */ if (use_dumpfile) { if (daemon_mode && (use_dumpfile[0] != '/')) LOG_WARN("Binary capture file path is not absolute and may be inaccessible after daemonizing"); if ((dumpfile = pcap_dump_open(pcap_hnd, use_dumpfile)) == NULL) LOG_DIE("Cannot open binary dump file '%s'", use_dumpfile); PRINT("Writing binary dump file: %s", use_dumpfile); } return; }
int pcap_io_init(char *adapter) { printf("WINPCAP: Opening adapter '%s'...",adapter); GetMACaddress(adapter,&host_mac); /* Open the adapter */ if ((adhandle= pcap_open_live(adapter, // name of the device 65536, // portion of the packet to capture. // 65536 grants that the whole packet will be captured on all the MACs. 1, // promiscuous mode (nonzero means promiscuous) 1, // read timeout errbuf // error buffer )) == NULL) { printf("\nWINPCAP: Unable to open the adapter. %s is not supported by WinPcap\n", adapter); return -1; } /* if(pcap_setnonblock(adhandle,1,errbuf)==-1) { printf("WINPCAP: Error setting non-blocking mode. Default mode will be used.\n"); } */ packet_log=fopen("logs/packet.log","w"); dump_pcap = pcap_dump_open(adhandle,"logs/pkt_log.pcap"); CreateThread(0,0,rx_thread,0,0,0); pcap_io_running=1; printf("WINPCAP: Ok.\n"); return 0; }
int main(int argc, char **argv) { //Check whether user has entered enough arguments if(argc < 2) { printf("Usage: ./firewall mode [input pcap file] [output pcap file]\n", " Mode: 1/2\n"); } char errbuf[100]; int mode = atoi(argv[1]); //If mode = 1 then use the interfaces to capture packets if(mode == 1) { pid_t childPID; //Open the interface handlers in_handle = pcap_open_live(INT_IN,65536,1,0,errbuf); out_handle = pcap_open_live(INT_OUT,65536,1,0,errbuf); //Create two processes for two interfaces childPID = fork(); if(childPID >= 0) { //Associate the handlers with the interfaces if(childPID == 0) { capture_loop(in_handle, -1, (pcap_handler)parse_packet, NULL); } else { capture_loop(out_handle, -1, (pcap_handler)parse_packet_p, NULL); } } else { printf("\n Fork failed, quitting!!!!!!\n"); return 1; } } //Else open the input pcap file for the processing and write to output pcap file else { //Check for the valid arguments if(argc < 4) { printf("Usage: ./firewall mode [input pcap file] [output pcap file]\n", " Mode: 1/2\n"); } in_handle = pcap_open_offline(argv[2],errbuf); //802.3 = 1 - link type //open new pcap handler out_handle = pcap_open_dead(1,65536); //open the file with the handler dumper = pcap_dump_open(out_handle, argv[3]); //Process all the packets from the file capture_loop(in_handle, -1, (pcap_handler)parse_packet_file, (u_char*)dumper); } return 0; }
int main(int argc, char *argv[]) { if(argc < 2) { printf("Usage: %s -i interface -f file\n", argv[0]); return (1); } int opt; while((opt = getopt(argc, argv, ":i:f:h")) != -1) { switch(opt) { case 'h': printf("Usage: %s -i interface -f file\n", argv[0]); return (1); case 'i': interface = optarg; break; case 'f': file = optarg; break; default: /* '?' */ printf("Usage: %s -i interface -f file\n", argv[0]); return (1); } } if(interface == NULL) { printf("Usage: %s -i interface -f file\n", argv[0]); return (1); } else if(file == NULL) { file = "trace.pcap"; } printf("Beginning capturing...\n"); char errbuf[PCAP_ERRBUF_SIZE]; memset(errbuf, 0, PCAP_ERRBUF_SIZE); pcap_t *cap = NULL; struct pcap_pkthdr pkthdr; cap = pcap_open_live(interface, 65535, 0, 1000, errbuf); if( cap == NULL) { printf("%s\r",errbuf); exit(1); } pcap_dumper_t* dumper; dumper = pcap_dump_open(cap, file); pcap_loop(cap, -1, proc_pkt, dumper); pcap_dump_close(dumper); pcap_close(cap); return 0; }
void open_logs() { if (pcap_filename.length()) { close_pcap_dump(); pcap_writer = pcap_dump_open(pcap, pcap_filename.c_str()); std::cerr << "writing pcap header to " << pcap_filename << std::endl; } }
PhysicalMedium_pimpl(clockid_t clockidToUse, const char * nameIn, int mcastPort) : clockidToUse(clockidToUse) { struct epoll_event ev; int rv; u_char loop; tx.mcastsockfd = -1; ev.events = EPOLLIN; ev.data.ptr = &NetworkSimulator::getUnblocker(); state = STOPPED; name = strdup(nameIn); poller.epfd = epoll_create1(EPOLL_CLOEXEC); thread = -1; if (poller.epfd < 0) throw "epoll_create error"; rv = epoll_ctl(poller.epfd, EPOLL_CTL_ADD, NetworkSimulator::getUnblocker().getReadPipe(), &ev); if (rv < 0) throw "PhysicalMedium_pimpl: failed to add unblocker to poller"; /* * SIGEV_NONE is supposed to prevent signal delivery, but it doesn't. * Set signo to SIGSTOP to make the received signal obvious but * harmless. */ memset(&sev, 0, sizeof(sev)); sev.sigev_notify = SIGEV_NONE; sev.sigev_signo = SIGSTOP; if (timer_create(clockidToUse, &sev, &timer) == -1) { xlog(LOG_ERR, "timer_create fail (%d:%s)", errno, strerror(errno)); throw "PhysicalMedium_pimpl: failed to create timer"; } // Create multicast socket and disable loopback as we don't want // to receive the packets we have just transmitted. tx.mcastsockfd=socket(AF_INET, SOCK_DGRAM, 0); tx.mcastport = mcastPort; // Ensure IP_MULTICAST_LOOP is set so QEMU nodes that are // running locally can receive the multicast packet. loop = 1; setsockopt(tx.mcastsockfd, IPPROTO_IP, IP_MULTICAST_LOOP, &loop, sizeof(loop)); bzero(&tx.mcastGroupAddr,sizeof(tx.mcastGroupAddr)); tx.mcastGroupAddr.sin_family = AF_INET; tx.mcastGroupAddr.sin_addr.s_addr=inet_addr("224.1.1.1"); tx.mcastGroupAddr.sin_port=htons(tx.mcastport); memset(&stats, 0, sizeof(stats)); pcap.fake = pcap_open_dead(DLT_IEEE802_15_4_NOFCS, 65535); assert(pcap.fake); pcap.dumper = pcap_dump_open(pcap.fake, "./packets.pcap"); assert(pcap.dumper); }
pcap_dumper_t * dump_open(const char *dumpfile) { capture_info_t *capinfo; if (vector_count(capture_cfg.sources) == 1) { capinfo = vector_first(capture_cfg.sources); return pcap_dump_open(capinfo->handle, dumpfile); } return NULL; }
void PacketWriter::init(const std::string& file_name, int link_type) { handle = pcap_open_dead(link_type, 65535); if(!handle) throw std::runtime_error("Error creating pcap handle"); dumper = pcap_dump_open(handle, file_name.c_str()); if(!dumper) { // RAII plx pcap_close(handle); throw std::runtime_error(pcap_geterr(handle)); } }
/* Setup filter resources */ static int pf_capture_setup(netio_desc_t *nio,void **opt, int argc,char *argv[]) { struct netio_filter_capture *c; int link_type; /* We must have a link type and a filename */ if (argc != 2) return(-1); /* Free resources if something has already been done */ pf_capture_free(nio,opt); /* Allocate structure to hold PCAP info */ if (!(c = malloc(sizeof(*c)))) return(-1); if (pthread_mutex_init(&c->lock,NULL)) { fprintf(stderr,"NIO %s: pthread_mutex_init failure (file %s)\n", nio->name,argv[0]); goto pcap_lock_err; } if ((link_type = pcap_datalink_name_to_val(argv[0])) == -1) { fprintf(stderr,"NIO %s: unknown link type %s, assuming Ethernet.\n", nio->name,argv[0]); link_type = DLT_EN10MB; } /* Open a dead pcap descriptor */ if (!(c->desc = pcap_open_dead(link_type,8192))) { fprintf(stderr,"NIO %s: pcap_open_dead failure\n",nio->name); goto pcap_open_err; } /* Open the output file */ if (!(c->dumper = pcap_dump_open(c->desc,argv[1]))) { fprintf(stderr,"NIO %s: pcap_dump_open failure (file %s)\n", nio->name,argv[0]); goto pcap_dump_err; } printf("NIO %s: capturing to file '%s'\n",nio->name,argv[1]); *opt = c; return(0); pcap_dump_err: pcap_close(c->desc); pcap_open_err: pthread_mutex_destroy(&c->lock); pcap_lock_err: free(c); return(-1); }
PcapFileOut::PcapFileOut(unsigned port, std::string filename) : PcapFileBase(port, filename) { pcap = pcap_open_dead(0, 0); if (pcap == nullptr) bm_fatal_error( std::string("Could not open file ") + filename + " for writing"); dumper = pcap_dump_open(pcap, filename.c_str()); if (dumper == nullptr) bm_fatal_error( std::string("Could not open file ") + filename + " for writing"); }
void PCAPExporterModule::performStart() { char errbuf[PCAP_ERRBUF_SIZE]; dummy = pcap_open_dead(link_type, snaplen); if (!dummy) { THROWEXCEPTION("Could not open dummy device: %s", errbuf); } dumper = pcap_dump_open(dummy, fileName.c_str()); if (!dumper) { THROWEXCEPTION("Could not open dump file: %s", errbuf); } }
int main(int argc, char *argv[]){ char errbuf[PCAP_ERRBUF_SIZE], *device="any",*output_filename="/tmp/test.dump",*filter; const char *tmp; struct bpf_program fcode; int count=0; int timer=10; int c; poptContext context; struct poptOption optionsTable[] = { {"output", 'o', POPT_ARG_STRING, &output_filename, 'o'}, {"count", 'c', POPT_ARG_INT, &count, 'c'}, {"time", 't', POPT_ARG_INT, &timer, 't'}, {NULL,0,0,NULL,0} }; context = poptGetContext(NULL, argc, (const char **) argv, optionsTable, 0); poptSetOtherOptionHelp(context, "<tcpdump filter>"); while (poptGetNextOpt(context) >= 0) {} filter = (char *)malloc(256); strcpy (filter,""); while ((tmp = poptGetArg(context))!=NULL) { if (strcmp(filter,"")) filter = strcat(filter," "); filter = strcat(filter,tmp); } if (strcmp(filter,"")==0) filter = "port 3306"; poptFreeContext(context); printf("file=%s, count=%d, time=%d, filter=%s\n",output_filename,count,timer,filter); signal(SIGTERM, cleanup); signal(SIGALRM, cleanup); signal(SIGINT, cleanup); memset(errbuf,0,PCAP_ERRBUF_SIZE); descr = pcap_open_live(device,BUFSIZ,0,100,errbuf); if (descr == NULL) { fprintf(stderr, "Couldn't open device %s: %s\n", device, errbuf); return(2); } if (pcap_compile(descr, &fcode, filter, 0, 0) < 0){ fprintf(stderr,"can not analyze filter:%s\n", filter); exit(1); } if (pcap_setfilter(descr,&fcode) == -1) { fprintf(stderr, "filter can not use: %s\n", filter); exit(1); } dumper = pcap_dump_open(descr,output_filename); alarm(timer); pcap_loop(descr,count,write_captured_packet,NULL); pcap_close(descr); pcap_dump_close(dumper); exit(0); }
void CaptureData(std::string captureFolder, std::string interface) { LOG(DEBUG, "Starting data capture. Storing results in folder:" + captureFolder, ""); boost::filesystem::path create = captureFolder; try { boost::filesystem::create_directory(create); } catch(boost::filesystem::filesystem_error const& e) { LOG(DEBUG, ("Problem creating directory " + captureFolder), ("Problem creating directory " + captureFolder + ": " + e.what())); } // Write out the state of the haystack at capture if(IsHaystackUp()) { LOG(DEBUG, "Haystack appears up. Recording current state.", ""); string haystackFile = captureFolder + "/haystackIps.txt"; haystackAddresses = Config::GetHaystackAddresses(Config::Inst()->GetPathHome() + "/" + Config::Inst()->GetPathConfigHoneydHS()); haystackDhcpAddresses = Config::GetHoneydIpAddresses(Config::Inst()->GetIpListPath()); LOG(DEBUG, "Writing haystack IPs to file " + haystackFile, ""); ofstream haystackIpStream(haystackFile); for(uint i = 0; i < haystackDhcpAddresses.size(); i++) { LOG(DEBUG, "Found haystack DHCP IP " + haystackDhcpAddresses.at(i).ip, ""); haystackIpStream << haystackDhcpAddresses.at(i).ip << endl; } for(uint i = 0; i < haystackAddresses.size(); i++) { LOG(DEBUG, "Found haystack static IP " + haystackAddresses.at(i).ip, ""); haystackIpStream << haystackAddresses.at(i).ip << endl; } haystackIpStream.close(); } // Prepare for packet capture string trainingCapFile = captureFolder + "/capture.pcap"; InterfacePacketCapture *capture = new InterfacePacketCapture(interface); capture->Init(); capture->SetPacketCb(SavePacket); pcap_t *handle = capture->GetPcapHandle(); pcap_activate(handle); pcapDumpStream = pcap_dump_open(handle, trainingCapFile.c_str()); capture->StartCaptureBlocking(); }
static struct shared_dumper *dumper_open(enum type t, uint32_t id) { struct shared_dumper *d; d = malloc(sizeof (struct shared_dumper)); d->filename = malloc(strlen(sessions_file_format) + strlen(type2string(t, 0)) + 16); sprintf(d->filename, sessions_file_format, type2string(t, 0), id); d->filedesc = pcap_dump_open(nids_params.pcap_desc, d->filename); if (NULL == d->filedesc) dumper_too_many_open_files(&d); ++dumper_fd_count; d->references = 1; return d; }