Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
A simple kernel module that printk's "Hello, packet" when it intercepts a packet. Uses netfilter.
#include <linux/module.h> // included for all kernel modules
#include <linux/kernel.h> // included for KERN_INFO
#include <linux/init.h> // included for __init and __exit macros
#include <linux/netfilter.h>
#include <linux/vmalloc.h>
//#undef __KERNEL__
#include <linux/netfilter_ipv4.h>
//#define __KERNEL__
MODULE_AUTHOR("Julia Evans");
MODULE_DESCRIPTION("Hello, packet!");
static struct nf_hook_ops nfho; //net filter hook option struct
unsigned int my_hook(unsigned int hooknum,
struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *)) {
struct sock *sk = skb->sk;
printk("Hello packet!");
return NF_ACCEPT;
static int init_filter_if(void)
nfho.hook = my_hook;
nfho.hooknum = 0 ; //NF_IP_PRE_ROUTING; = PF_INET;
nfho.priority = NF_IP_PRI_FIRST;
return 0;
static int __init hello_init(void)
printk(KERN_INFO "Hello world!\n");
return 0; // Non-zero return means that the module couldn't be loaded.
static void __exit hello_cleanup(void)
printk(KERN_INFO "Cleaning up module.\n");
obj-m += hello-packet.o
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) modules
make -C /lib/modules/$(shell uname -r)/build M=$(PWD) clean

This comment has been minimized.

Show comment Hide comment

nkapliev Jul 23, 2017

Julia, thank you for the code!

Julia, thank you for the code!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment