网上大部分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);
}