Quantcast
Channel: Active questions tagged kernel - Stack Overflow
Viewing all articles
Browse latest Browse all 6333

How to send and receive a struct through netlink?

$
0
0

I'm trying to send a struct from user-space to my module in kernel space using netlink, my struct in the user-space is:

struct test{  unsigned int length;  char name[MAX_NAME_LENGTH];};

and in the kernel space is:

struct test{  __u32 length;  char name[MAX_NAME_LENGTH];};

where MAX_NAME_LENGTH is a macro defined to be equal 50.

In the user-space, I've the function main which send my struct to the kernel with the following code:

int main(){    struct iovec iov[2];    int sock_fd;    struct sockaddr_nl src_add;    struct sockaddr_nl dest_add;    struct nlmsghdr * nl_hdr = NULL;    struct msghdr msg;     struct test message;    memset(&message, 0, sizeof(struct test));    message.length = 18;    strcpy(message.name, "Just a test\0");    sock_fd = socket(PF_NETLINK, SOCK_RAW, NETLINK_USER);    if (sock_fd < 0){        printf("Netlink socket creation failed\n");        return -1;    }    memset(&src_add, 0, sizeof(src_add));    src_add.nl_family = AF_NETLINK;    src_add.nl_pid    = getpid();    memset(&dest_add, 0, sizeof(dest_add));    dest_add.nl_family = AF_NETLINK;    dest_add.nl_pid    = 0; // Send to linux kernel    dest_add.nl_groups = 0; // Unicast    bind(sock_fd,(struct sockaddr *)&src_add,sizeof(src_add));    nl_hdr = (struct nlmsghdr *) malloc(NLMSG_SPACE(sizeof(struct test)));    memset(nl_hdr, 0, NLMSG_SPACE(sizeof (struct test)));    nl_hdr->nlmsg_len   = NLMSG_SPACE(sizeof(struct test));    nl_hdr->nlmsg_pid   = getpid();    nl_hdr->nlmsg_flags = 0;    iov[0].iov_base = (void *)nl_hdr;    iov[0].iov_len  = nl_hdr->nlmsg_len;    iov[1].iov_base = &message;    iov[1].iov_len  = sizeof(struct test);    memset(&msg,0, sizeof(msg));    msg.msg_name    = (void *)&dest_add;    msg.msg_namelen = sizeof(dest_add);    msg.msg_iov     = &iov[0];    msg.msg_iovlen  = 2;    sendmsg(sock_fd,&msg,0);    close(sock_fd);    return 0;}

And in the kernel side I've registered a function called callback to be called every time that a message is received, this is the callback function:

static void callback(struct sk_buff *skb){    struct nlmsghdr *nl_hdr;    struct test * msg_rcv;    nl_hdr  = (struct nlmsghdr*)skb->data;    msg_rcv = (struct test*) nlmsg_data(nl_hdr);     printk(KERN_INFO "Priting the length and name in the struct:%u, %s\n",msg_rcv->length, msg_rcv->name);}

When I run these codes and see the dmesg output I receive the following message: Priting the length and name in the struct:0,, so why the fields of the struct filled in the user-space side aren't being sent to the kernel?

Btw, NETLINK_USER is defined as 31.


Viewing all articles
Browse latest Browse all 6333

Trending Articles