1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
| #include <linux/kernel.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/sched.h>
#include <net/sock.h>
#include <net/netlink.h>
#define NETLINK_TEST 29
struct sock *nl_sk = NULL;
void nl_data_ready(struct sk_buff *__skb)
{
struct sk_buff *skb;
struct nlmsghdr *nlh;
u32 pid;
int rc;
int len = NLMSG_SPACE(1200);
char str[100];
printk("net_link: data is ready to read.\n");
skb = skb_get(__skb);
if (skb->len >= NLMSG_SPACE(0)) {
nlh = nlmsg_hdr(skb);
printk("net_link: recv %s.\n", (char *)NLMSG_DATA(nlh));
memcpy(str, NLMSG_DATA(nlh), sizeof(str));
pid = nlh->nlmsg_pid; /*pid of sending process */
printk("net_link: pid is %d\n", pid);
kfree_skb(skb);
skb = alloc_skb(len, GFP_ATOMIC);
if (!skb) {
printk(KERN_ERR "net_link: allocate failed.\n");
return;
}
nlh = nlmsg_put(skb, 0, 0, 0, 1200, 0);
NETLINK_CB(skb).portid = 0; /* from kernel */
memcpy(NLMSG_DATA(nlh), str, sizeof(str));
strcpy(NLMSG_DATA(nlh) + 10, " from kernel");
printk("net_link: going to send.\n");
rc = netlink_unicast(nl_sk, skb, pid, MSG_DONTWAIT);
if (rc < 0) {
printk(KERN_ERR "net_link: can not unicast skb (%d)\n", rc);
}
printk("net_link: send is ok.\n");
}
return;
}
static int test_netlink(void)
{
struct netlink_kernel_cfg cfg = {
.groups = 0,
.input = nl_data_ready,
.cb_mutex = NULL,
.flags = 0,
.bind = NULL,
};
nl_sk = netlink_kernel_create(&init_net, NETLINK_TEST, &cfg);
if (!nl_sk) {
printk(KERN_ERR "net_link: Cannot create netlink socket.\n");
return -EIO;
}
printk("net_link: create socket ok.\n");
return 0;
}
int netlink_init(void)
{
test_netlink();
return 0;
}
void netlink_exit(void)
{
if (nl_sk != NULL) {
sock_release(nl_sk->sk_socket);
}
printk("net_link: remove ok.\n");
}
module_init(netlink_init);
module_exit(netlink_exit);
MODULE_LICENSE("GPL");
|