1 /* This example is placed in the public domain. */
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <time.h>
6
7 #include <libmnl/libmnl.h>
8 #include <linux/genetlink.h>
9
10 static int group;
11
data_cb(const struct nlmsghdr * nlh,void * data)12 static int data_cb(const struct nlmsghdr *nlh, void *data)
13 {
14 printf("received event type=%d from genetlink group %d\n",
15 nlh->nlmsg_type, group);
16 return MNL_CB_OK;
17 }
18
main(int argc,char * argv[])19 int main(int argc, char *argv[])
20 {
21 struct mnl_socket *nl;
22 char buf[MNL_SOCKET_BUFFER_SIZE];
23 int ret;
24
25 if (argc != 2) {
26 printf("%s [group]\n", argv[0]);
27 exit(EXIT_FAILURE);
28 }
29 group = atoi(argv[1]);
30
31 nl = mnl_socket_open(NETLINK_GENERIC);
32 if (nl == NULL) {
33 perror("mnl_socket_open");
34 exit(EXIT_FAILURE);
35 }
36
37 if (mnl_socket_bind(nl, 0, MNL_SOCKET_AUTOPID) < 0) {
38 perror("mnl_socket_bind");
39 exit(EXIT_FAILURE);
40 }
41
42 if (mnl_socket_setsockopt(nl, NETLINK_ADD_MEMBERSHIP, &group,
43 sizeof(int)) < 0) {
44 perror("mnl_socket_setsockopt");
45 exit(EXIT_FAILURE);
46 }
47
48 ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
49 while (ret > 0) {
50 ret = mnl_cb_run(buf, ret, 0, 0, data_cb, NULL);
51 if (ret <= 0)
52 break;
53 ret = mnl_socket_recvfrom(nl, buf, sizeof(buf));
54 }
55 if (ret == -1) {
56 perror("error");
57 exit(EXIT_FAILURE);
58 }
59
60 mnl_socket_close(nl);
61
62 return 0;
63 }
64