用户进程与内核进程通信netlink

用户进程与内核进程通信netlink

为了方便应用程序使用netlink接口,一个叫libnl库被开发.

1 下载libnl2 

http://packages.ubuntu.com/oneiric/libnl2

2 下载libnl2-dev

http://packages.ubuntu.com/precise/libnl2-dev

3 先安装libnl2 在安装libnl2-dev

 

应用层代码

 

#include <stdio.h>

#include <stdlib.h>

 

#include <netlink/netlink.h>

 

#define MY_MSG_TYPE (0x10 + 2)  // + 2 is arbitrary but is the same for kern/usr

int

main(int argc, char *argv[])

{

    struct nl_sock *nls;

    char msg[] = { 0xde, 0xad, 0xbe, 0xef, 0x90, 0x0d, 0xbe, 0xef };

    int ret;

 

    nls = nl_socket_alloc();

    if (!nls) {

       printf("bad nl_socket_alloc\n");

       return EXIT_FAILURE;

    }

 

    ret = nl_connect(nls, NETLINK_USERSOCK);

    if (ret < 0) {

       nl_perror(ret, "nl_connect");

       nl_socket_free(nls);

       return EXIT_FAILURE;

    }

 

    ret = nl_send_simple(nls, MY_MSG_TYPE, 0, msg, sizeof(msg));

    if (ret < 0) {

       nl_perror(ret, "nl_send_simple");

       nl_close(nls);

       nl_socket_free(nls);

       return EXIT_FAILURE;

    } else {

       printf("sent %d bytes\n", ret);

    }

 

    nl_close(nls);

   nl_socket_free(nls);

 

    return EXIT_SUCCESS;

}

 

内核代码

 

#include <linux/kernel.h>

#include <linux/module.h>

 

#include <net/sock.h>

#include <net/netlink.h>

 

#define MY_MSG_TYPE (0x10 + 2)  // + 2 is arbitrary. same value for kern/usr

 

static struct sock *my_nl_sock;

 

DEFINE_MUTEX(my_mutex);

 

static int

my_rcv_msg(struct sk_buff *skb, struct nlmsghdr *nlh)

{

    int type;

    char *data;

 

    type = nlh->nlmsg_type;

    if (type != MY_MSG_TYPE) {

       printk("%s: expect %#x got %#x\n", __func__, MY_MSG_TYPE, type);

       return -EINVAL;

    }

 

    data = NLMSG_DATA(nlh);

    printk("%s: x x x x x x x x\n", __func__,

           data[0], data[1], data[2], data[3],

           data[4], data[5], data[6], data[7]);

    return 0;

}

 

static void

my_nl_rcv_msg(struct sk_buff *skb)

{

   mutex_lock(&my_mutex);

    netlink_rcv_skb(skb, &my_rcv_msg);

   mutex_unlock(&my_mutex);

}

 

static int

my_init(void)

{

    my_nl_sock = netlink_kernel_create(&init_net, NETLINK_USERSOCK, 0,

          my_nl_rcv_msg, NULL, THIS_MODULE);

    if (!my_nl_sock) {

       printk(KERN_ERR "%s: receive handler registration failed\n", __func__);

       return -ENOMEM;

    }

 

    return 0;

}

 

static void

my_exit(void)

{

    if (my_nl_sock) {

       netlink_kernel_release(my_nl_sock);

    }

}

 

module_init(my_init);

module_exit(my_exit);

系统:ubuntu 10.04 ,内核: linux-2.6.38
编译应用层代码需要加入动态链接库 /usr/lib/libnl.so
即sudo gcc -o 1 1.c /usr/lib/libnl.so

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值