基于2.6.23.1内核,用netfilter抓包,并且用proc文件输出,实现源码
#include <linux/module.h> /* Specifically, a module */
#include <linux/kernel.h> /* We're doing kernel work */
#include <linux/proc_fs.h>
#include <linux/netfilter.h>
#include <linux/netfilter_ipv4.h>
#include <linux/types.h>
#include <linux/if_ether.h>
#include<linux/tcp.h>
#include<linux/ip.h>
#include <linux/skbuff.h>
#define IP 0x800
#define TCP 0x6
/* Necessary because we use the proc fs */
#define procfs_name "port"
char *buf;
struct nf_hook_ops nfho;
struct proc_dir_entry *Our_Proc_File;
int len=0;
unsigned int
hook_func (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 *iph;
struct tcphdr *tcp;
struct sk_buff *SKB;
int ips[4],ipd[4];
SKB = *skb;
len = 0;
eth = (struct ethhdr *) SKB->mac_header;
iph = (struct iphdr *) SKB->network_header;
tcp = (struct tcphdr *) SKB->transport_header;
if (ntohs (eth->h_proto) == IP)
{
if (iph->protocol == TCP)
{
len += sprintf(buf + len, "smac = %02x:%02x:%02x:%02x:%02x:%02x\n", eth->h_source[0],eth->h_source[1],eth->h_source[2],eth->h_source[3],eth->h_source[4],eth->h_source[5]);
len += sprintf(buf + len, "dmac = %02x:%02x:%02x:%02x:%02x:%02x\n", eth->h_dest[0],eth->h_dest[1],eth->h_dest[2],eth->h_dest[3],eth->h_dest[4],eth->h_dest[5]);
len += sprintf(buf + len, "dip = %u.%u.%u.%u\n", NIPQUAD(iph->daddr));
len += sprintf(buf + len, "sip = %u.%u.%u.%u\n", NIPQUAD(iph->daddr));
len += sprintf(buf + len, "sport = %d \n",ntohs(tcp -> source));
len += sprintf(buf + len, "dport = %d \n",ntohs(tcp -> dest));
}
}
return NF_ACCEPT;
}
int
procfile_read (char *buffer,
char **buffer_location,
off_t offset, int buffer_length, int *eof, void *data)
{
memcpy(buffer,buf,len);
return len;
}
int
init_module ()
{
buf = kmalloc(1024,GFP_KERNEL);
nfho.hook = hook_func; /* 处理函数 */
nfho.hooknum = NF_IP_PRE_ROUTING; /* 使用IPv4的第一个hook */
nfho.pf = PF_INET;
nfho.priority = NF_IP_PRI_FIRST; /* 让我们的函数首先执行 */
nf_register_hook (&nfho);
Our_Proc_File = create_proc_entry (procfs_name, 0644, NULL);
Our_Proc_File->read_proc = procfile_read;
Our_Proc_File->owner = THIS_MODULE;
Our_Proc_File->mode = S_IFREG | S_IRUGO;
Our_Proc_File->uid = 0;
Our_Proc_File->gid = 0;
Our_Proc_File->size = 37;
return 0; /* everything is ok */
}
void
cleanup_module ()
{
kfree(buf);
nf_unregister_hook (&nfho);
remove_proc_entry (procfs_name, &proc_root);
}
makefile代码:
ifeq ($(KERNELRELEASE),)
KERNELDIR ?= /lib/modules/$(shell uname -r)/build
PWD := $(shell pwd)
modules:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
modules_install:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules_install
clean:
rm -rf *.o *~ core .depend .*.cmd *.ko *.mod.c .tmp_versions
.PHONY: modules modules_install clean
else
# called from kernel build system: just declare what our modules are
obj-m := proc.o
endif
作者“programmer”
补充:软件开发 , C语言 ,