By liran bh | 2/27/2017 | Linux Kernel & Internals

Netfilter

This example shows how to create a network filter in IPv4. We can add filters in 5 points: input flow before and after routing, output flow before and after routing and while forwarding a packat from one adapter to another

#include <linux/module.h>
#include <linux/skbuff.h>          
#include <linux/init.h>
#include <net/sock.h>
#include <linux/inet.h>
#include <linux/ip.h>             
#include <linux/kernel.h> 
#include <linux/netfilter.h>
#include <uapi/linux/netfilter_ipv4.h> 

 
unsigned int main_hook(unsigned int hooknum,
                       struct sk_buff *skb,
                       const struct net_device *in,
                       const struct net_device *out,
                       int (*okfn)(struct sk_buff*))
{
    struct iphdr *iph;
 
    iph = ip_hdr(skb);
    if(iph->saddr == in_aton("192.168.0.2"))
    { 
        return NF_DROP; 
    }
    return NF_ACCEPT;
}

static struct nf_hook_ops netfops;                    

int __init my_module_init(void)
{
    netfops.hook              =       main_hook;
    netfops.pf                =       PF_INET;        
    netfops.hooknum           =       0;
    netfops.priority          =       NF_IP_PRI_FIRST;
    nf_register_hook(&netfops);
 
    return 0;
}
void __exit my_module_exit() 
{ 
    nf_unregister_hook(&netfops); 
}
 
module_init(my_module_init);
module_exit(my_module_exit);
MODULE_LICENSE("GPL");

 

After adding the module (insmod) it will drop any package from ip 192.168.0.2

Note that you need to enable netfilter suppot in the kernel configuration

 

{{CommentsModel.TotalCount}} Comments

Your Comment

{{CommentsModel.Message}}

Recent Stories

Top DiscoverSDK Experts

User photo
3355
Ashton Torrence
Web and Windows developer
GUI | Web and 11 more
View Profile
User photo
3220
Mendy Bennett
Experienced with Ad network & Ad servers.
Mobile | Ad Networks and 1 more
View Profile
User photo
3060
Karen Fitzgerald
7 years in Cross-Platform development.
Mobile | Cross Platform Frameworks
View Profile
Show All
X

Compare Products

Select up to three two products to compare by clicking on the compare icon () of each product.

{{compareToolModel.Error}}

Now comparing:

{{product.ProductName | createSubstring:25}} X
Compare Now