Introduce old redir program
[lcapit-junk-code.git] / linux-kernel / netlink / tiny-to-kernel / tk-test.c
blob392553cddaafc6074fc8d341df3a972b3d77c598
1 /*
2 * tk-test: send a netlink message to the kernel w/o any payload.
3 *
4 * This requires the netlink-tiny-tk kernel module. It will read
5 * the netlink message and print this process' ID in the kernel
6 * ring buffer.
7 *
8 * Luiz Fernando N. Capitulino
9 * <lcapitulino@gmail.com>
11 #include <stdio.h>
12 #include <string.h>
13 #include <stdlib.h>
14 #include <unistd.h>
15 #include <sys/types.h>
16 #include <sys/socket.h>
17 #include <linux/netlink.h>
19 #define NETLINK_TEST 20 // from netlink-tiny-tk.c
21 int main(void)
23 ssize_t bytes;
24 int err, sock_fd;
25 struct iovec iov;
26 struct msghdr msg;
27 struct nlmsghdr nlhdr;
28 struct sockaddr_nl sa, nladdr;
31 * Create the netlink socket and bind it to a port
32 * (which is our pid).
34 * Data structure used: struct sockaddr_nl sa
37 sock_fd = socket(AF_NETLINK, SOCK_RAW, NETLINK_TEST);
38 if (sock_fd < 0) {
39 perror("socket()");
40 exit(1);
43 memset(&sa, 0, sizeof(sa));
44 sa.nl_family = AF_NETLINK;
45 sa.nl_pid = getpid(); // self pid
47 err = bind(sock_fd, (struct sockaddr *) &sa, sizeof(sa));
48 if (err) {
49 perror("bind()");
50 exit(1);
54 * Send a netlink message to the kernel
56 * Fill the required structures and send a netlink
57 * message to the kernel using sendmsg().
59 * Data structures used:
61 * struct nlmsghdr nlhdr: netlink header
62 * struct iovec iov: payload (?)
63 * struct msghdr msg: required by sendmsg()
66 memset(&nlhdr, 0, sizeof(nlhdr));
67 nlhdr.nlmsg_len = sizeof(nlhdr);
68 nlhdr.nlmsg_pid = getpid();
70 iov.iov_base = (void *) &nlhdr;
71 iov.iov_len = nlhdr.nlmsg_len;
73 memset(&nladdr, 0, sizeof(nladdr));
74 nladdr.nl_family = AF_NETLINK;
76 memset(&msg, 0, sizeof(msg));
77 msg.msg_name = (void *) &(nladdr);
78 msg.msg_namelen = sizeof(nladdr);
79 msg.msg_iov = &iov;
80 msg.msg_iovlen = 1;
82 bytes = sendmsg(sock_fd, &msg, 0);
83 if (bytes < 0) {
84 perror("sendmsg()");
85 exit(1);
88 close(sock_fd);
90 printf("Message sent! My pid: %d\n", getpid());
92 return 0;