现在的位置: 首页 > 综合 > 正文

linux netlink简单配置使用

2018年03月18日 ⁄ 综合 ⁄ 共 1314字 ⁄ 字号 评论关闭

内核模块

#include <linux/init.h>

#include <linux/module.h>
#include <linux/kernel.h>
  
//#include <linux/netlink.h>
//#include <net/netlink.h>
//#include <linux/socket.h>
#include <net/sock.h> 

#define NL_TEST 21
#define MYPAYLOAD  NLMSG_ALIGN(100)

extern struct net init_net;
struct sock *sock = NULL;
unsigned int pid;

void NL_kernel_send(void)
{
struct sk_buff *skb_send = NULL;
struct nlmsghdr *nlh_send = NULL;
int ret;
char *buf = "kernel recv ok!";
 
skb_send = alloc_skb(NLMSG_SPACE(MYPAYLOAD ), GFP_ATOMIC);
if (NULL == skb_send){
printk("alloc_skb fail\n");
return ;
}

nlh_send = nlmsg_put(skb_send, 0, 0, 0, MYPAYLOAD, 0);

NETLINK_CB(skb_send).pid = 0;
//NETLINK_CB(skb_send).dst_pid = pid;
NETLINK_CB(skb_send).dst_group = 0;

memcpy(NLMSG_DATA(nlh_send), buf, sizeof(buf));   

ret = netlink_unicast(sock, skb_send, pid, MSG_DONTWAIT);  
if (ret < 0) {
 printk(KERN_ERR "net_link: can not unicast skb \n");
 return ;
}
printk("net_link: send is ok.\n");
 
return ;
}

void NL_kernel_recv(struct sk_buff * skb)
{
    struct nlmsghdr *nlh = NULL;

    skb_get(skb); 
  
    nlh = nlmsg_hdr(skb); 
 
    pid = nlh->nlmsg_pid;
    
    kfree_skb(skb); 
    
    NL_kernel_send();
 
}

int netlink_init(void)
{
sock = netlink_kernel_create(&init_net, NL_TEST, 0, NL_kernel_recv, 0, THIS_MODULE);

return 0;
}

void netlink_exit(void)
{
sock_release(sock->sk_socket);
}

module_init(netlink_init);  
module_exit(netlink_exit); 
 
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("PFFW");
MODULE_AUTHOR("PFFW"); 

抱歉!评论已关闭.