2.6.30内核Netfilter的简单例子、二(DropLo)

66 篇文章 0 订阅

感觉上一个例子过于简单,再来一个带判断条件的、并简单操作sk_buff:丢弃所有来自环路设备的数据包,drop lo。国际惯例,先贴代码:

1、源代码:dropLo.c

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/skbuff.h>
#include <linux/ip.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <linux/netdevice.h>

MODULE_LICENSE("GPL");

/* This is the structure we shall use to register our function */
    static struct nf_hook_ops nfho;
    static char *drop_if = "lo";

    /* This is the hook function itself */
    unsigned int hook_func(unsigned int hooknum,
                           struct sk_buff *skb,
                           const struct net_device *in,
                           const struct net_device *out,
                           int (*okfn)(struct sk_buff *))
    {
        pr_info("Packet FROM.../n");
        if (strcmp(in->name, drop_if) == 0) {
            printk("Dropped packet on %s...n", drop_if);
            return NF_DROP;
        } else {
            return NF_ACCEPT;
        }
    }

    /* Initialisation routine */
    int init_module()
    {
        /* Fill in our hook structure */
        nfho.hook     = hook_func;         /* Handler function */
        nfho.hooknum  = NF_INET_PRE_ROUTING; /* First hook for IPv4 */
        nfho.pf       = PF_INET;
        nfho.priority = NF_IP_PRI_FIRST;   /* Make our function first */

        nf_register_hook(&nfho);

        pr_info("dropLo install into kernel!/n");
        return 0;
    }
            /* Cleanup routine */
    void cleanup_module()
    {
        nf_unregister_hook(&nfho);
        pr_info("dropLo removed from kernel!/n");
    }

2、Makefile:

 

obj-m +=dropLo.o
all:
  make -C /lib/modules/`uname -r`/build M=`pwd`
clean:
  make -C /lib/modules/`uname -r`/build M=`pwd` clean

install:
        /sbin/insmod dropLo.ko
remove:
        /sbin/rmmod dropLo

3、注意 :和上一个例子相比,多添加了一个头文件:include   <linux/netdevice.h>

4、编译模块:

make

5、安装模块:

make install

6、测试:

ping 127.0.0.1

发现ping不通吧,哈哈。在ping其他地址,如网关,则可以。

7、卸载模块:

make remove

8、下载 http://download.csdn.net/source/1651549

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值