netfilter的例子 支持新版本内核

网上大部分netfilter例子已经失效了

本例子兼容内核版本大于4.15及以上版本的

针对 UDP包进行过滤:

     //’Hello World’ v2 netfilter hooks example
    //For any packet, get the ip header and check the protocol field
    //if the protocol number equal to UDP (17), log in var/log/messages
    //default action of module to let all packets through
     
    #include <linux/kernel.h>
    #include <linux/module.h>
    #include <linux/netfilter.h>
    #include <linux/netfilter_ipv4.h>
    #include <linux/skbuff.h>
    #include <linux/udp.h>
    #include <linux/ip.h>
     
    static struct nf_hook_ops nfho;   //net filter hook option struct
    struct udphdr *udp_header;          //udp header struct (not used)
    struct iphdr *ip_header;            //ip header struct

unsigned int sample_nf_hoofn(void *priv, struct sk_buff *skb, const struct nf_hook_state *state)
{
	ip_header = (struct iphdr *)skb_network_header(skb);

	if(ip_header->protocol == 17)
	{
		udp_header = (struct udphdr *)skb_transport_header(skb);
//		printk(KERN_INFO "got udp packet \n");
		return NF_DROP;
	}

	return NF_ACCEPT;
}
     
    int init_module()
    {
            nfho.hook = sample_nf_hoofn;
            nfho.hooknum = NF_INET_PRE_ROUTING;
            nfho.pf = PF_INET;
            nfho.priority = NF_IP_PRI_FIRST;
     
            nf_register_net_hook(&init_net, &nfho);
           
            return 0;
    }
     
    void cleanup_module()
    {
            nf_unregister_net_hook(&init_net, &nfho);     
    }
     
 

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值