下面是一个基于Netfilter的forward hook的例子:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <linux/ip.h>
static struct nf_hook_ops nfho;
/* This function will be called for each incoming packet */
unsigned int hook_func(void *priv, struct sk_buff *skb, const struct nf_hook_state *state) {
struct iphdr *iph;
/* Get the IP header of the incoming packet */
iph = ip_hdr(skb);
/* Check if the packet is an IPv4 packet */
if (iph->version == 4) {
/* If it's an IPv4 packet, drop it */
printk(KERN_INFO "Dropping IPv4 packet from %d.%d.%d.%d to %d.%d.%d.%d\n",
NIPQUAD(iph->saddr), NIPQUAD(iph->daddr));
return NF_DROP;
}
/* If the packet is not IPv4, let it pass */
return NF_ACCEPT;
}
int init_module() {
/* Register the hook function */
nfho.hook = hook_func;
nfho.pf = PF_INET; /* IPv4 */
nfho.hooknum = NF_INET_FORWARD; /* Hook into the forward chain */
nfho.priority = NF_IP_PRI_FIRST; /* Set the highest priority */
nf_register_hook(&nfho);
printk(KERN_INFO "netfilter forward hook loaded\n");
return 0;
}
void cleanup_module() {
/* Unregister the hook function */
nf_unregister_hook(&nfho);
printk(KERN_INFO "netfilter forward hook unloaded\n");
}