hturner
hturner

Reputation: 235

Count how many times an IP number appears in a text file - C Program

I have a log file of 10 hits e.g. one line is:

127.0.0.1 - - [10/Oct/2007:13:55:36 ­0700]"GET /index.html HTTP/1.0" 200 2326 "http://www.example.com/links.html" "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322)"

The format of each line is the same i.e. the IP address is always at the start.

I've currently read in the file using fopen and fgets but now I want to count how many unique IPs there are in the file, as well as count how many times an IP 'hits'. Not sure how I would attempt this.. Any tips on how I would go about doing this?

Upvotes: -1

Views: 458

Answers (1)

chux
chux

Reputation: 154243

Code can march though the file looking for the ddd.ddd.ddd.ddd pattern.

Avoided use "%d" or "%u" as they accept leading spaces, and '-' and '+'.

Pseudo code

Read from a file until EOF found
  repeatedly look for a digit
  if it is found
    note position
    put digit back into stream
    look for ddd.ddd.ddd.ddd
    if found
      decode (and test for values > 255)
      if successful return result
    go back to position

return fail value;

Sample code. Should also have IO error checking.

unsigned long Parse_IP(FILE *inf) {
  int ch;
  for ((ch = fgetc(inf)) != EOF) {
    if (isdigit(ch)) {
      long pos = ftell(inf);
      ungetc(ch, inf);
      char buf[4][4];
      int count = fscanf(inf, "%3[0-9].%3[0-9].%3[0-9].%3[0-9]", 
          buf[0], buf[1], buf[2], buf[3]);
      if (count == 4) {
        unsigned long ip = 0;  
        int i;
        for (i=0; i<4; i++) {
          int digit = atoi(buf[i]);
          if (digit > 255) break;
          ip = ip*256 + digit;
        }
        if (i == 4) return ip;  
      }
      fseek(inf, pos, SEEK_SET);
    }
  }
  return 0;
}

Sample usage

unsigned long ip;
while ((ip = Parse_IP(inf)) != 0) {
  printf("ip %08lX\n", ip);
}

Upvotes: 2

Related Questions