-1

10 ヒットのログ ファイルがあります。たとえば、1 行は次のとおりです。

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)"

各行の形式は同じです。つまり、IP アドレスは常に先頭にあります。

現在、fopen と fgets を使用してファイルを読み込んでいますが、ファイル内にある一意の IP の数と、IP が「ヒット」した回数をカウントしたいと考えています。これをどのように試みるかわかりません..これを行う方法に関するヒントはありますか?

4

1 に答える 1

2

コードは、ddd.ddd.ddd.ddd パターンを探してファイルを移動できます。

"%d"or"%u"は先頭のスペースを受け入れるため、 and の'-'使用は避けて'+'ください。

疑似コード

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;

サンプルコード。IO エラー チェックも必要です。

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;
}

使用例

unsigned long ip;
while ((ip = Parse_IP(inf)) != 0) {
  printf("ip %08lX\n", ip);
}
于 2015-11-24T23:34:48.913 に答える