Linux的netlink机制是非常好的Linux内核与应用层进行双向交互数据的方式。其常用的单播方式可以实现内核为服务端,应用层为客户端的通信方式。如果需要实现应用层为服务端,内核为客户端的通信方式,则需要使用组播。这种场景一般是应用层守护进程需要实现获取内核的某些模块的状态信息。
内核中已经定义好的组有:
#define NETLINK_ROUTE 0 /* Routing/device hook */
#define NETLINK_W1 1 /* 1-wire subsystem */
#define NETLINK_USERSOCK 2 /* Reserved for user mode socket protocols */
#define NETLINK_FIREWALL 3 /* Firewalling hook */
#define NETLINK_INET_DIAG 4 /* INET socket monitoring */
#define NETLINK_NFLOG 5 /* netfilter/iptables ULOG */
#define NETLINK_XFRM 6 /* ipsec */
#define NETLINK_SELINUX 7 /* SELinux event notifications */
#define NETLINK_ISCSI 8 /* Open-iSCSI */
#define NETLINK_AUDIT 9 /* auditing */
#define NETLINK_FIB_LOOKUP 10
#define NETLINK_CONNECTOR 11
#define NETLINK_NETFILTER 12 /* netfilter subsystem */
#define NETLINK_IP6_FW 13
#define NETLINK_DNRTMSG 14 /* DECnet routing messages */
#define NETLINK_KOBJECT_UEVENT 15 /* Kernel messages to userspace */
#define NETLINK_GENERIC 16
内核代码:
1 #include <linux/module.h> 2 #include <linux/kernel.h> 3 #include <linux/init.h> 4 #include <net/sock.h> 5 #include <linux/socket.h> 6 #include <linux/net.h> 7 #include <asm/types.h> 8 #include <linux/netlink.h> 9 #include <linux/rtnetlink.h> 10 #include <linux/skbuff.h> 11 #include <linux/delay.h> 12 13 #define NETLINK_USER 29 //User defined group, consistent in both kernel prog and user prog 14 #define MYGRP 2 //User defined group, consistent in both kernel prog and user prog 15 16 struct sock *nl_sk = NULL; 17 18 static void send_to_user(void); 19 20 static void send_to_user(void) 21 { 22 struct sk_buff *skb_out; 23 struct nlmsghdr *nlh; 24 int msg_size; 25 char msg[20] = "Hello from kernel"; 26 int res; 27 28 printk(KERN_INFO "Entering: %s ", __FUNCTION__); 29 msg_size = strlen(msg); 30 printk(KERN_INFO "msg_size: %d ", msg_size); 31 //msg[msg_size - 1] = '