void process_packet(u_char *user, const struct pcap_pkthdr *pkthdr, const u_char *packet)
{
    static int packet_count = 0;
    static struct timeval first_packet_ts;

    time_t ref_tv_sec;
    time_t ref_tv_usec;

    if (packet_count == 0)
    {
        first_packet_ts = pkthdr->ts;
        ref_tv_sec = 0;
        ref_tv_usec = 0;
    }
    else
    {
        if (first_packet_ts.tv_usec > pkthdr->ts.tv_usec)
        {
            ref_tv_sec = pkthdr->ts.tv_sec - first_packet_ts.tv_sec - 1;
            ref_tv_usec = 1000000 - first_packet_ts.tv_usec + pkthdr->ts.tv_usec;
        }
        else
        {
            ref_tv_sec = pkthdr->ts.tv_sec - first_packet_ts.tv_sec;
            ref_tv_usec = pkthdr->ts.tv_usec - first_packet_ts.tv_usec;
        }
    }

    printf("=======================================================\n");

    /* print headers */
    print_pcap_packet_info(packet_count,
                           ref_tv_sec,
                           ref_tv_usec,
                           pkthdr->len);

    /* print payload */
    print_payload(packet, pkthdr->len);

    /* print headers */
    print_ether_header(packet);
    print_ip_header(packet);
    print_tcp_header(packet);
 
    printf("=======================================================\n\n");

    packet_count++;
}
示例#2
0
文件: netray.c 项目: mw99/netray
/*
 * Process a packet on the transport layer. 
 *
 * @param recvsize: size of the captured data 
 * @param packet: packet capture data target structure
 * @param raw: packet data at layer 4 entry
 */
