使用dev_add_pack注册新的以太网类型

接着上一篇文件:使用PF_PACKET和SOCK_RAW发送自定义type以太网数据包

上一篇文章我们使用wireshare抓包,虽然在Linux下也可以使用抓包工具,但是我打算自己动手,在内核增加以太网处理类型。

先上码:

#include <linux/module.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <net/rtnetlink.h>
#include <net/netns/generic.h>
#include <linux/etherdevice.h>

#define DRV_VERSION "0.1"

const char brcm_fullname[] = "BRCM Support";
const char brcm_version[] = DRV_VERSION;
static const char brcm_copyright[] = "dean <350532197>";
static const char brcm_buggyright[] = "dean <350532197>";
void hook_func(struct sk_buff *skb)
{
    struct sk_buff *sb = skb;
    struct ethhdr *eth;
    eth=eth_hdr(sb);

    printk(KERN_INFO "SRC MAC: %pM\n",&eth->h_source);
    printk(KERN_INFO "DST MAC: %pM\n",&eth->h_dest);
    printk(KERN_INFO "MAC protocol: %04x\n",ntohs(eth->h_proto));
    printk(KERN_INFO "Date length=%d, Data=%s\n",sb->len,sb->data);
}

int brcm_skb_recv(struct sk_buff *skb, struct net_device *dev,
 struct packet_type *ptype, struct net_device *orig_dev)
{
      hook_func(skb);
kfree_skb(skb);
return NET_RX_DROP;
}

static struct packet_type brcm_packet_type __read_mostly = {
.type = cpu_to_be16(0x8874),
.func = brcm_skb_recv, /* BRCM receive method */
};

static int __init brcm_proto_init(void)
{
pr_info("%s v%s %s\n", brcm_fullname, brcm_version, brcm_copyright);
pr_info("All bugs added by %s\n", brcm_buggyright);
dev_add_pack(&brcm_packet_type);
return 0;
}

static void __exit brcm_cleanup_module(void)
{
dev_remove_pack(&brcm_packet_type);
}

module_init(brcm_proto_init);
module_exit(brcm_cleanup_module);

MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);


编译加载运行:

/tmp # insmod my_brcm.ko 
[ 8961.342368] BRCM Support v0.1 dean <350532197>
[ 8961.349598] All bugs added by dean <350532197>
/tmp # [ 8981.887476] SRC MAC: 00:15:17:28:e4:06
[ 8981.891233] DST MAC: 00:0b:82:27:fd:e4
[ 8981.894999] MAC protocol: 8874
[ 8981.898057] Date length=46, Data=hello world!

客户端使用使用PF_PACKET和SOCK_RAW发送自定义type以太网数据包编译出来的软件发送helloworld。

可以看出,此模块正确获取到数据包。


感谢yoyo的文章Linux内核实践 - 如何添加网络协议

http://blog.csdn.net/qy532846454/article/details/6627536

你可能感兴趣的:(SOCK_RAW,PF_PACKET)