How to capture network frames in the kernel module

I want to capture frames when they are received by a specific network adapter; extract some information from them (currently I need to capture the source MAC address and source IP addresses); save this information in some public data structure; and let the frame go up the TCP / IP stack.

I used Netfilter before, but apparently it does not provide link level bindings.
I can do it?

I write this as a kernel module; running Linux kernel 2.6.32

+5
source share
1 answer

Netfilter , ( sk_buff, Link). , . MAC- src src IP.

static struct nf_hook_ops nfin;

static unsigned int hook_func_in(unsigned int hooknum,
            struct sk_buff *skb,
                            const struct net_device *in,
                            const struct net_device *out,
                            int (*okfn)(struct sk_buff *))
{
    struct ethhdr *eth;
    struct iphdr *ip_header;
    /* check *in is the correct device */
    if (in is not the correct device)
          return NF_ACCEPT;         

    eth = (struct ethhdr*)skb_mac_header(skb);
    ip_header = (struct iphdr *)skb_network_header(skb);
    printk("src mac %pM, dst mac %pM\n", eth->h_source, eth->h_dest);
    printk("src IP addr:=%d.%d.%d.%d:%d\n", NIPQUAD(ip_headr->saddr));
    return NF_ACCEPT;
}

static int __init init_main(void)
{
    nfin.hook     = hook_func_in;
    nfin.hooknum  = NF_IP_LOCAL_IN;
    nfin.pf       = PF_INET;
    nfin.priority = NF_IP_PRI_FIRST;
    nf_register_hook(&nfin);

    return 0;
}



static void __exit cleanup_main(void)
{
    nf_unregister_hook(&nfin);
}
module_init(init_main);
module_exit(cleanup_main);
+6

All Articles