bool process_transport_layer(size_t recvsize, struct packet* packet, byte* raw)
{
	// switch over layer 4 protocol
	switch( packet->transport_layer_code )
	{
		break;case PRO_ICMP:
			if( recvsize < sizeof(struct icmphdr) )
			{
				printf("ERROR Received data indicates an ICMP header but it is incomplete\n");
				return false;
			}
			extract_icmp_header( packet, raw );
			print_icmp_header( packet );

		break;case PRO_TCP:
			if( recvsize < sizeof(struct tcphdr) )
			{
				printf("ERROR Received data indicates a TCP header but it is incomplete\n");
				return false;
			}
			extract_tcp_header( packet, raw );
			print_tcp_header( packet );

		break;case PRO_UDP:
			if( recvsize < sizeof(struct udphdr) )
			{
				printf("ERROR Received data indicates an UDP header but it is incomplete\n");
				return false;
			}
			extract_udp_header( packet, raw );
			print_udp_header( packet );

		break;case UNKNOWN_TRANSPORT_PROTOCOL:
			printf("Unknown transport layer protocol.\n");
			return false;
	}

	return true;
}
int main()
{
	char buff[MAX_SIZE];
	int sock_fd;
	int protocol;
	if ((sock_fd = socket(AF_PACKET, SOCK_RAW, htons(ETH_P_ALL))) == -1) {
		perror("socket()");
		exit(-1);
	}
	while(1) {
		if(recvfrom(sock_fd, buff, MAX_SIZE, 0, NULL, NULL) == -1) {
			perror("recvfrom()");
			exit(-1);
		}
		print_eth_header((ethernet_header_p)buff);
		protocol = print_ip_header((ip_header_p)(buff + sizeof(ethernet_header_t)));
		if (protocol == 0x6) {
			print_tcp_header((tcp_header_p)(buff + sizeof(ethernet_header_t) + sizeof(ip_header_t))); 
		} else if(protocol == 0x11) {
			print_udp_header((udp_header_p)(buff + sizeof(ethernet_header_t) + sizeof(ip_header_t))); 
		}
	}
	return 0;
}
示例#4
0
void print_ip4_packet(u8 *ip_pkt)
{
	struct iphdr *iph = (struct iphdr *)ip_pkt;
	u8 *pkt = ip_pkt + (iph->ihl << 2);
	u16 flags = (ntohs(iph->frag_off) & 0xE000);
	u16 frag_off = (ntohs(iph->frag_off) & 0x1FFF);

	pr_err("-----------------------------------------------------------\n");

/*---------------------------------------------------------------------------

				IPv4 Header Format

	+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
	|Version|  IHL  |Type of Service|          Total Length         |
	+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
	|         Identification        |C|D|M|     Fragment Offset     |
	|                               |E|F|F|                         |
	+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
	|  Time to Live |    Protocol   |         Header Checksum       |
	+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
	|                       Source Address                          |
	+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
	|                    Destination Address                        |
	+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

	+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
	|                    Options                    |    Padding    |
	+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+

	IHL - Header Length
	Flags - Consist of 3 bits
		The 1st bit is "Congestion" bit.
		The 2nd bit is "Dont Fragment" bit.
		The 3rd bit is "More Fragments" bit.

---------------------------------------------------------------------------*/

	memset(ip_flags, 0, sizeof(ip_flags));
	if (flags & IP_CE)
		strcat(ip_flags, "CE ");
	if (flags & IP_DF)
		strcat(ip_flags, "DF ");
	if (flags & IP_MF)
		strcat(ip_flags, "MF ");

	pr_err("IP4:: Version = %u, Header Length = %u, TOS = %u, Length = %u\n",
		iph->version, (iph->ihl << 2), iph->tos, ntohs(iph->tot_len));
	pr_err("IP4:: ID = %u, Fragment Offset = %u\n",
		ntohs(iph->id), frag_off);
	pr_err("IP4:: Flags = %s\n", ip_flags);
	pr_err("IP4:: TTL = %u, Protocol = %u, Header Checksum = 0x%04X\n",
		iph->ttl, iph->protocol, ntohs(iph->check));
	pr_err("IP4:: Src IP Addr = %u.%u.%u.%u, Dst IP Addr = %u.%u.%u.%u\n",
		ip_pkt[12], ip_pkt[13], ip_pkt[14], ip_pkt[15],
		ip_pkt[16], ip_pkt[17], ip_pkt[18], ip_pkt[19]);

	switch (iph->protocol) {
	case 6:
		/* TCP */
		print_tcp_header(pkt);
		break;

	case 17:
		/* UDP */
		print_udp_header(pkt);
		break;

	default:
		break;
	}

	pr_err("-----------------------------------------------------------\n");
}
int main(int argc, char **argv)
{
  char *filename;
  FILE *datafile;
  struct stat fstat;

  long int bufcount;
  char *buff;
  int max_bufsz = DEFMAX_BUFSZ;
  int bufsz;

  //Kluge stuff, count total num samps
  //  long int totsampcount;

  //TCP stuff
  struct tcp_header *tcp_hdr;
  struct tcp_parser *parser;
  //  bool careful_strip = true; //ensures things are where they say they are before junking them
  //  FILE *stripfile;
  char tcp_str[16] = { 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00, 
			0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07 };

  struct dewe_chan *chan[MAX_NUMCHANS];
  char *chanbuff[MAX_NUMCHANS];
  char *chantimestamps[MAX_NUMCHANS];
  char combfname[] = "combined_chans.data";
  FILE *combfile; //File for combining upper 10, lower 6 bits of two different channels
                  //to accommodate the strange 10-bit TM data at Wallops
  
  signal(SIGINT, do_depart);

  //Kluge stuff, init total num samps
  //  totsampcount = 0;

  //tcp header stuff
  tcp_hdr = tcp_header_init();

  //tcp parser stuff
  parser = parser_init();

  parser->hdrsz = 32 + STARTSTR_SZ; //per DEWESoft NET interface docs

  //copy in start and tail string for use by parse_tcp_header() and strip_tcp_packet()
  if( DEF_VERBOSE ) printf("tcp_fileparse.c [main()] Start string:\t");
  for (int i = 0; i < STARTSTR_SZ; i ++){
    strncpy(&(parser->startstr[i]),&(tcp_str[8+i]),1);
    if ( DEF_VERBOSE ) printf("%x",parser->startstr[i]);
  }
  if( DEF_VERBOSE ) printf("\n");
  parser->startstr_sz = STARTSTR_SZ;

  if( DEF_VERBOSE ) printf("tcp_fileparse.c [main()] Tail string:\t");
  strncpy(parser->tlstr,tcp_str,STARTSTR_SZ); 
  if (DEF_VERBOSE ){
    for (int i = 0; i < STARTSTR_SZ; i ++){
      printf("%x",parser->tlstr[i]);
    }
    printf("\n");
  }
  parser->tailsz = STARTSTR_SZ;

  parser->oldhpos = -(parser->hdrsz + parser->tailsz); //Needs to be initialized thusly so that 
                                                       //parse_tcp_header doesn't complain that 
                                                       //the first header isn't where predicted
  parser->do_predict = true;
  parser->isfile = true;

  parser->verbose = DEF_VERBOSE;

  //Handle command line  
  if(argc == 2) {
    filename = strdup(argv[1]);
  }
  else if ( argc == 3 ){
    filename = strdup(argv[1]);
    max_bufsz = atoi(argv[2]);
  }
  else if( ( argc == 4 ) || ( argc == 5) ){

    filename = strdup(argv[1]);
    max_bufsz = atoi(argv[2]);

    //Strip packet modes
    if( atoi(argv[3]) <= 2){ 
      parser->strip_packet = atoi(argv[3]);
      parser->strip_fname = malloc(sizeof(char) * 128);
      parser->strip_fname = "stripped.data";
      //    sprintf(parser->strip_fname,"stripped-%s",filename);
      parser->oldt_in_this_buff = 0;
      parser->t_in_this_buff = 0;
    }
    //Channel modes
    else if( ( atoi(argv[3]) == 4 ) ||  ( atoi(argv[3]) == 5 ) || ( atoi(argv[3]) == 6 ) || ( atoi(argv[3]) == 7 ) ){ // only parse chan info 
      parser->do_chans = atoi(argv[3]) - 3;
      if( argc ==5 ){ //channel num provided
	parser->nchans = atoi(argv[4]);
      }
      else {
	parser->nchans = DEF_NUMCHANS;
      }
      if( DEF_VERBOSE ) printf("tcp_fileparse.c [main()] parser->nchans\t=\t%i\n",parser->nchans);
    }
    else {
      printf("You fool!!! You expect this program to clean your room as well?\n");
      return EXIT_FAILURE;
    }
  }
  else {
    printf("%s <tcp data file> <optional max readbuffer size> <run_mode> [for run_mode 4/5: NUM_CHANS]\n",argv[0]);
    printf("RUN MODES:\n");
    printf("\tFOR STRIPPING PACKETS\n");
    printf("\t0: No stripping of data is done. Prints packet headers to stdout.\n");
    printf("\t1: The packet header and footer are stripped from the data for RTD, but left in the data file\n");
    printf("\t2: The packet header and footer are stripped from the data for RTD AND the saved data file\n");
    printf("\t3: Stripped data are saved and RTDed, and bad packets are output to an error file, badpack.data (NOT YET IMPLEMENTED)\n");
    printf("\n");
    printf("\tFOR DOING CHANNEL TRICKERY\n");
    printf("\t4: Channel information is parsed and printed to stdout, but no files are created.\n");
    printf("\t5: A data file is created for each channel.\n");
    printf("\t6: A data file is created for each channel, AND the first and second channel are combined with"
	   "\n\t   join_upper10_lower6() and outputted as joinupper10lower6.data.\n");
    printf("\t7: Just for RxDSPs! A data file is created for each channel (always assumed asynchronous)"
	   "\n\t   but only the timestamp associated with a Dartmouth header is kept, instead of keeping all timestamps."
	   "\n\t   (Precludes digitizer mode, -g)\n");
    return(EXIT_SUCCESS);
  }

  //Open data file
  printf("Opening TCP data file %s\n",filename);
  if( ( datafile = fopen(filename,"r") ) == NULL ){
    fprintf(stderr,"Gerrorg. Couldn't open file %s.\n",filename);
    return(EXIT_FAILURE);
  }
  stat(filename,&fstat);
  parser->filesize = fstat.st_size;

  //Prepare buffers
  buff = malloc(sizeof(char) * max_bufsz);
  if( DEF_VERBOSE ) printf("Max buffer size:\t%i\n", max_bufsz);
 
  //tcp chan stuff
  if( parser->do_chans ){
    for (int i = 0; i < parser->nchans; i ++) {

      chan[i] = chan_init( i, 3, true, false); //channel num, data type 3 (16-bit unsigned int), async, not singleval

      if( ( parser->do_chans == 2 ) || ( parser->do_chans == 3 ) ){ //open files for chandata
	sprintf(chan[i]->outfname,"chan%i.data",i);
	chan[i]->outfile = fopen(chan[i]->outfname,"w");
	if (chan[i]->outfile == NULL) {
	  fprintf(stderr,"Gerrorg. Couldn't open %s for channel %i.\n", chan[i]->outfname, chan[i]->num );
	  return(EXIT_FAILURE);
	}
	if( DEF_VERBOSE ){
	  printf("Channel %i file:\t\t%p\n", i, chan[i]->outfile );
	  printf("Channel %i filename:\t\t%s\n", i, chan[i]->outfname);
	}
	
	//tstamp files
	if( chan[i]->is_asynchr ){

	  sprintf(chan[i]->ts_fname,"chan%i_tstamps.data",i);
	  chan[i]->ts_file = fopen(chan[i]->ts_fname,"w");
	  if (chan[i]->ts_file == NULL) {
	    fprintf(stderr,"Gerrorg. Couldn't open %s for channel %i.\n", chan[i]->ts_fname, chan[i]->num );
	    return(EXIT_FAILURE);
	  }
	  if( DEF_VERBOSE ){
	    printf("Channel %i timestamp file:\t\t%p\n", i, chan[i]->ts_file );
	    printf("Channel %i timestamp filename:\t\t%s\n", i, chan[i]->ts_fname);
	  }
	}
      }
    }

    //chan buffs
    for(int i = 0; i < parser->nchans; i++){
      chanbuff[i] = malloc( chan[i]->bufsize );
      chan[i]->d.type3 = chanbuff[i];
      chan[i]->packaddr = chan[i]->d.type3;
      chan[i]->oldpackaddr = chan[i]->d.type3;
      if( chan[i]->is_asynchr ){
	chantimestamps[i] = malloc( MAXNUMSAMPS * 8);
	chan[i]->oldtstamps_addr = chan[i]->tstamps_addr = chan[i]->timestamps = chantimestamps[i];
	if( DEF_VERBOSE ) printf("tcp_fileparse.c [main()] Malloc'ed %i bytes for channel %u timestamps buffer...\n", MAXNUMSAMPS * 8, chan[i]->num );
      }
    }
    if( parser->do_chans == 3){ //doing join_upper10_lower6
      combfile = fopen(combfname,"w");
      if (combfile == NULL) {
	fprintf(stderr,"Gerrorg. Couldn't open %s.\n", combfname );
	return(EXIT_FAILURE);
      }
      if( DEF_VERBOSE ){
	printf("Combined data filename: %s\n", combfname);
	printf("Combined data file: %p\n", combfile );
      }
    }
    else {
      combfile = NULL;
    }	
  }  

  //If stripping data, set up file for stripped data
  if(parser->strip_packet == 2){
    printf("stripfname: %s\n",parser->strip_fname);
    parser->stripfile = fopen(parser->strip_fname,"w");
    printf("Stripfile: %p\n",parser->stripfile);
    if (parser->stripfile == NULL) {
      fprintf(stderr,"Gerrorg. Couldn't open stripfile %s.\n",parser->strip_fname);
      return(EXIT_FAILURE);
    }
  }

  if( DEF_VERBOSE ) print_header_memberszinfo(tcp_hdr);

  //Prediction stuff
  if(parser->do_predict){
    parser->hprediction = 0; //At the beginning, we predict that the header will be right at the beginning!
    parser->num_badp = 0;
  }

  //Start looping through file
  printf("Parsing TCP data file %s...\n",filename);
  bufsz = max_bufsz;
  int i = 0;
  int count = 0;
  running = true;
  while( ( bufcount = fread(buff, 1, bufsz, datafile) ) > 0 && running ) {
    
    printf("\n***\nBuffer #%i\n***\n",i+1);

    parser->bufrem = bufcount;
    parser->bufpos = 0;
    parser->delbytes = 0;

    while(  parser->bufpos < parser->bufrem ){

      if(parser->strip_packet) { usleep(4000); }
	else { usleep(6000); }

      parse_tcp_header(parser, buff, tcp_hdr);       //get new header_addr here

      update_after_parse_header(parser, buff, tcp_hdr);       //new hpos, bufpos, packetpos, if applicable 

    
      if( parser->parse_ok ){
	
	printf("*****Packet #%u*****\n",parser->numpackets);
	print_tcp_header(tcp_hdr);

	// Kluge stuff--total num samps
	parser->totsampcount += tcp_hdr->chan0_numsamps;
	printf("Total samples rec'd so far:\t%"PRIi64"\n", parser->totsampcount);
	//	if( DEF_VERBOSE ) print_raw_tcp_header(tcp_hdr);
	
	//Current header not where predicted?
	if( parser->do_predict) {
	  
	  if( parser->hpos != parser->hprediction ) {
	    parser->num_badp +=1;
	    printf("***Header position not where predicted by previous packet size!\n");
	    printf("***Header position relative to beginning of buffer:\t%li\n",parser->hpos);
	    printf("***Predicted position relative to beginning of buffer:\t%li\n",parser->hprediction);
	    printf("***Missed by %li bytes... Try again, Hank.\n",parser->hprediction-parser->hpos);
	  }
	  else {

	    printf("***Header %i was found where predicted: %li\n",parser->hc,parser->hprediction);
	    parser->tc +=1; //Since the prediction was correct, there must have been a tail

	  }

	  //predicted position of the next header
	  parser->hprediction = parser->hpos + tcp_hdr->pack_sz + parser->tailsz + parser->startstr_sz;

	} 	
      }	

      //Strip packet modes
      if( parser->strip_packet ){

	prep_for_strip(parser, buff, tcp_hdr); 	//determines whether there are footers to kill
	strip_tcp_packet(parser, buff, tcp_hdr); 	//do the deed

	if( parser->do_predict ) { 	//update our prediction accordingly	  
	  parser->hprediction -= ( ( (int)parser->oldtkill + (int)parser->tkill) * parser->tailsz +
				   parser->hkill * parser->hdrsz );	  
	}	
	post_strip(parser, buff, tcp_hdr); 	//finish the job	
      } //end strip_packet

      //Channel modes
      if( parser->do_chans ){

      	bool moresamps = true;      
      	long int tmp_buf_pos = parser->bufpos;

  	if( parser->parse_ok ){

	  //get new packet stuff, if applicable
	  for(int i = 0; i < parser->nchans; i++){
	    update_chans_post_parse( chan[i], tcp_hdr, parser, buff );
	    //tell me about it
	    print_chan_info( chan[i] );
	  }

	  //temp set to zero because we want everything in the buffer BEHIND the new header
	  if( parser->oldhpos < 0 ) {
	    parser->bufpos = 0; 
	  }
	  else {
	    parser->bufpos = parser->oldhpos; 
	  }
	    
	  //wrap up old channel data, which will only be here if we got a new header
	  for(int i = 0; i < parser->nchans; i++){
	    //	    if( chan[i]->oldnumsampbytes != chan[i]->oldnumbytes_received && parser->bufpos < parser->hpos  ){
	    if( ( chan[i]->oldnumsampbytes != chan[i]->oldnumbytes_received || 
		  chan[i]->oldnumtbytes != chan[i]->oldtbytes_received) && parser->bufpos < parser->hpos  ){
	      if( DEBUG ) {
		printf("tcp_fileparse.c [main()] CH%i: Doing old samples\n", i );
		printf("tcp_fileparse.c [main()] CH%i: Bufpos = %li\n", i, parser->bufpos );
		printf("tcp_fileparse.c [main()] CH%i: hpos = %li\n", i, parser->hpos );
	      }
	      get_chan_samples( chan[i], buff, parser, tcp_hdr, true);
	    }
	  }
	  if( DEBUG ) {
	    printf("tcp_fileparse.c [main()] Finished oldsamps. Bufpos should be right behind hpos!\n");
	    //	    printf("tcp_fileparse.c [main()] hpos = %li, bufpos == %li\n", parser->hpos, parser->bufpos);
	  }
	  if( (parser->bufpos += parser->tailsz ) != parser->hpos && parser->oldhpos > 0 ) {
	    printf("Channels read incorrectly!!!\n");
	    printf("tcp_fileparse.c [main()] hpos = %li, bufpos == %li\n", parser->hpos, parser->bufpos);
	  }
	  parser->bufpos =  parser->hpos + parser->hdrsz - 4; //skip header for next get_chan_samples
	}  
	  
	moresamps = true; //reset for next bit
      

	for(int j = 0; j < parser->nchans; j++ ){
	  if( moresamps ) {
	    moresamps = get_chan_samples( chan[j], buff, parser, tcp_hdr, false);
	  } else { break; }
	}
	
      	parser->bufpos = tmp_buf_pos; //set it to what it was before channels messed with it

	if( parser->do_chans > 1 ){ //time to write chan data
	  
	  int npacks_ready = 0;
	  int noldpacks_ready = 0;
	  
	  for(int i = 0; i < 2; i ++){
	    noldpacks_ready += (int) chan[i]->oldpack_ready;
	    npacks_ready += (int) chan[i]->pack_ready;
	    
	    if( DEF_VERBOSE ){ 
	      printf("Chan %i old packet ready to combine: %i\n", i, chan[i]->oldpack_ready);
	      printf("Chan %i new packet ready to combine: %i\n", i, chan[i]->pack_ready);
	    }
	  }
	  if( parser-> do_chans >= 2 ){
	    if( npacks_ready == 2 ) {
	      
	      if( parser->do_chans == 3 )combine_and_write_chandata( chan[0], chan[1], 0, parser, combfile );
	      for(int i = 0; i < 2; i ++){
		write_chan_samples( chan[i], false, parser, true );
	      }

	      if( noldpacks_ready == 2 ){
		if( parser->do_chans == 3 )combine_and_write_chandata( chan[0], chan[1], 1, parser, combfile );
		for(int i = 0; i < 2; i ++){
		  write_chan_samples( chan[i], true, parser, true );
		}
	      }
	      for( int i = 0; i < 2; i++ ) {
		clean_chan_buffer( chan[i], true );
	      }
	    }
	    else if( noldpacks_ready == 2 ){
	      if( parser->do_chans == 3 )combine_and_write_chandata( chan[0], chan[1], 1, parser, combfile );
	      for(int i = 0; i < 2; i ++){
		write_chan_samples( chan[i], true, parser, true );
		clean_chan_buffer( chan[i], false );
	      }
	    }
	    else {
	      printf ("Not all channels are prepared to do data combination!\n");
	    }
	  } //end combine channel data
	} //end write chan data
	else { //just clean up, nothing to write
	  for(int i = 0; i < parser->nchans; i++){
	    clean_chan_buffer( chan[i] , chan[i]->pack_ready );
	  }
	}	
      } //end do_chans
    
      update_end_of_loop(parser, buff, tcp_hdr);       //new bufpos, packetpos happens here
      
    } //end of current buffer

    //Update all stuff outside last buffer
    parser->total += bufcount;
    printf("Read %li bytes so far\n", parser->total);
    
    if(parser->strip_packet){

      parser->deltotal += parser->delbytes;
      printf("Killed %li bytes so far\n",parser->deltotal);
      if( parser-> strip_packet == 2 ) { 

}

      if( parser->strip_packet == 2){//Up the ante

	printf("Writing %li bytes to %s\n",parser->bufrem, parser->strip_fname);     	

	count = fwrite(buff, 1, parser->bufrem, parser->stripfile);
    	if( count == 0){
    	  printf("Gerrorg writing to %s\n",parser->strip_fname);
    	}
    	parser->wcount += count;

    	printf("count = %i\n",count);

      }
    }
    printf("Oldhpos BEFORE subtraction:\t%li\n", parser->oldhpos);
    parser->hprediction -= parser->bufrem;
    parser->oldhpos -= parser->bufrem;
    printf("Oldhpos AFTER subtraction:\t%li\n", parser->oldhpos);
    i++;

  }

  //print stats
  print_stats(parser);
  /* if( parser->do_chans ) { for(int i = 0; i < p->nchans; i++ ){ print_chan_stats(chan, p); } } */

  //Clean up shop
  if(datafile != NULL) fclose(datafile);
  free(filename);
  free(tcp_hdr);
  if( parser->do_chans ){
    for(int i = 0; i < parser->nchans; i++ ){
      /* if( ( parser->do_chans == 2 ) || ( parser->do_chans == 3 ) ){ //open files for chandata */
      /* 	free( chan[i]->outfile ); */
      /* }	 */
      //      free_chan( chan[i] );
      free( chan[i] );
    }
    //chan buffs
    /* for(int i = 0; i < parser->nchans; i++){ */
    /*   free ( chanbuff[i] ); */
    /*   if( chan[i]->is_asynchr ){ */
    /* 	free ( chantimestamps[i] ); */
    /*   } */
    /* } */
    
    
    if( parser->do_chans == 3){ //doing join_upper10_lower6
      free( combfile );
    }
  }
  //  free_parser(parser);
  free(parser);
  free(buff);
 
  return(EXIT_SUCCESS);
}
int main (int argc, char* argv[])
{
        int data_len, i, urg_recv = 0, count = 0;
        struct sockaddr socket_address;
        socklen_t sock_addr_len = sizeof(socket_address);
        unsigned char *buffer = (unsigned char*) malloc(IP_MAXPACKET);
        unsigned char *urg_msg = (unsigned char*) malloc(URG_MSG_SIZE);
        int raw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
 
        if(raw_socket < 0)
        {
                printf("Something went wrong with the socket\n");
                return 1;
        }
 
        while(1)
        {
                data_len = recvfrom(raw_socket, buffer, IP_MAXPACKET, 0, &socket_address, &sock_addr_len);             
                if(data_len < 0)
                {
                        printf("Could not parse packet\n");
                        continue;
                }
 
                count++;
                if(DEBUG >= 1)
                        printf("--Processing packet number %d--\n", count);
 
                struct iphdr *ip_header = (struct iphdr *) buffer;
                if(ip_header->protocol != IPPROTO_TCP)
                {
                        printf("Packet is not TCP protocol\n");
                        continue;
                }
 
                int th_offset = ip_header->ihl * 4;
                struct tcphdr *tcp_header = (struct tcphdr *) (buffer + th_offset);
                if(tcp_header->dest != htons(PORT))
                {
                        printf("Data was not sent to this port (%d)\n", PORT);
                        continue;
                }
 
                //The FIN flag means the transfer is complete
                if(tcp_header->fin == 1)
                {
                        break;
                }
 
                if(DEBUG >= 2)
                {
                        print_ip_header(ip_header);
                        print_tcp_header(tcp_header);
                }
 
                if(urg_recv < URG_MSG_SIZE - 1) //Since we don't know what packet contains urg_ptr data we have to use all of them
                {
                        urg_msg[urg_recv] = tcp_header->urg_ptr >> 8 & 0xFF;
                        urg_msg[urg_recv+1] = tcp_header->urg_ptr & 0xFF;
                        if(DEBUG >= 1)
                                printf("URG DATA\n%c%c",urg_msg[urg_recv], urg_msg[urg_recv+1]);
                        urg_recv += 2;
                }
 
                int tcp_data_begin = th_offset + tcp_header->doff * 4;
                int tcp_data_size = data_len - tcp_data_begin;
                if(DEBUG >= 1)
                {
                        printf("\nTCP DATA\n");
                        printf("%.*s\n\n", tcp_data_size, (char *) (buffer + tcp_data_begin));
                }
        }