Chinaunix首页 | 论坛 | 博客
  • 博客访问: 87037
  • 博文数量: 10
  • 博客积分: 2055
  • 博客等级: 大尉
  • 技术积分: 370
  • 用 户 组: 普通用户
  • 注册时间: 2007-03-30 16:59
文章分类
文章存档

2011年(1)

2008年(9)

我的朋友

分类: LINUX

2008-04-17 13:08:18


    here the method list :

1. Procfs
2. Device Driver
3. Netlink Socket
4. Sysctl
5. System Call
6. Others (e.g. VFS)


here is one example of using socket to communicate with kernel:


//sockopt.h


#ifndef _SOCKOPT_
#define _SOCKOPT_

#define MY_SOCKOPT 5000

#endif



//sockopt.c


#include<linux/kernel.h>
#include<linux/module.h>
#include<linux/netfilter.h>
#include"sockopt.h"


static int my_set(struct sock *sk, int optval, void *user, unsigned int len)
{
        printk("my set: sk=%d, optval=%d, user=%s, len=%d\n", (int)sk, optval, (char *)user, len);
        return 0;
}

static int my_get(struct sock *sk, int optval, void *user, int *len)
{
        printk("my get: sk=%d, optval=%d\n", (int)sk, optval);
        strcpy((char *)user, "hahaha");
        *len = 7;
        return 0;
}

static struct nf_sockopt_ops my_sockopt=
{
        {NULL, NULL},
        PF_INET,
        MY_SOCKOPT, MY_SOCKOPT + 1, my_set,
        MY_SOCKOPT, MY_SOCKOPT + 1, my_get,
        0,
        NULL
};

static int __init init(void)
{
        int ret;
        ret = nf_register_sockopt(&my_sockopt);
        if(ret !=0 )
        {
                printk("Can not register\n");
        }
        return ret;
}

static void __exit tini(void)
{
        nf_unregister_sockopt(&my_sockopt);
}

module_init( init );
module_exit( tini );
MODULE_LICENSE( "GPL" );



//test.c


#include"sockopt.h"
#include<sys/socket.h>
#include<stdio.h>
#include<sys/types.h>
#include<linux/in.h>

int main()
{
        int sk;
        int len;
        int ret;
        char buf[64] = "gogo";
        sk = socket(PF_INET, SOCK_STREAM, 0);
        if(sk < 0)
        {
                printf("create error\n");
                return -1;
        }
        ret = setsockopt(sk, IPPROTO_IP, MY_SOCKOPT, buf, strlen( buf ));
        printf("setsockopt:%d sk=%d\n", ret, sk);
        len = sizeof(buf);
        ret = getsockopt(sk, IPPROTO_IP, MY_SOCKOPT, buf, &len);
        printf("getsockopt:%d, sk=%d, buf=%s, len=%d\n", ret, sk, buf, len);
        return 0;
}



#makefile
all:sockopt.o test

sockopt.o:sockopt.c
        gcc -D__KERNEL__ -I/usr/src/linux/include -Wall -Wstrict-prototypes -Wno-trigraphs -O2 -fno-strict-aliasing -fno-common -pipe -mpreferred-stack-boundary=2 -march=i586 -DMODULE -DMODVERSIONS -include /usr/src/linux/include/linux/modversions.h -nostdinc -iwithprefix include -c -o $@ $^

test:test.c
        gcc test.c -o test



1, touch these files and run make
2, insert kernel module. "insmod sockopt.o"
3, run user space testing program. "./test"
4, remove kernel module. "rmmod sockopt"

阅读(764) | 评论(0) | 转发(0) |
0

上一篇:Vmalloc notice

下一篇:[HOWTO]mmap driver

给主人留下些什么吧!~~