hyperscan使用

编译产物

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

posted @ 2023-08-10 14:41  秋来叶黄  阅读(224)  评论(0编辑  收藏  举报