Question

I tried to use netlink socket to send binary data from kernel space to user space. I followed the example from How to use netlink socket to communicate with a kernel module?

However at the receiving end in userspace, I am getting received data length to be greater than what was sent from kernel space. However the data is the same. Data gets appended with some garbage value.

Is there no guarantee in netlink socket that received data length will be same as data sent from kernel space ?

Was it helpful?

Solution

You might want to check the documentation to make sure that you are using macros like "NLMSG_SPACE", "NLMSG_PAYLOAD", and "NLMSG_DATA" correctly.

Extra data might be from the unused portions of the data frames and your program not reading the message length correctly. (In effect, not using the macros correctly.) For example, if you send 1 byte, I believe there will actually be 4 bytes sent because NLMSG_SPACE will round up to a multiple of 4 to "align" the data in the packet.

Reading it should be no problem though, just use the macros to get the real length of the data and only read that much.

Here's an example of getting a pointer to the buffer and the length of that buffer.

// Get a pointer to the start of the data in the buffer and the buffer (payload) length
buf = (u_char *) (NLMSG_DATA(nlh));
len = NLMSG_PAYLOAD(nlh, 0);

Here are the definitions of the macros. Look at those if you want. This here is probably more understandable.

The code you linked to is sending characters and gets away with it by "memset"-ing the data to 0, so printing that char array just works.

Hope this helps. Post some code if you can't get it working.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top