感觉上一个例子过于简单,再来一个带判断条件的、并简单操作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` cleaninstall:
/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