1

I'm writing a 'C' code that stores the TCP payload of captured packets in a file (payload of each packet is separated by multiple "\n" characters). Using C, is it possible to search for a particular string in the file after all the packets are captured?

P.S : The file can be very large, depending upon the number of captured packets.

9
  • 2
    Why you want to search the file after being written, the incoming packets are being written into a buffer, I guess, can't you just search that? Commented Dec 14, 2017 at 9:36
  • Aren't your TCP packets allowed to contain multiple \n bytes in a row as payload?
    – Gerhardh
    Commented Dec 14, 2017 at 9:42
  • Errr.... yes, it is possible. Commented Dec 14, 2017 at 9:42
  • @SouravGhosh The buffer contains the entire packet (with the ethernet, ip and tcp headers) I intend to extract the URL and print it.
    – Nnn
    Commented Dec 14, 2017 at 9:51
  • @MichaelWalz Could you tell me how it is done?
    – Nnn
    Commented Dec 14, 2017 at 9:54

1 Answer 1

2

Read the file line by line and search using strstr.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
FILE * fp;
char * line = NULL;
size_t len = 0;
ssize_t read;
char * pos;
int found = -1;

fp = fopen("filename", "r");
if (fp == NULL)
    exit(EXIT_FAILURE);

while ((read = getline(&line, &len, fp)) != -1) 
   {
      pos = strstr(line,"search_string");
      if(pos != NULL)
      {
          found = 1;
          break;
      }
   }

if(found==1)
    printf("Found");
else
    printf("Not Found");

fclose(fp);

if (line)
    free(line);

exit(EXIT_SUCCESS);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.