在编写linux内核中的网络模块时,用到了钩子函数也就是hook函数。现在来看看linux是如何实现hook函数的。


    先介绍一个结构体:

    struct nf_hook_ops,这个结构体是实现钩子函数必须要用到的结构体,其实际的定义为:

    linux内核中的hook函数详解_钩子

  其中的成员信息为:

      hook  :是一个函数指针,可以将自定义的函数赋值给它,来实现当有数据包到达是调用你自定义的函数。自定义函数的返回值为:

     linux内核中的hook函数详解_linux_02


     owner:是模块的所有者,一般owner = THIS_MODULE ;

    pf   :是protocol flags,其取值范围为:

     linux内核中的hook函数详解_钩子_03

     

      hooknum :中存放的是用户自定义的钩子函数的调用时机,其取值为:

      linux内核中的hook函数详解_钩子_04    

      其中的每个值的含义为:

      linux内核中的hook函数详解_linux_05

     priority : 为所定义的钩子函数的优先级,其取值为份两种:分别为IPV4 和 IPV6; 

    priority 的IPV4取值为:      

linux内核中的hook函数详解_linux_06

     priority 的IPV6取值为:

    linux内核中的hook函数详解_函数_07



    以上是对struct nf_hook_ops结构体中的每个字段的详解;

    现在举例:

    struct nf_hook_ops  my_hook = {
            .hook = myfunction,
            
            .owner = THIS_MODULE ,
            
            .pf = NFPROTO_IPV4,
            
            .hooknum = NET_INET_FORWARD ,
            
            .priority = NF_IP4_PRI_FIRST };
            
    unsigned int myfunction( unsigend int hooknum,  struct sk_buff *skb,
                             const struct net_device *in,
                             const struct net_device *out,
                             int (*okfn)(struct sk_buff *) )
    {
    
    }


    如上面的代码一样,当定义一个struct nf_hook_ops结构体,并且对其完成了初始化以后,需要将这个结构体进行注册,之后这个结构体以及其中的自定义函数才会其作用。

   

    注册一个struct nf_hook_ops需要用到的函数为:

    int  nf_register_hook( struct nf_hook_ops *reg )

   其实这个 int nf_register_hook()函数在内核中的实现也没有多么的复杂,

来看看它是如何实现的:

    linux内核中的hook函数详解_钩子_08


     当不再需要使用这个struct nf_hook_ops时,需要注销这个结构体,其可用的函数为:

     void nf_unregister_hook( struct nf_hook_ops *reg )

   linux内核中的hook函数详解_函数_09


    当一次需要注册多个struct nf_hook_ops结构体,如:

     struct nf_hook_ops myhooks[n]时,使用:

    int nf_register_hooks( struct nf_hook_ops *regs, unsigned int n );

linux内核中的hook函数详解_函数_10


     同样,当一次需要注销多个struct nf_hook_ops结构体是,使用:

     void nf_unregister_hoos( struct nf_hook_ops *regs, unsigned int n );

     linux内核中的hook函数详解_linux_11



     总结:

           struct nf_hook_ops

           int nf_register_hook( struct nf_hook_ops *reg );

           void nf_unregister_hook( struct nf_hook_ops *reg );

           int nf_register_hooks( struct nf_hook_ops *regs, unsigend int n );

           void nf_unregister_hooks( struct nf_hook_ops *regs, unsigned int n );