netfilter例子改写3

本文提供了一个Linux内核模块示例,该模块通过netfilter框架拦截并丢弃来自特定IP地址的数据包。具体实现包括定义钩子函数以检查数据包源IP,并在匹配预设IP时将其丢弃。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

netfilter test examples are for linux 2.4. Now these examples are rewrite on linux kernel 3.2.19
filter_srcip.c
--------------Begin------------------------------------------
/* Sample code to install a Netfilter hook function that will
 * drop all incoming packets from an IP address we specify */

#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/skbuff.h>
#include <linux/ip.h>                  /* For IP header */
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>

/* This is the structure we shall use to register our function */
static struct nf_hook_ops nfho;

/* IP address we want to drop packets from, in NB order */

/* 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 *))
{
    struct iphdr *ip1 = NULL;
    if (!skb){
        return NF_ACCEPT;
    }
    ip1 = ip_hdr(skb);
    if (NULL != ip1){
        if (ip1->daddr == 0x100007f ){
            printk("loopback,drop\n");
            return NF_DROP;
        }
    }else{
        printk("null!\n");
    }
    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 for IPv4 */
   nfho.pf       = PF_INET;
   nfho.priority = NF_IP_PRI_FIRST;   /* Make our func first */
   printk("init_module,filter_srcip\n");
   nf_register_hook(&nfho);

   return 0;
}

/* Cleanup routine */
void cleanup_module()
{
    printk("cleanup_module,filter_srcip\n");
    nf_unregister_hook(&nfho);
}
----------------------End---------------------------
Makefile
----------------------Begin-------------------------
ifneq ($(KERNELRELEASE),)
mymodule-objs:=filter_srcip.o
obj-m:=filter_srcip.o
else
PWD:=$(shell pwd)
KVER:=$(shell uname -r)

#KDIR:=/usr/src/linux-source-2.6.32/
KDIR:=/usr/src/linux-source-3.2.0/linux-source-3.2.0
all:
        $(MAKE) -C $(KDIR) M=$(PWD)
clean:
        @rm -rf .*.com *.o *.mod.c *.ko .tmp_versions modules.order Module.symvers
install:
        @insmod filter_srcip.ko
uninstall:
        @rmmod filter_srcip.ko
endif
----------------------End---------------------------
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

mounter625

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值