- 论坛徽章:
- 0
|
附上代码:
#include <linux/module.h>
#include <linux/init.h>
#include <linux/types.h>
#include <linux/socket.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <linux/skbuff.h>
#include <linux/inet.h>
#include <linux/ip.h>
#include <linux/tcp.h>
#include <net/tcp.h>
#include <linux/udp.h>
#include <linux/netdevice.h>
MODULE_LICENSE("GPL");
MODULE_AUTHOR("bbo");
static struct nf_hook_ops g_hnf;
unsigned int forwardData(unsigned int hooknum,
struct sk_buff *__skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
struct sk_buff *skb = NULL;
struct iphdr *iph = NULL;
struct tcphdr *tcph = NULL;
int iph_len = 0, tcph_len = 0;
unsigned char *payload = NULL;
skb = __skb;
iph = ip_hdr(skb) - 1;
if (!skb || !iph )
return NF_ACCEPT;
if (skb->len < 20)
return NF_ACCEPT;
if (iph->version != 4)
return NF_ACCEPT;
iph_len = iph->ihl * 4;//ip_hdrlen(skb);
if (skb->protocol != htons(ETH_P_IP))
printk("skb->protocol:%d\n", ntohs(skb->protocol));
if (iph->protocol == IPPROTO_TCP)
{
if (skb->pkt_type != 0)
printk("pkt_type=%d\n", skb->pkt_type);
return NF_ACCEPT;
unsigned int sip = (unsigned int)iph->saddr;
unsigned int dip = (unsigned int)iph->daddr;
tcph = (struct tcphdr*)((unsigned char*)iph + iph->ihl * 4);
tcph_len = tcph->doff * 4;
unsigned short sport = 0, dport = 0;
sport = ntohs(tcph->source);
dport = ntohs(tcph->dest);
printk("<0>source ip:%d.%d.%d.%d\n", sip & 0x000000ff, (sip & 0x0000ff00) >> 8, (sip & 0x00ff0000) >> 16, (sip & 0xff000000) >> 24 );
printk("<0>dest ip:%d.%d.%d.%d\n", dip & 0x000000ff, (dip & 0x0000ff00) >> 8, (dip & 0x00ff0000) >> 16, (dip & 0xff000000) >> 24 );
printk("<0>source port:%d, dest port:%d\n", sport, dport);
return NF_ACCEPT;
}
else if (iph->protocol == IPPROTO_UDP)
{
return NF_ACCEPT;
}
return NF_ACCEPT;
}
static int __init filter_init(void)
{
printk("<0>init filter feature");
g_hnf.hooknum = NF_INET_PRE_ROUTING;//NF_INET_LOCAL_IN;
g_hnf.priority = NF_IP_PRI_MANGLE;
g_hnf.pf = PF_INET;
g_hnf.hook = forwardData;
int ret = nf_register_hook(&g_hnf);
if (ret < 0)
{
printk("<0>netfilter register failed!\n");
return ret;
}
return 0;
}
static void __exit filter_exit(void)
{
printk("<0>exit module");
nf_unregister_hook(&g_hnf);
}
module_init(filter_init);
module_exit(filter_exit); |
|