69 lines
No EOL
1.6 KiB
C
69 lines
No EOL
1.6 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <string.h>
|
|
#include <unistd.h>
|
|
#include <sys/socket.h>
|
|
#include <linux/netlink.h>
|
|
|
|
#define MAX_PAYLOAD 1024
|
|
#define MYPROTO NETLINK_USERSOCK
|
|
#define MY_GROUP 27
|
|
|
|
|
|
int main(void)
|
|
{
|
|
int sock_fd;
|
|
struct sockaddr_nl addr;
|
|
struct nlmsghdr *nlh;
|
|
struct iovec iov;
|
|
struct msghdr msg;
|
|
char buffer[MAX_PAYLOAD];
|
|
|
|
|
|
/* 1. Create netlink socket */
|
|
sock_fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_USERSOCK);
|
|
if (sock_fd < 0) {
|
|
perror("socket");
|
|
return -1;
|
|
}
|
|
|
|
memset(&addr, 0, sizeof(addr));
|
|
addr.nl_family = AF_NETLINK;
|
|
addr.nl_pid = getpid();
|
|
addr.nl_groups = 1 << (MY_GROUP - 1);
|
|
|
|
// (Group is 1-based, sets bit (group-1) for subscription)
|
|
|
|
/* 2. Bind the socket */
|
|
if (bind(sock_fd, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
|
|
perror("bind");
|
|
close(sock_fd);
|
|
return -1;
|
|
}
|
|
|
|
|
|
while (1) {
|
|
/* 3. Prepare to receive messages in a loop */
|
|
memset(buffer, 0, sizeof(buffer));
|
|
nlh = (struct nlmsghdr *)buffer;
|
|
iov.iov_base = (void *)nlh;
|
|
iov.iov_len = MAX_PAYLOAD;
|
|
|
|
memset(&msg, 0, sizeof(msg));
|
|
msg.msg_name = (void *)&addr;
|
|
msg.msg_namelen = sizeof(addr);
|
|
msg.msg_iov = &iov;
|
|
msg.msg_iovlen = 1;
|
|
|
|
printf("Waiting for kernel broadcast...\n");
|
|
if (recvmsg(sock_fd, &msg, 0) < 0) {
|
|
perror("recvmsg");
|
|
break;
|
|
}
|
|
|
|
printf("Received kernel message: \"%s\"\n", (char *)NLMSG_DATA(nlh));
|
|
}
|
|
|
|
close(sock_fd);
|
|
return 0;
|
|
} |