編譯產物
hyperscan編譯完成後有如下文件
ls -R
.:
include lib64 share
./include:
hs
./include/hs:
hs_common.h hs_compile.h hs.h hs_runtime.h
./lib64:
libhs.a libhs_runtime.a pkgconfig
./lib64/pkgconfig:
libhs.pc
./share:
doc
./share/doc:
hyperscan
./share/doc/hyperscan:
examples
./share/doc/hyperscan/examples:
patbench.cc pcapscan.cc README.md simplegrep.c
include和lib64是需要的頭文件和類庫,其他是一些文檔
代碼
#include <iostream>
#include <unistd.h>
#include <vector>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
//引入hyperscan頭文件
#include "include/hs/hs.h"
using namespace std;
//匹配成功的回調函數
int record_cb(unsigned id, unsigned long long, unsigned long long to, unsigned, void *ctxt)
{
return 0;
}
int main()
{
hs_database_t *db = nullptr;
hs_compile_error_t *compile_err = nullptr;
//源數據
string data = "abcdefghijklmn";
//從文件讀取匹配規則
vector<const char*> expr;
vector<unsigned int> flags;
vector<unsigned int> ids;
FILE *fp=fopen("dict.txt", "r");
char * buf = new char[512]();
while (fgets(buf, 512, fp) != NULL)
{
buf[strlen(buf)-1]='\0';
expr.push_back(buf);
//每個匹配規則的flag設置爲0,可以自行查看有哪些flag
flags.push_back(0);
//每個匹配規則的id設置爲i,在回調函數中用來區分匹配到哪一條規則
ids.push_back(i);
buf = new char[512]();
}
//創建規則數據庫
hs_error_t err = hs_compile_multi(&expr[0], &flags[0], &ids[0], expr.size(), HS_MODE_NOSTREAM, nullptr, &db, &compile_err);
hs_scratch_t *scratch = nullptr;
err = hs_alloc_scratch(db, &scratch);
//進行匹配
err = hs_scan(db, data.c_str(), data.size(), 0, scratch, record_cb, 0);
hs_free_database(db);
err = hs_free_scratch(scratch);
return 0;
}
編譯
g++ test.cpp -lhs -Llib64
引入libhs類庫,指定引入的目錄爲lib64