int PcapReader::open(const string& file_path) { char err_str[PCAP_ERRBUF_SIZE]; if (m_handle) { m_error = "Pcap file already open"; return -1; } m_handle = pcap_open_offline_with_tstamp_precision(file_path.c_str(), PCAP_TSTAMP_PRECISION_NANO, err_str); if (!m_handle) { m_error = "Failed to open pcap file"; return -1; } m_file_beg = ftell(pcap_file(m_handle)); fseek(pcap_file(m_handle), 0, SEEK_END); m_file_end = ftell(pcap_file(m_handle)); fseek(pcap_file(m_handle), m_file_beg, SEEK_SET); return 0; }
nmsg_pcap_t nmsg_pcap_input_open(pcap_t *phandle) { struct nmsg_pcap *pcap; pcap = calloc(1, sizeof(*pcap)); if (pcap == NULL) return (NULL); pcap->handle = phandle; pcap->datalink = pcap_datalink(phandle); pcap->new_pkt = calloc(1, NMSG_IPSZ_MAX); pcap->reasm = reasm_ip_new(); if (pcap->reasm == NULL) { free(pcap->new_pkt); free(pcap); return (NULL); } reasm_ip_set_timeout(pcap->reasm, 60); if (pcap_file(phandle) == NULL) pcap->type = nmsg_pcap_type_live; else pcap->type = nmsg_pcap_type_file; return (pcap); }
/* routine is executed on exit */ void program_ending(int signo) { struct pcap_stat stat; if (pd != NULL && pcap_file(pd) == NULL) { (void)fflush(stdout); putc('\n', stderr); if (pcap_stats(pd, &stat) < 0) (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd)); else { (void)fprintf(stderr, "%d packets received by filter\n", stat.ps_recv); (void)fprintf(stderr, "%d packets dropped by kernel\n", stat.ps_drop); } } printf("\n"); printf("ip packet count = %d\n", ip_packet_count); printf("arp packet count = %d\n", arp_packet_count); printf("icmp packet count = %d\n", icmp_packet_count) printf("broadcast packet count = %d\n", broadcast_packet_count); exit(0); }
static mrb_value capture(mrb_state *mrb, mrb_value self) { struct capture_object *cap; int nfd; cap = (struct capture_object *)mrb_get_datatype(mrb, self, &mrb_pcap_type); cap->mrb = mrb; if (pcap_file(cap->pcap) != NULL) { mrb_raise(mrb, E_RUNTIME_ERROR, "pcap file not supported"); } else { int fd = pcap_fileno(cap->pcap); fd_set rset; FD_ZERO(&rset); do { FD_SET(fd, &rset); nfd = select(fd+1, &rset, NULL, NULL, NULL); if (nfd != 0) { pcap_dispatch(cap->pcap, 1, handler, (u_char *)cap); break; } else { continue; } } while (1); } return cap->cap_data; }
void reader_libpcapfile_opened() { int dlt_to_linktype(int dlt); pcapFileHeader.linktype = dlt_to_linktype(pcap_datalink(pcap)) | pcap_datalink_ext(pcap); pcapFileHeader.snaplen = pcap_snapshot(pcap); offlineFile = pcap_file(pcap); if (config.bpf) { struct bpf_program bpf; if (pcap_compile(pcap, &bpf, config.bpf, 1, PCAP_NETMASK_UNKNOWN) == -1) { LOG("ERROR - Couldn't compile filter: '%s' with %s", config.bpf, pcap_geterr(pcap)); exit(1); } if (pcap_setfilter(pcap, &bpf) == -1) { LOG("ERROR - Couldn't set filter: '%s' with %s", config.bpf, pcap_geterr(pcap)); exit(1); } } int t; for (t = 0; t < MOLOCH_FILTER_MAX; t++) { if (config.bpfsNum[t]) { int i; if (bpf_programs[t]) { for (i = 0; i < config.bpfsNum[t]; i++) { pcap_freecode(&bpf_programs[t][i]); } } else { bpf_programs[t] = malloc(config.bpfsNum[t]*sizeof(struct bpf_program)); } for (i = 0; i < config.bpfsNum[t]; i++) { if (pcap_compile(pcap, &bpf_programs[t][i], config.bpfs[t][i], 1, PCAP_NETMASK_UNKNOWN) == -1) { LOG("ERROR - Couldn't compile filter: '%s' with %s", config.bpfs[t][i], pcap_geterr(pcap)); exit(1); } } moloch_reader_should_filter = reader_libpcapfile_should_filter; } } if (config.flushBetween) moloch_session_flush(); offlinePcapName = strdup(offlinePcapFilename); int fd = pcap_fileno(pcap); if (fd == -1) { g_timeout_add(0, reader_libpcapfile_read, NULL); } else { moloch_watch_fd(fd, MOLOCH_GIO_READ_COND, reader_libpcapfile_read, NULL); } }
GThreadFunc barra_de_progreso(){ FILE *pcap = NULL; while(running && nids_params.pcap_desc != NULL){ pcap = pcap_file(nids_params.pcap_desc); if(pcap == 0) break; pcap_position = ftell(pcap); if(pcap_position == -1L) break; loadBar(pcap_position, pcap_size, pcap_size, 40); usleep(500000); } return NULL; }
int pcap_ex_fileno(pcap_t *pcap) { #ifdef _WIN32 /* XXX - how to handle savefiles? */ return ((int)pcap_getevent(pcap)); #else FILE *f = pcap_file(pcap); if (f != NULL) return (fileno(f)); return (pcap_fileno(pcap)); #endif /* !_WIN32 */ }
int main(int argc, char *argv[]) { bpf_u_int32 netaddr=0, mask=0; struct bpf_program filter; pcap_t *descr = NULL; struct pcap_pkthdr pkthdr; const unsigned char *packet = NULL; struct ip *ipptr = NULL; struct tcphdr *tcpptr = NULL; if (argc < 2 || argc > 3 || (argv[1][0] == '-' && argv[1][1] == 'h')){ printf("Usage: tcpsniffer <interface> | tcpsniffer -f <dumpfile>\n"); exit(1); } if (argc == 2) { descr = Pcap_open_live(argv[1], MAXBYTES2CAPTURE, 1, 512); Pcap_lookupnet(argv[1], &netaddr, &mask); } else { // argc == 3 descr = Pcap_open_offline(argv[2]); } Pcap_compile(descr, &filter, "tcp", 1, mask); Pcap_setfilter(descr, &filter); while (1){ packet = Pcap_next(descr, &pkthdr); if (packet == NULL) { if (pcap_file(descr) != NULL) { printf("\nend of dumpfile!\n"); } else { printf("\n loop was broken out of with pcap_breakloop!\n"); } exit(1); } ipptr = (struct ip *)(packet + 14); printf("\n\nReceived Packet Size: %d bytes\n", pkthdr.len); printf("\n\nthe IP packets version: %d\n", ipptr->ip_v); printf ("the IP packets total_length is :%d\n", ntohs(ipptr->ip_len)); printf ("the IP protocol is %d\n", ipptr->ip_p); printf ("Destination IP: %s\n", inet_ntoa(ipptr->ip_dst)); printf ("Source IP: %s\n", inet_ntoa(ipptr->ip_src)); tcpptr = (struct tcphdr *) (packet + 14 + ipptr->ip_hl*4); printf ("Destination port : %d\n", ntohs(tcpptr->th_dport)); printf ("Source port : %d\n", ntohs(tcpptr->th_sport)); printf ("the seq of packet is %u\n", ntohl(tcpptr->th_seq)); } return 0; }
/* return codes: 1 = pkt, 0 = timeout, -1 = error, -2 = EOF */ int pcap_ex_next(pcap_t *pcap, struct pcap_pkthdr **hdr, u_char **pkt) { #ifdef _WIN32 if (__pcap_ex_gotsig) { __pcap_ex_gotsig = 0; return (-1); } return (pcap_next_ex(pcap, hdr, pkt)); #else static u_char *__pkt; static struct pcap_pkthdr __hdr; struct timeval tv = { 1, 0 }; fd_set rfds; int fd, n; fd = pcap_fileno(pcap); for (;;) { if (__pcap_ex_gotsig) { __pcap_ex_gotsig = 0; return (-1); } if ((__pkt = (u_char *) pcap_next(pcap, &__hdr)) == NULL ) { #ifdef HAVE_PCAP_FILE if (pcap_file(pcap) != NULL) #else if (pcap->sf.rfile != NULL ) #endif return (-2); FD_ZERO(&rfds); FD_SET(fd, &rfds); n = select(fd + 1, &rfds, NULL, NULL, &tv); if (n <= 0) return (n); } else break; } *pkt = __pkt; *hdr = &__hdr; return (1); #endif }
static void pcap_init(int type, char *data, char *host) { char *filter = NULL; pcap_t *handle = NULL; struct bpf_program fp; char errbuf[PCAP_ERRBUF_SIZE]; g_return_if_fail(data != NULL); g_return_if_fail(host != NULL); if(type == LIVE) { handle = pcap_open_live(data, SNAP_LEN, 1, 1000, errbuf); if (handle == NULL) { fprintf(stderr, "Falha ao abrir device %s: %s\n", data, errbuf); return; } } else { handle = pcap_open_offline(data, errbuf); if(handle == NULL) { fprintf(stderr, "Falha: %s\n", errbuf); return; } pcap_file(handle); } if(strlen(host) > 1) { filter = g_strdup_printf("port 80 and host %s", host); } else { filter = g_strdup_printf("port 80"); } if (pcap_compile(handle, &fp, filter, 0, 0) == -1) { fprintf(stderr, "Falha ao compilar filtro %s: %s\n", filter, pcap_geterr(handle)); return; } if (pcap_setfilter(handle, &fp) == -1) { fprintf(stderr, "Falha ao utilizar filtro %s: %s\n", filter, pcap_geterr(handle)); return; } pcap_loop(handle, -1, packet_analyze, NULL); pcap_freecode(&fp); pcap_close(handle); }
/* return codes: 1 = pkt, 0 = timeout, -1 = error, -2 = EOF */ int pcap_ex_next(pcap_t *pcap, struct pcap_pkthdr *hdr, u_char **pkt) { #ifdef _WIN32 struct pcap_pkthdr *hdrp; int ret; if (__pcap_ex_gotsig) { __pcap_ex_gotsig = 0; return (-1); } ret = pcap_next_ex(pcap, &hdrp, pkt); if (hdrp && hdr) *hdr = *hdrp; return ret; #else static u_char *__pkt; struct timeval tv = { 1, 0 }; fd_set rfds; int fd, n; fd = pcap_fileno(pcap); for (;;) { if (__pcap_ex_gotsig) { __pcap_ex_gotsig = 0; return (-1); } if ((__pkt = (u_char *)pcap_next(pcap, hdr)) == NULL) { if (pcap_file(pcap) != NULL) return (-2); FD_ZERO(&rfds); FD_SET(fd, &rfds); n = select(fd + 1, &rfds, NULL, NULL, &tv); if (n <= 0) return (n); } else break; } *pkt = __pkt; return (1); #endif }
/* make a clean exit on interrupts */ RETSIGTYPE cleanup(int signo) { struct pcap_stat stat; /* Can't print the summary if reading from a savefile */ if (pd != NULL && pcap_file(pd) == NULL) { (void)fflush(stdout); putc('\n', stderr); if (pcap_stats(pd, &stat) < 0) (void)fprintf(stderr, "pcap_stats: %s\n", pcap_geterr(pd)); else { (void)fprintf(stderr, "%d packets received by filter\n", stat.ps_recv); (void)fprintf(stderr, "%d packets dropped by kernel\n", stat.ps_drop); } } exit(0); }
int pcap_next_ex(pcap_t *p, struct pcap_pkthdr **pkt_header, const u_char **pkt_data) { int pcapbytes = 0; pcap_data.header = *pkt_header; pcap_data.payload = *pkt_data; pcapbytes = pcap_dispatch(p, 1, &trace_pcap_handler, (u_char *) &pcap_data); if (pcapbytes == -1) return -1; if (pcapbytes == 0 && pcap_file(p) != NULL) return -2; if (pcapbytes == 0) return 0; return 1; }
void ec_decode(u_char *param, const struct pcap_pkthdr *pkthdr, const u_char *pkt) { FUNC_DECODER_PTR(packet_decoder); struct packet_object po; u_int len; u_char *data; u_int datalen; struct iface_env *iface; iface = (struct iface_env *)param; CANCELLATION_POINT(); /* start the timer for the stats */ stats_half_start(&GBL_STATS->bh); /* XXX -- remove this */ #if 0 if (!GBL_OPTIONS->quiet) USER_MSG("CAPTURED: 0x%04x bytes form %s\n", pkthdr->caplen, iface->name ); #endif if (GBL_OPTIONS->read) /* update the offset pointer */ GBL_PCAP->dump_off = ftell(pcap_file(GBL_IFACE->pcap)); else { /* update the statistics */ stats_update(); } /* * dump packet to file if specified on command line * it dumps all the packets disregarding the filter * * do not perform the operation if we are reading from another * filedump. See below where the file is dumped when reading * form other files (useful for decription). */ if (GBL_OPTIONS->write && !GBL_OPTIONS->read) { /* * we need to lock this because in SM_BRIDGED the * packets are dumped in the log file by two threads */ DUMP_LOCK; pcap_dump((u_char *)GBL_PCAP->dump, pkthdr, pkt); DUMP_UNLOCK; } /* bad packet */ if (pkthdr->caplen > UINT16_MAX) { USER_MSG("Bad packet detected, skipping...\n"); return; } /* * copy the packet in a "safe" buffer * we don't want other packets after the end of the packet (as in BPF) * * also keep the buffer aligned ! * the alignment is set by the media decoder. */ memcpy(GBL_PCAP->buffer + GBL_PCAP->align, pkt, pkthdr->caplen); /* extract data and datalen from pcap packet */ data = (u_char *)GBL_PCAP->buffer + GBL_PCAP->align; datalen = pkthdr->caplen; /* * deal with trucated packets: * if someone has created a pcap file with the snaplen * too small we have to skip the packet (is not interesting for us) */ if (GBL_PCAP->snaplen <= datalen) { USER_MSG("Truncated packet detected, skipping...\n"); return; } /* alloc the packet object structure to be passet through decoders */ packet_create_object(&po, data, datalen); /* Be sure to NULL terminate our data buffer */ *(data + datalen) = 0; /* set the po timestamp */ memcpy(&po.ts, &pkthdr->ts, sizeof(struct timeval)); /* set the interface where the packet was captured */ if (GBL_OPTIONS->iface && !strcmp(iface->name, GBL_OPTIONS->iface)) po.flags |= PO_FROMIFACE; else if (GBL_OPTIONS->iface_bridge && !strcmp(iface->name, GBL_OPTIONS->iface_bridge)) po.flags |= PO_FROMBRIDGE; /* HOOK POINT: RECEIVED */ hook_point(HOOK_RECEIVED, &po); /* * by default the packet should not be processed by ettercap. * if the sniffing filter matches it, the flag will be reset. */ po.flags |= PO_IGNORE; /* * start the analysis through the decoders stack * * if the packet can be handled it will reach the top of the stack * where the decoder_data will add it to the top_half queue, * else the packet will not be handled but it should be forwarded * * after this fuction the packet is completed (all flags set) */ packet_decoder = get_decoder(LINK_LAYER, GBL_PCAP->dlt); BUG_IF(packet_decoder == NULL); packet_decoder(data, datalen, &len, &po); /* special case for bridged sniffing */ if (GBL_SNIFF->type == SM_BRIDGED) { EXECUTE(GBL_SNIFF->check_forwarded, &po); EXECUTE(GBL_SNIFF->set_forwardable, &po); } /* XXX - BIG WARNING !! * * if the packet was filtered by the filtering engine * the state of the packet_object is inconsistent ! * the fields in the structure may not reflect the real * packet fields... */ /* use the sniffing method funcion to forward the packet */ if ( (po.flags & PO_FORWARDABLE) && !(po.flags & PO_FORWARDED) ) { /* HOOK POINT: PRE_FORWARD */ hook_point(HOOK_PRE_FORWARD, &po); EXECUTE(GBL_SNIFF->forward, &po); } /* * dump packets to a file from another file. * this is useful when decrypting packets or applying filters * on pcapfile and we want to save the result in a file */ if (GBL_OPTIONS->write && GBL_OPTIONS->read) { DUMP_LOCK; /* reuse the original pcap header, but with the modified packet */ pcap_dump((u_char *)GBL_PCAP->dump, pkthdr, po.packet); DUMP_UNLOCK; } /* * if it is the last packet set the flag * and send the packet to the top half. * we have to do this because the last packet * might be dropped by the filter. */ if (GBL_OPTIONS->read && GBL_PCAP->dump_size == GBL_PCAP->dump_off) { po.flags |= PO_EOF; top_half_queue_add(&po); } /* free the structure */ packet_destroy_object(&po); /* calculate the stats */ stats_half_end(&GBL_STATS->bh, pkthdr->caplen); CANCELLATION_POINT(); return; }
LOCAL void reader_libpcapfile_opened() { int dlt_to_linktype(int dlt); if (config.flushBetween) moloch_session_flush(); moloch_packet_set_linksnap(dlt_to_linktype(pcap_datalink(pcap)) | pcap_datalink_ext(pcap), pcap_snapshot(pcap)); offlineFile = pcap_file(pcap); if (config.bpf && pcapFileHeader.linktype != 239) { struct bpf_program bpf; if (pcap_compile(pcap, &bpf, config.bpf, 1, PCAP_NETMASK_UNKNOWN) == -1) { LOGEXIT("ERROR - Couldn't compile filter: '%s' with %s", config.bpf, pcap_geterr(pcap)); } if (pcap_setfilter(pcap, &bpf) == -1) { LOGEXIT("ERROR - Couldn't set filter: '%s' with %s", config.bpf, pcap_geterr(pcap)); } } readerPos++; if (readerFileName[readerPos]) moloch_free_later(readerFileName[readerPos], g_free); readerFileName[readerPos] = g_strdup(offlinePcapFilename); int fd = pcap_fileno(pcap); if (fd == -1) { g_timeout_add(0, reader_libpcapfile_read, NULL); } else { moloch_watch_fd(fd, MOLOCH_GIO_READ_COND, reader_libpcapfile_read, NULL); } if (filenameOpsNum > 0) { // Free any previously allocated if (readerFieldOps[readerPos].size > 0) moloch_field_ops_free(&readerFieldOps[readerPos]); moloch_field_ops_init(&readerFieldOps[readerPos], filenameOpsNum, MOLOCH_FIELD_OPS_FLAGS_COPY); // Go thru all the filename ops looking for matches and then expand the value string int i; for (i = 0; i < filenameOpsNum; i++) { GMatchInfo *match_info = 0; g_regex_match(filenameOps[i].regex, offlinePcapFilename, 0, &match_info); if (g_match_info_matches(match_info)) { GError *error = 0; char *expand = g_match_info_expand_references(match_info, filenameOps[i].expand, &error); if (error) { LOG("Error expanding '%s' with '%s' - %s", offlinePcapFilename, filenameOps[i].expand, error->message); g_error_free(error); } if (expand) { moloch_field_ops_add(&readerFieldOps[readerPos], filenameOps[i].field, expand, -1); g_free(expand); } } g_match_info_free(match_info); } } }
void pcap_read(const char *dumpfile, const char *interface, const char *filter_cmd, int snaplen) { int fd; const char *device = NULL; struct bpf_program bprog; if (dumpfile != NULL) { /* read from a saved pcap file */ pd = pcap_open_offline(dumpfile, errbuf); if (pd == NULL) err(1, "%s", errbuf); } else { if (interface != NULL) { device = interface; } else { device = pcap_lookupdev(errbuf); if (device == NULL) errx(1, "%s", errbuf); } if (snaplen == 0) snaplen = DEFAULT_SNAPLEN; fprintf(stderr, "pcap_read: reading from %s with snaplen:%d\n", device, snaplen); pd = pcap_open_live(device, snaplen, 1, 0, errbuf); if (pd == NULL) errx(1, "%s", errbuf); } if (pcap_compile(pd, &bprog, filter_cmd, 0, 0) < 0) err(1, "pcap_compile: %s", pcap_geterr(pd)); else if (pcap_setfilter(pd, &bprog) < 0) err(1, "pcap_setfilter: %s", pcap_geterr(pd)); net_reader = lookup_printer(pcap_datalink(pd)); fd = fileno(pcap_file(pd)); if (device != NULL) { /* let user own process after interface has been opened */ setuid(getuid()); #if defined(BSD) && defined(BPF_MAXBUFSIZE) { /* check the buffer size */ u_int bufsize; if (ioctl(fd, BIOCGBLEN, (caddr_t)&bufsize) < 0) perror("BIOCGBLEN"); else fprintf(stderr, "bpf buffer size is %d\n", bufsize); } #endif /* BSD */ } while (1) { int cnt; cnt = pcap_dispatch(pd, 1, dump_reader, 0); if (cnt < 0) break; if (dumpfile != NULL && cnt == 0) /* EOF */ break; } pcap_close(pd); }
/* name : input_init */ static int input_init( probe_t *probe, int flags ) { char *device = g_par.interface; int dltype; if ( flags & PROBE_OFFLINE ) { /* open file */ if ( (probe->pcap=pcap_open_offline( device, errbuf )) ==NULL) { errorf( "[%s] pcap_open_offline(): %s\n", device, errbuf ); return -1; } probe->cnt = 1; } else { /* open interface */ int promisc = (flags&PROBE_PROMISC)?1:0; char *p = probe->device; if ( *device == '\0' ) { if ((device=pcap_lookupdev( errbuf )) ==NULL) { errorf( "pcap_lookupdev() failed: %s\n", errbuf ); return -1; } } if ( (probe->pcap=pcap_open_live( device, g_snaplen, promisc, 100 /*ms*/, errbuf )) ==NULL ) { /* todo!! */ errorf( "pcap_open_live(%s): %s\n", p, errbuf ); return -1; } probe->cnt = 1000; } switch ( dltype = pcap_datalink(probe->pcap) ) { case DLT_EN10MB: probe->dltype = dltype; probe->offset = 14; break; case DLT_ATM_RFC1483: probe->dltype = dltype; probe->offset = 8; break; default: probe->dltype = DLT_RAW; probe->offset = 0; } if( g_par.filter != NULL ) { if( (pcap_compile( probe->pcap, &probe->fprg, g_par.filter, 1, 0 ) <0) || (pcap_setfilter( probe->pcap, &probe->fprg ) <0) ) { mlogf( 0, "[%s] unable to set filter: '%s'\n", g_par.progname, g_par.filter ); } else { mlogf( 1, "[%s] set filter to '%s'\n", g_par.progname, g_par.filter ); } } mlogf( 1, "[%s] device: %s, dltype=%d, %s\n", g_par.progname, (flags&PROBE_OFFLINE)?basename(device):device, probe->dltype, (flags&PROBE_OFFLINE)?"offline" :(flags&PROBE_PROMISC)?"promisc.":"no promisc." ); if ( flags & PROBE_OFFLINE ) { probe->fd = fileno( pcap_file( probe->pcap ) ); probe->device = strdup( basename( device ) ); } else { probe->fd = pcap_fileno( probe->pcap ); probe->device = strdup( device ); } if ( probe->fd >= 0) { if ( mpoll_fdadd( probe->fd, MPOLL_IN, cb_dispatch, (void*)probe ) <0 ) { mlogf( 0, "[%s] %s\n", g_par.progname, strerror(errno) ); return -1; } mlogf( 2, "[%s] add fd %d to poll loop\n", g_par.progname, probe->fd ); } if ( flow_init( &(probe->ipflows), g_par.ipflow_max, g_par.biflows, g_par.ipflow_timeout ) <0 ) { mlogf( 0, "[%s] ipflow initialisation failed: %s", g_par.progname, strerror(errno) ); return -1; } return 0; }
void query_processor(){ char str[50]; char subquery1[50],subquery2[50]; char bpf_query[50]; struct bpf_program bpf_prog; printf("\nIndex Query Options for fields:\n SrcIP or DstIP or SrcPort or DstPort or Protocol\n Protocol=0 for TCP else 1 for UDP\n"); printf("\nExample: protocol=1\n"); printf("\nPlease Enter Your Index Query: "); scanf("%s",str); printf("\nYour Index Query Was: %s",str); char* pos; //OR if((pos=strchr(str,';'))!=NULL){ strncpy(subquery1,str,pos-str); subquery1[pos-str]='\0'; strncpy(subquery2,str+(pos-str)+1,str+strlen(str)-pos); printf("\nSubquery1: %s",subquery1); printf("\nOR"); printf("\nSubquery2: %s\n",subquery2); single_query(subquery1,1); single_query(subquery2,2); int i; for(i=0;i<packet_count;i++){ query_result[i]=sub1result[i] || sub2result[i]; } } //AND else if((pos=strchr(str,':'))!=NULL){ strncpy(subquery1,str,pos-str); subquery1[pos-str]='\0'; strncpy(subquery2,str+(pos-str)+1,str+strlen(str)-pos); printf("\nSubquery1: %s",subquery1); printf("\nAND"); printf("\nSubquery2: %s\n",subquery2); single_query(subquery1,1); single_query(subquery2,2); int i; for(i=0;i<packet_count;i++){ query_result[i]=sub1result[i] && sub2result[i]; } } //Single big query else{ single_query(str,0); } //Populate the indirection from the indirection array file FILE *indir_file; indir_file=fopen("resources/Indirection.txt","r"); int i; int indir_arr[1000]; char line[1000]; for(i=0;i<packet_count;i++) { fgets(line,1000,indir_file); int j=0; int count=0; while(line[j]!='\n'){ count=count*10+ line[j]-48; j++; } indir_arr[i] = count; } int offsets_arr_length=0; for(i=0;i<packet_count;i++) { if(query_result[i]==1) { offsets[offsets_arr_length++]=indir_arr[i]; } } char errbuf[PCAP_ERRBUF_SIZE]; pcap_t* descr; const u_char *packet; struct pcap_pkthdr hdr; const struct ip* iphdr; const struct sniff_tcp* tcp; const struct UDP_hdr *udp; descr = pcap_open_offline("1.cap",errbuf); if(descr == NULL) { printf("pcap_open_offline(): %s\n",errbuf); exit(1); } printf("\n%d packets met with the requirements of index query\n",offsets_arr_length); printf("\nPlease Enter Your BPF query:"); getchar(); gets(bpf_query); printf("Your BPF query was: %s\n",bpf_query); printf("\nSatisfying packets:\n"); for(k=0;k<offsets_arr_length;k++) { fseek(pcap_file(descr),offsets[k],SEEK_SET); if (pcap_compile(descr, &bpf_prog, (const char*)bpf_query, 0, PCAP_NETMASK_UNKNOWN) == -1) { printf("Couldn't parse filter %s: %s\n", bpf_query, pcap_geterr(descr)); } if (pcap_setfilter(descr, &bpf_prog) == -1) { printf("Couldn't install filter %s: %s\n", bpf_query, pcap_geterr(descr)); } packet = pcap_next(descr,&hdr); //printf("\n%d",offsets[k]+16+hdr.len); //printf("\n%d",ftell(pcap_file(descr))); if(packet!=NULL && offsets[k]+16+hdr.len ==ftell(pcap_file(descr))) { iphdr = (struct ip*)(packet + sizeof(struct ether_header)); printf("\nPacket Number:%d\n",k+1); printf("Packet Found at offset:%d\n",offsets[k]); printf("Source:%s\n",inet_ntoa(iphdr->ip_src)); printf("Destination:%s\n",inet_ntoa(iphdr->ip_dst)); if(iphdr->ip_p==6){ printf("Protocol:TCP\n"); tcp = (struct sniff_tcp*)(packet+sizeof(struct ether_header)+sizeof(struct iphdr)); printf("Source Port:%d\n",ntohs(tcp->th_sport)); printf("Destination Port:%d\n",ntohs(tcp->th_dport)); } else if(iphdr->ip_p==17){ printf("Protocol:UDP\n"); udp=(struct UDP_hdr*)(packet+sizeof(struct ether_header)+sizeof(struct iphdr)); printf("Source Port:%d\n",ntohs(udp->uh_sport)); printf("Destination Port:%d\n",ntohs(udp->uh_dport)); } } printf("\n"); } }
void packet_indexer(){ int i; char errbuf[PCAP_ERRBUF_SIZE]; pcap_t* descr; const u_char *packet; struct pcap_pkthdr hdr; /* pcap.h */ long int indir_offset=0; char *token; int token_int; descr = pcap_open_offline("1.cap",errbuf); if(descr == NULL) { printf("pcap_open_offline(): %s\n",errbuf); exit(1); } const struct ip* iphdr; const struct sniff_tcp* tcp; const struct UDP_hdr *udp; FILE *indir,*sip[4],*dip[4],*port_f[2],*proto_f; //file openings indir=fopen("resources/Indirection.txt","w"); sip[0]=fopen("resources/Source1.txt","w"); sip[1]=fopen("resources/Source2.txt","w"); sip[2]=fopen("resources/Source3.txt","w"); sip[3]=fopen("resources/Source4.txt","w"); dip[0]=fopen("resources/Destination1.txt","w"); dip[1]=fopen("resources/Destination2.txt","w"); dip[2]=fopen("resources/Destination3.txt","w"); dip[3]=fopen("resources/Destination4.txt","w"); port_f[0]=fopen("resources/SourcePort.txt","w"); port_f[1]=fopen("resources/DestinPort.txt","w"); proto_f= fopen("resources/Protocol.txt","w"); //Generating Bitmap From Packets while(end_flag==0){ indir_offset=ftell(pcap_file(descr)); packet = pcap_next(descr,&hdr); if(packet != NULL){ fprintf(indir,"%ld\n",indir_offset); ++packet_count; /* jump past the ethernet header */ iphdr = (struct ip*)(packet + sizeof(struct ether_header)); /*printf("\nPacket Number:%d\n",packet_count); printf("Source:%s\n",inet_ntoa(iphdr->ip_src)); printf("Destination:%s\n",inet_ntoa(iphdr->ip_dst));*/ if(iphdr->ip_p==6){ //printf("Protocol:TCP\n"); tcp = (struct sniff_tcp*)(packet+sizeof(struct ether_header)+sizeof(struct iphdr)); /*printf("Source Port:%d\n",ntohs(tcp->th_sport)); printf("Destination Port:%d\n",ntohs(tcp->th_dport));*/ port[0][packet_count-1][ntohs(tcp->th_sport)]=1; port[1][packet_count-1][ntohs(tcp->th_dport)]=1; proto[packet_count-1][0]=1; } else if(iphdr->ip_p==17){ //printf("Protocol:UDP\n"); udp=(struct UDP_hdr*)(packet+sizeof(struct ether_header)+sizeof(struct iphdr)); /*printf("Source Port:%d\n",ntohs(udp->uh_sport)); printf("Destination Port:%d\n",ntohs(udp->uh_dport));*/ port[0][packet_count-1][ntohs(udp->uh_sport)]=1; port[1][packet_count-1][ntohs(udp->uh_dport)]=1; proto[packet_count-1][1]=1; } //Indirection Array //Source IP Tokenizing and normal bitmap index creation token = strtok(inet_ntoa(iphdr->ip_src), "."); i=0; while( token != NULL ){ token_int=atoi(token); src[i++][packet_count-1][token_int]=1; token = strtok(NULL, "."); } //Destination IP Tokenizing and normal bitmap index creation token = strtok(inet_ntoa(iphdr->ip_dst), "."); i=0; while( token != NULL ){ token_int=atoi(token); dst[i++][packet_count-1][token_int]=1; token = strtok(NULL, "."); } } else end_flag=1; }//end of while //Source Compression for(i=0;i<4;i++){ for(k=0;k<256;k++){ for(j=0;j<packet_count;j++){ if(j==0){ if(src[i][j][k]==0){ digit_type=0; digit_count=1; } else if(src[i][j][k]==1){ digit_type=1; digit_count=1; } }//if-j else{ if(digit_type==src[i][j][k]){ digit_count++; } else { fprintf(sip[i],"%ld ",digit_count); fprintf(sip[i],"%ld ",digit_type); digit_type=src[i][j][k]; digit_count=1; } } }//j fprintf(sip[i],"%ld ",digit_count); fprintf(sip[i],"%ld ",digit_type); fprintf(sip[i],"\n"); }//k }//i //Destination comperssion for(i=0;i<4;i++){ for(k=0;k<256;k++){ for(j=0;j<packet_count;j++){ if(j==0){ if(dst[i][j][k]==0){ digit_type=0; digit_count=1; } else if(dst[i][j][k]==1){ digit_type=1; digit_count=1; } }//if-j else{ if(digit_type==dst[i][j][k]){ digit_count++; } else { fprintf(dip[i],"%ld ",digit_count); fprintf(dip[i],"%ld ",digit_type); digit_type=dst[i][j][k]; digit_count=1; } } }//j fprintf(dip[i],"%ld ",digit_count); fprintf(dip[i],"%ld ",digit_type); fprintf(dip[i],"\n"); }//k }//i //Port comperssion for(i=0;i<2;i++){ for(k=0;k<65536;k++){ for(j=0;j<packet_count;j++){ if(j==0){ if(port[i][j][k]==0){ digit_type=0; digit_count=1; } else if(port[i][j][k]==1){ digit_type=1; digit_count=1; } }//if-j else{ if(digit_type==port[i][j][k]){ digit_count++; } else { fprintf(port_f[i],"%ld ",digit_count); fprintf(port_f[i],"%ld ",digit_type); digit_type=port[i][j][k]; digit_count=1; } } }//j fprintf(port_f[i],"%ld ",digit_count); fprintf(port_f[i],"%ld ",digit_type); fprintf(port_f[i],"\n"); }//k }//i //End Port Compression //protocol compression for(k=0;k<2;k++){ for(j=0;j<packet_count;j++){ if(j==0){ if(proto[j][k]==0){ digit_type=0; digit_count=1; } else if(proto[j][k]==1){ digit_type=1; digit_count=1; } }//if-j else{ if(digit_type==proto[j][k]){ digit_count++; } else { fprintf(proto_f,"%ld ",digit_count); fprintf(proto_f,"%ld ",digit_type); digit_type=proto[j][k]; digit_count=1; } } }//j fprintf(proto_f,"%ld ",digit_count); fprintf(proto_f,"%ld ",digit_type); fprintf(proto_f,"\n"); }//k fclose(indir); fclose(sip[0]); fclose(sip[1]); fclose(sip[2]); fclose(sip[3]); fclose(dip[0]); fclose(dip[1]); fclose(dip[2]); fclose(dip[3]); fclose(port_f[0]); fclose(port_f[1]); fclose(proto_f); pcap_close(descr); }
void capture_init(void) { pcap_t *pd; pcap_t *pb = NULL; /* for the bridge */ pcap_dumper_t *pdump; bpf_u_int32 net, mask; struct bpf_program bpf; char pcap_errbuf[PCAP_ERRBUF_SIZE]; /* * if the user didn't specified the interface, * we have to found one... */ if (!GBL_OPTIONS->read && GBL_OPTIONS->iface == NULL) { char *ifa = pcap_lookupdev(pcap_errbuf); ON_ERROR(ifa, NULL, "No suitable interface found..."); GBL_OPTIONS->iface = iface_name(ifa); } if (GBL_OPTIONS->iface) DEBUG_MSG("capture_init %s", GBL_OPTIONS->iface); else DEBUG_MSG("capture_init (no interface)"); if (GBL_SNIFF->type == SM_BRIDGED) { if (!strcmp(GBL_OPTIONS->iface, GBL_OPTIONS->iface_bridge)) FATAL_ERROR("Bridging iface must be different from %s", GBL_OPTIONS->iface); USER_MSG("Bridging %s and %s...\n\n", GBL_OPTIONS->iface, GBL_OPTIONS->iface_bridge); } else if (GBL_OPTIONS->read) { USER_MSG("Reading from %s... ", GBL_OPTIONS->pcapfile_in); } else USER_MSG("Listening on %s... ", GBL_OPTIONS->iface); /* set the snaplen to maximum */ GBL_PCAP->snaplen = UINT16_MAX; /* open the interface from GBL_OPTIONS (user specified) */ if (GBL_OPTIONS->read) pd = pcap_open_offline(GBL_OPTIONS->pcapfile_in, pcap_errbuf); else pd = pcap_open_live(GBL_OPTIONS->iface, GBL_PCAP->snaplen, GBL_PCAP->promisc, PCAP_TIMEOUT, pcap_errbuf); ON_ERROR(pd, NULL, "pcap_open: %s", pcap_errbuf); /* * update to the reap assigned snapshot. * this may be different reading from files */ DEBUG_MSG("requested snapshot: %d assigned: %d", GBL_PCAP->snaplen, pcap_snapshot(pd)); GBL_PCAP->snaplen = pcap_snapshot(pd); /* get the file size */ if (GBL_OPTIONS->read) { struct stat st; fstat(fileno(pcap_file(pd)), &st); GBL_PCAP->dump_size = st.st_size; } /* set the pcap filters */ if (GBL_PCAP->filter != NULL && strcmp(GBL_PCAP->filter, "")) { DEBUG_MSG("pcap_filter: %s", GBL_PCAP->filter); if (pcap_lookupnet(GBL_OPTIONS->iface, &net, &mask, pcap_errbuf) == -1) ERROR_MSG("%s", pcap_errbuf); if (pcap_compile(pd, &bpf, GBL_PCAP->filter, 1, mask) < 0) ERROR_MSG("%s", pcap_errbuf); if (pcap_setfilter(pd, &bpf) == -1) ERROR_MSG("pcap_setfilter"); pcap_freecode(&bpf); } /* if in bridged sniffing, we have to open even the other iface */ if (GBL_SNIFF->type == SM_BRIDGED) { pb = pcap_open_live(GBL_OPTIONS->iface_bridge, GBL_PCAP->snaplen, GBL_PCAP->promisc, PCAP_TIMEOUT, pcap_errbuf); ON_ERROR(pb, NULL, "%s", pcap_errbuf); /* set the pcap filters */ if (GBL_PCAP->filter != NULL) { if (pcap_lookupnet(GBL_OPTIONS->iface_bridge, &net, &mask, pcap_errbuf) == -1) ERROR_MSG("%s", pcap_errbuf); if (pcap_compile(pb, &bpf, GBL_PCAP->filter, 1, mask) < 0) ERROR_MSG("%s", pcap_errbuf); if (pcap_setfilter(pb, &bpf) == -1) ERROR_MSG("pcap_setfilter"); pcap_freecode(&bpf); } } /* open the dump file */ if (GBL_OPTIONS->write) { DEBUG_MSG("pcapfile_out: %s", GBL_OPTIONS->pcapfile_out); pdump = pcap_dump_open(pd, GBL_OPTIONS->pcapfile_out); ON_ERROR(pdump, NULL, "%s", pcap_geterr(pd)); GBL_PCAP->dump = pdump; } /* set the right dlt type for the iface */ GBL_PCAP->dlt = pcap_datalink(pd); DEBUG_MSG("capture_init: %s [%d]", pcap_datalink_val_to_description(GBL_PCAP->dlt), GBL_PCAP->dlt); USER_MSG("(%s)\n\n", pcap_datalink_val_to_description(GBL_PCAP->dlt)); /* check that the bridge type is the same as the main iface */ if (GBL_SNIFF->type == SM_BRIDGED && pcap_datalink(pb) != GBL_PCAP->dlt) FATAL_ERROR("You can NOT bridge two different type of interfaces !"); /* check if we support this media */ if (get_decoder(LINK_LAYER, GBL_PCAP->dlt) == NULL) { if (GBL_OPTIONS->read) FATAL_ERROR("Dump file not supported (%s)", pcap_datalink_val_to_description(GBL_PCAP->dlt)); else FATAL_ERROR("Inteface \"%s\" not supported (%s)", GBL_OPTIONS->iface, pcap_datalink_val_to_description(GBL_PCAP->dlt)); } /* set the alignment for the buffer */ set_alignment(GBL_PCAP->dlt); /* allocate the buffer for the packets (UINT16_MAX) */ SAFE_CALLOC(GBL_PCAP->buffer, UINT16_MAX + GBL_PCAP->align, sizeof(char)); /* set the global descriptor for both the iface and the bridge */ GBL_PCAP->pcap = pd; if (GBL_SNIFF->type == SM_BRIDGED) GBL_PCAP->pcap_bridge = pb; /* on exit clean up the structures */ atexit(capture_close); }
void got_packet (u_char *useless,const struct pcap_pkthdr *pheader, const u_char *packet) { if ( intr_flag != 0 ) { check_interupt(); } inpacket = 1; tstamp = pheader->ts; /* are we dumping */ if (mode & MODE_DUMP) { time_t now = time(NULL); /* check if we should roll on time */ if( ( roll_time != 0 ) && ( now >= (roll_time_last + roll_time) ) ) { roll_time_last = now; printf("Rolling on time.\n"); dump_file_roll(); } dump_file_offset = (uint64_t)ftell((FILE *)dump_handle); /* check if we should roll on size */ if ( (roll_size > 0) && (dump_file_offset >= roll_size) ) { printf("Rolling on size.\n"); dump_file_roll(); } /* write the packet */ pcap_dump((u_char *)dump_handle, pheader, packet); if ( dump_with_flush ) pcap_dump_flush(dump_handle); } else if ( mode & MODE_FILE ) { read_file_offset = (uint64_t)ftell(pcap_file(handle)) - pheader->caplen - 16; } /* printf("[*] Got network packet...\n"); */ ether_header *eth_hdr; eth_hdr = (ether_header *) (packet); u_short eth_type; eth_type = ntohs(eth_hdr->eth_ip_type); int eth_header_len; eth_header_len = ETHERNET_HEADER_LEN; vlanid = 0; if ( eth_type == ETHERNET_TYPE_8021Q ) { /* printf("[*] ETHERNET TYPE 8021Q\n"); */ eth_type = ntohs(eth_hdr->eth_8_ip_type); eth_header_len +=4; vlanid = ntohs(eth_hdr->eth_8_vid); } else if ( eth_type == (ETHERNET_TYPE_802Q1MT|ETHERNET_TYPE_802Q1MT2|ETHERNET_TYPE_802Q1MT3|ETHERNET_TYPE_8021AD) ) { /* printf("[*] ETHERNET TYPE 802Q1MT\n"); */ eth_type = ntohs(eth_hdr->eth_82_ip_type); eth_header_len +=8; vlanid = ntohs(eth_hdr->eth_82_vid); } /* zero-ise our structure, simplifies our hashing later on */ int ip_tracked = 0; ip_t *ip_src = calloc(1, sizeof(ip_t)); ip_t *ip_dst = calloc(1, sizeof(ip_t)); if ( eth_type == ETHERNET_TYPE_IP ) { /* printf("[*] Got IPv4 Packet...\n"); */ ip4_header *ip4; ip4 = (ip4_header *) (packet + eth_header_len); ip_set(&ip_config, ip_src, &ip4->ip_src, AF_INET); ip_set(&ip_config, ip_dst, &ip4->ip_dst, AF_INET); if ( ip4->ip_p == IP_PROTO_TCP ) { tcp_header *tcph; tcph = (tcp_header *) (packet + eth_header_len + (IP_HL(ip4)*4)); /* printf("[*] IPv4 PROTOCOL TYPE TCP:\n"); */ ip_tracked = cx_track(ip_src, tcph->src_port, ip_dst, tcph->dst_port, ip4->ip_p, pheader->len, tcph->t_flags, tstamp, AF_INET); } else if (ip4->ip_p == IP_PROTO_UDP) { udp_header *udph; udph = (udp_header *) (packet + eth_header_len + (IP_HL(ip4)*4)); /* printf("[*] IPv4 PROTOCOL TYPE UDP:\n"); */ ip_tracked = cx_track(ip_src, udph->src_port, ip_dst, udph->dst_port, ip4->ip_p, pheader->len, 0, tstamp, AF_INET); } else if (ip4->ip_p == IP_PROTO_ICMP) { icmp_header *icmph; icmph = (icmp_header *) (packet + eth_header_len + (IP_HL(ip4)*4)); /* printf("[*] IP PROTOCOL TYPE ICMP\n"); */ ip_tracked = cx_track(ip_src, icmph->s_icmp_id, ip_dst, icmph->s_icmp_id, ip4->ip_p, pheader->len, 0, tstamp, AF_INET); } else { /* printf("[*] IPv4 PROTOCOL TYPE OTHER: %d\n",ip4->ip_p); */ ip_tracked = cx_track(ip_src, ip4->ip_p, ip_dst, ip4->ip_p, ip4->ip_p, pheader->len, 0, tstamp, AF_INET); } } else if ( eth_type == ETHERNET_TYPE_IPV6) { /* printf("[*] Got IPv6 Packet...\n"); */ ip6_header *ip6; ip6 = (ip6_header *) (packet + eth_header_len); ip_set(&ip_config, ip_src, &ip6->ip_src, AF_INET6); ip_set(&ip_config, ip_dst, &ip6->ip_dst, AF_INET6); if ( ip6->next == IP_PROTO_TCP ) { tcp_header *tcph; tcph = (tcp_header *) (packet + eth_header_len + IP6_HEADER_LEN); /* printf("[*] IPv6 PROTOCOL TYPE TCP:\n"); */ ip_tracked = cx_track(ip_src, tcph->src_port, ip_dst, tcph->dst_port, ip6->next, pheader->len, tcph->t_flags, tstamp, AF_INET6); } else if (ip6->next == IP_PROTO_UDP) { udp_header *udph; udph = (udp_header *) (packet + eth_header_len + IP6_HEADER_LEN); /* printf("[*] IPv6 PROTOCOL TYPE UDP:\n"); */ ip_tracked = cx_track(ip_src, udph->src_port, ip_dst, udph->dst_port, ip6->next, pheader->len, 0, tstamp, AF_INET6); } else if (ip6->next == IP6_PROTO_ICMP) { //icmp6_header *icmph; //icmph = (icmp6_header *) (packet + eth_header_len + IP6_HEADER_LEN); /* printf("[*] IPv6 PROTOCOL TYPE ICMP\n"); */ ip_tracked = cx_track(ip_src, ip6->hop_lmt, ip_dst, ip6->hop_lmt, ip6->next, pheader->len, 0, tstamp, AF_INET6); } else { /* printf("[*] IPv6 PROTOCOL TYPE OTHER: %d\n",ip6->next); */ ip_tracked = cx_track(ip_src, ip6->next, ip_dst, ip6->next, ip6->next, pheader->len, 0, tstamp, AF_INET6); } } if ( ip_tracked == 0 ) { if (ip_src != NULL) ip_free(ip_src); if (ip_dst != NULL) ip_free(ip_dst); } inpacket = 0; return; (void) useless; /* else { */ /* printf("[*] ETHERNET TYPE : %x\n", eth_hdr->eth_ip_type); */ /* return; */ /* } */ }
int main(int argc, char *argv[]) { char c; char in_file[1024]; char out_file[1024]; char json_file[1024]; char check; unsigned long byte_offset; unsigned long pk_cnt; char errbuf[PCAP_ERRBUF_SIZE]; pcap_t *cap; struct pcap_pkthdr *h; const u_char *bytes; struct pcap_file_header fh; FILE *fp_pcap; size_t nwrt, wcnt; extern char *optarg; extern int optind, optopt; FILE *pcap_of; unsigned long dur, pkt_num; unsigned int dlt; struct timeval tstart; byte_offset = 0; check = 0; dur = 0; def = 0; pkt_num = 0; while ((c = getopt(argc, argv, "vf:s:o:hj:d:n:")) != -1) { switch(c) { case 'v': printf("pcapseek %d.%d.%d\n", PS_VER_MAG, PS_VER_MIN, PS_VER_REV); return 0; break; case 'f': sprintf(in_file, "%s", optarg); check |= 0x01; break; case 's': byte_offset = atol(optarg); check |= 0x02; break; case 'o': sprintf(out_file, "%s", optarg); check |= 0x04; break; case 'j': sprintf(json_file, "%s", optarg); check |= 0x08; break; case 'd': dur = atol(optarg); break; case 'n': pkt_num = atol(optarg); break; case 'h': Usage(argv[0]); return 0; break; case '?': printf("Error: unrecognized option: -%c\n", optopt); Usage(argv[0]); exit(-1); break; } } printf("pcapseek v%d.%d.%d\n", PS_VER_MAG, PS_VER_MIN, PS_VER_REV); printf("%s\n", PS_CR); if (check != 0x07) { Usage(argv[0]); exit(-1); } printf("Packet offset: %lu dur: %lu\n", byte_offset, dur); pk_cnt = 0; cap = pcap_open_offline(in_file, errbuf); if (cap == NULL) { printf("Error:%s\n", errbuf); return -1; } pcap_of = pcap_file(cap); /* pcap out file */ fp_pcap = fopen(out_file, "w"); memset(&fh, 0, sizeof(struct pcap_file_header)); fh.magic = 0xA1B2C3D4; fh.version_major = PCAP_VERSION_MAJOR; fh.version_minor = PCAP_VERSION_MINOR; fh.snaplen = 65535; fh.linktype = pcap_datalink(cap); if (fp_pcap != NULL) { fwrite((char *)&fh, 1, sizeof(struct pcap_file_header), fp_pcap); } else { printf("Error to open file:%s\n", out_file); pcap_close(cap); return -1; } if (byte_offset != 0) { SrchPktOffset(pcap_of, cap, byte_offset); } dlt = pcap_datalink(cap); while (pcap_next_ex(cap, &h, &bytes) == 1) { if (pk_cnt == 0) { tstart.tv_sec = h->ts.tv_sec; } else { if (dur != 0 && (h->ts.tv_sec - tstart.tv_sec) > dur) { break; } } if (PktCheck(dlt, h, (u_char *)bytes)) { pk_cnt++; wcnt = 0; do { nwrt = fwrite(((char *)h)+wcnt, 1, sizeof(struct pcap_pkthdr)-wcnt, fp_pcap); if (nwrt != -1) wcnt += nwrt; else break; } while (wcnt != sizeof(struct pcap_pkthdr)); wcnt = 0; do { nwrt = fwrite(((char *)bytes)+wcnt, 1, h->caplen-wcnt, fp_pcap); if (nwrt != -1) wcnt += nwrt; else break; } while (wcnt != h->caplen); if (pkt_num == pk_cnt) { break; } } else if (pk_cnt == 0) { /* some layers are missing */ } } fclose(fp_pcap); pcap_close(cap); printf("Pkt: %lu\n", pk_cnt); return 0; }