aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorvg <vgm+dev@devys.org>2024-04-04 15:22:01 +0200
committervg <vgm+dev@devys.org>2024-04-04 15:22:01 +0200
commitb0234b0947e0bc0a6b46721631df0e2f83043df9 (patch)
tree4ded04dacdb5e5fec0dd2a4555f1a6d579ec5088
parentecd234dc9d0b1a763894e0db686a9e38054bdae8 (diff)
downloadscripts-b0234b0947e0bc0a6b46721631df0e2f83043df9.tar.gz
scripts-b0234b0947e0bc0a6b46721631df0e2f83043df9.tar.bz2
scripts-b0234b0947e0bc0a6b46721631df0e2f83043df9.zip
C script to monitor netlink events
-rwxr-xr-xscripts/netlink-monitor75
1 files changed, 75 insertions, 0 deletions
diff --git a/scripts/netlink-monitor b/scripts/netlink-monitor
new file mode 100755
index 0000000..1f22922
--- /dev/null
+++ b/scripts/netlink-monitor
@@ -0,0 +1,75 @@
+#!/usr/bin/env C
+
+#include <unistd.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <stddef.h>
+#include <string.h>
+#include <fcntl.h>
+#include <errno.h>
+#include <signal.h>
+#include <getopt.h>
+#include <sys/time.h>
+#include <sys/socket.h>
+#include <sys/un.h>
+#include <sys/select.h>
+#include <linux/types.h>
+#include <linux/netlink.h>
+
+int init_netlink_socket(int * netlink_socket)
+{
+ struct sockaddr_nl snl;
+ int ret;
+
+ memset(&snl, 0, sizeof(struct sockaddr_nl));
+ snl.nl_family = AF_NETLINK;
+ snl.nl_pid = getpid();
+ snl.nl_groups = 1;
+
+ *netlink_socket = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_KOBJECT_UEVENT);
+ if (*netlink_socket == -1) {
+ fprintf(stderr, "netlink socket: %s\n", strerror(errno));
+ return -1;
+ }
+
+ ret = bind(*netlink_socket, (struct sockaddr *) & snl,
+ sizeof(struct sockaddr_nl));
+ if (ret < 0) {
+ fprintf(stderr, "netlink bind failed: %s\n", strerror(errno));
+ close(*netlink_socket);
+ *netlink_socket = -1;
+ return -1;
+ }
+
+ return 0;
+}
+
+int main(void)
+{
+ int ret = -1;
+ int netlink_socket = -1;
+ int buflen = -1;
+ char netlink_buf[4096+1];
+
+ ret = init_netlink_socket(&netlink_socket);
+ if (ret) {
+ fprintf(stderr, "init_netlink_socket() has failed %s\n",
+ strerror(errno));
+ close(netlink_socket);
+ return -1;
+ }
+
+ while (1) {
+ buflen = recv(netlink_socket, netlink_buf, sizeof(netlink_buf)-1 , 0);
+ if (buflen <= 0) {
+ fprintf(stderr, "error receiving uevent message: %s\n",
+ strerror(errno));
+ } else {
+ netlink_buf[buflen-1] = '\0';
+ printf("%s\n", netlink_buf);
+ fflush(stdout);
+ }
+ }
+
+ return 0;
+}