netlink socket kernel to user comm

From: Richard Langly
Date: Fri Oct 09 2009 - 17:51:45 EST


My user space program isn't getting the msg from my module. Having a
problem making netlink communicate from kernel to user space.

I load my module, then I load my user space program. My module waits
20 secs before sending data so that my user space program calls bind
on an existing socket.

Kernel code
---
static void nl_data_ready(struct sock *sk, int len)
{
wake_up_interruptible(sk->sk_sleep);
}

// I call this from my module_init function.
int my_init()
{
struct sk_buff *skb = NULL;
int err = 0;
u32 pid = 0;

my_sk_sk = netlink_kernel_create(&init_net, NETLINK_TEST, 0, nl_data_ready,
NULL, THIS_MODULE);

if (my_sk_sk == NULL) {
printk("my_sk_init: could not create socket\n");

return -1;
}

// Wait 20 seconds before sending msg so that I can start my user space
// program after my module is loaded so that it can call bind() on
an existing
// socket.
unsigned long delay = jiffies + 20 * HZ;

while (time_before(jiffies, delay));

size_t len = 0;

strcpy(skb->data, "SEND_INIT");

if (len > 0)
skb->data[len - 1] = '\0';

len = strlen(skb->data);

skb = alloc_skb(NLMSG_SPACE(len), GFP_KERNEL);

if (skb) {
char *scratch;

scratch = skb_put(skb, len);
}

NETLINK_CB(skb).pid = 0;

err = netlink_unicast(my_sk_sk, skb, pid, MSG_DONTWAIT);

kfree_skb(skb);

sock_release(my_sk_sk->sk_socket);

return 0;
}

User space code which I call from main()
---
int test_nl()
{
nl_sock = socket(PF_NETLINK, SOCK_RAW, NETLINK_TEST);

memset(&src_addr, 0, sizeof(src_addr));

src_addr.nl_family = AF_NETLINK;
src_addr.nl_pid = getpid(); /* self pid */
src_addr.nl_groups = 0; /* not in mcast groups */
bind(nl_sock, (struct sockaddr *) &src_addr, sizeof(src_addr));

nlh = (struct nlmsghdr *) malloc(NLMSG_SPACE(MAX_PAYLOAD));

memset(&nlh, 0, NLMSG_SPACE(MAX_PAYLOAD));

iov.iov_base = (void *) nlh;
iov.iov_len = NLMSG_SPACE(MAX_PAYLOAD);

msg.msg_iov = &iov;
msg.msg_iovlen = 1;

while (1) {
recvmsg(nl_sock, &msg, 0);
printf("Received from kernel: %s\n", NLMSG_DATA(nlh));
}

close_nl();
}


int main(int argc, char *argv[])
{
test_nl();

close_nl();
}
--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/