Passing/printing parameters in Arduino - arduino

There is a function RFID that returns *z4 parameter that should be put into TagID.
When I print TagID from loop(), '1' instead of '1B31687DBC7FF' is printed.
How can I get the whole value? I would like to print full string '1B31687DBC7FF' to serial port.
#include "Arduino.h"
#include <Wire.h>
#include <LiquidCrystal_I2C.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
LiquidCrystal_I2C lcd(0x3F, 2, 1, 0, 4, 5, 6, 7, 3, POSITIVE);
int inWord = 0;
int outWord[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
int index = 0;
unsigned char Data2Calc[]= { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
unsigned short CRC2Calc = 0;
unsigned char Bytes2Calc = 9;
char z5 []= { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
const char* TagID;
void setup()
{
pinMode(13, OUTPUT);
lcd.begin(16,2);
lcd.backlight();
lcd.setCursor(0,0);
lcd.print("RFID Reader");
lcd.setCursor(0,1);
lcd.print("Skanuj TAG");
Serial.begin(9600);
Serial1.begin(9600);
lcd.setCursor(0,0);
}
void loop()
{
if (Serial1.available())
{
TagID = RFID();
}
else
{
if (index==11)
{
index=0;
Serial.print(TagID);
Serial.println("");
lcd.setCursor(0,0);
lcd.print("ID:");
lcd.print(TagID);
}
}
}
const char * RFID()
{
char z1 []= { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
char z2 []= { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
char z3 []= { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
unsigned short crc2[] = { 0 };
inWord = Serial1.read();
index++;
if (index == 1)
{
if (inWord == 1)
{
outWord[index] = inWord;
}
else
{
index=index-1;
}
}
else if (index > 1)
{
if (index == 11)
{
outWord[index] = inWord;
for (int i = 1; i <12; i++)
{
Data2Calc[i-1] = outWord[i];
}
CRC16(Data2Calc, &CRC2Calc, Bytes2Calc);
itoa(outWord[10],z1,16);
itoa(outWord[11],z2,16);
strcat(z1, z2);
*crc2 = CRC2Calc;
sprintf(z2, "%x", *crc2); //
if (strcmp(z1,z2) == 0)
{
char z4 []= { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
for (int i=1;i<10;i++)
{
itoa(outWord[i],z3,16);
if (strlen(z3)<2) strcat(z4, "0");
strcat(z4, z3);
//Serial.print(z4);
//Serial.println("");
}
//Serial.print("z4=");
//Serial.print(z4);
//Serial.println("");
strncpy(z5, z4, 18);
}
}
else
{
outWord[index] = inWord;
}
}
return z5;
}
void CRC16(unsigned char * Data, unsigned short * CRC, unsigned char Bytes)
{
int i, byte;
unsigned short C;
*CRC = 0;
for (byte = 1; byte <= Bytes; byte++, Data++)
{
C = ((*CRC >> 8) ^ *Data) << 8;
for (i = 0; i < 8; i++)
{
if (C & 0x8000)
C = (C << 1) ^ 0x1021;
else
C = C << 1;
}
*CRC = C ^ (*CRC << 8);
}
}
Whole output of the functions is attached bellow:
Currently there are no serial ports registered - please use the + button to add a port to the monitor.
Connect to serial port COM4 at 9600
TagID: 1
UPDATE 1
I have attached above full code. Sorry... it is a bit long.
UPDATE 2
OK. I got it somewhat working, but not quite as expected. I got the value printed as expected, but only for the first time I call the function. If I call the function more times, I get some garbage added to the printed value as bellow:
Currently there are no serial ports registered - please use the + button to add a port to the monitor.
Connect to serial port COM4 at 9600
TagID: 1b31596d9cff
TagID: 1b31596d9cff1b31596d9cff
TagID: 1b31596d9cff1Řc–
ś˙cŘ1b31596d9cff
TagID: 1b31596d9cff1Řc–
ś˙cŘ1b311031596d9cff
TagID: 1b31596d9cff1Řc–
ś˙cŘ1b311031596d9cff
Any idea on what the problem might be?
I have updated the latest full source code at the top of the post.
Thanks.
UPDATE 3
OK, I got it finally working. I have changed declaration from 'char z1 []=...' to 'const char z1 []=...'
I am not sure it is written in decent style... but it works :) I attach working source code at the top of the page.
UPDATE 4
No, after a few tests I have to admit that the solution from UPDATE 3 does NOT work. Indeed it reads correctly but only for the first time... then program crashes and... it reads RFID again for the first time... so it looks only it reads OK, but it does not.
Serial output for 5 readings is as follows:
Currently there are no serial ports registered - please use the + button to add a port to the monitor.
Connect to serial port COM4 at 9600
1b31596d9cff
1b31596d9cff1b31596d9cff
1b31596d9cff1Řc–
ś˙cŘ1b31596d9cff
1b31596d9cff1Řc– ś˙cŘ1b311031596d9cff
1b31596d9cff1Řc– ś˙cŘ1b311031596d9cff
Any hints on what is wrong with the code?
UPDATE 5
OK. Finally I got it working... at least from what I can see.
I changed tables size, reworked HEX display way and made a few minor changes.
The entire source code updated at the top.

TagID is a char and your function returns a char. A char is a one byte variable. It will hold at most one character. It shouldn't then surprise you that you only print one character. You haven't provided enough of your code to really figure out what you're actually after. But that explains why you only get one character printed. A char variable can hold one character, not that whole string of stuff.
I'm thinking that you wanted to get a char*, a pointer to a char array. But you're going to have trouble with that too because z4 is a local array and goes out of scope before you get a chance to use it.

Related

Why this adafruit screen code interferes with this code?

I have a code for artificial neural network on Arduino. I'm using an Arduino UNO at 16Mhz and a SSD1306 led screen. The ANN is a simple logic XOR function. The code generates two random numbers 1.0 or 0.0, then passes the values to the inputs of the ANN, then the ANN inference the value and prints the inference time in milliseconds on the led screen, after that, prints on Serial monitor the input values, the output value and the inference time. Complete code is:
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#include <math.h>
#define SCREEN_WIDTH 128 // OLED display width, in pixels
#define SCREEN_HEIGHT 64 // OLED display height, in pixels
// Declaration for an SSD1306 display connected to I2C (SDA, SCL pins)
#define OLED_RESET -1 // Reset pin # (or -1 if sharing Arduino reset pin)
Adafruit_SSD1306 display(SCREEN_WIDTH, SCREEN_HEIGHT, &Wire, OLED_RESET);
volatile unsigned long adcTime = 0;
const float NEFTIS_E = 2.71828183;
const int NEFTIS_ANN_LENGHT = 13; // Total neurons in the network.
const int NEFTIS_OUT_LENGHT = 1; // Total output neurons.
const int NEFTIS_INPUT_LENGHT = 2; // Total input neurons.
enum ENUM_ActivationFuntionType
{
AF_Logistic, // Logistic sigmoid.
AF_TanH, // Hypervolic tangent.
AF_ArcTan, // Arc tangent.
AF_ReLU, // Rectified Linear Unit.
AF_LeakyReLU, // Leaky ReLU.
AF_ELU, // Exponentian Linear Unit.
AF_SoftPlus, //
AF_Boolean, // Boolean.
};
// Synapse structure
typedef struct
{
float weight;
int inputNeuron;
} struct_synapse;
// Neuron structure
typedef struct
{
float value;
float bias;
int indexStart;
int nInputs;
bool isInput;
ENUM_ActivationFuntionType activationFunction;
float linearDelta;
} struct_neuron;
struct_neuron Neftis_Neurons[] = {
{1.0f, 0, 0, 0, true, AF_Logistic, 0.01},
{1.0f, 0, 0, 0, true, AF_Logistic, 0.01},
{0.0f, 0, 0, 2, false, AF_Logistic, 0.01},
{0.0f, 0, 2, 2, false, AF_Logistic, 0.01},
{0.0f, 0, 4, 2, false, AF_Logistic, 0.01},
{0.0f, 0, 6, 2, false, AF_Logistic, 0.01},
{0.0f, 0, 8, 2, false, AF_Logistic, 0.01},
{0.0f, 0, 10, 2, false, AF_Logistic, 0.01},
{0.8f, 0, 12, 2, false, AF_Logistic, 0.01},
{0.0f, 0, 14, 2, false, AF_Logistic, 0.01},
{0.0f, 0, 16, 2, false, AF_Logistic, 0.01},
{0.0f, 0, 18, 2, false, AF_Logistic, 0.01},
{0.0f, 0, 20, 10, false, AF_Logistic, 0.01}
};
struct_synapse Neftis_Synapses[] = {
{-5.43316f, 0},
{-5.543714f, 1},
{-4.262666f, 0},
{1.139778f, 1},
{2.446421f, 0},
{-6.2367f, 1},
{-2.993009f, 0},
{-0.5112332f, 1},
{-3.330907f, 0},
{0.02449156f, 1},
{-1.701479f, 0},
{-1.936165f, 1},
{0.5805757f, 0},
{1.178081f, 1},
{-3.712192f, 0},
{0.5605027f, 1},
{-4.816404f, 0},
{-4.946669f, 1},
{-3.816507f, 0},
{0.6793132f, 1},
{-9.65515f, 2},
{2.788617f, 3},
{5.523755f, 4},
{0.8867579f, 5},
{1.384886f, 6},
{-0.4491375f, 7},
{-3.600839f, 8},
{1.99833f, 9},
{-6.788064f, 10},
{2.101213f, 11}
};
void setup() {
// put your setup code here, to run once:
Serial.begin(115200);/*
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
display.display();*/
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
float inputs[NEFTIS_INPUT_LENGHT];
inputs[0] = (float) random(0, 2);
inputs[1] = (float) random(0, 2);
Neftis_SetInputs(inputs);
unsigned long start = micros();
Neftis_Run();
adcTime = micros() - start;
display.clearDisplay();
display.setTextSize(1); // Normal 1:1 pixel scale
display.setTextColor(SSD1306_WHITE); // Draw white text
display.setCursor(1, 16); // Start at top-left corner
display.print(adcTime);
Serial.println(Neftis_Neurons[0].value);
Serial.println(Neftis_Neurons[1].value);
Serial.println(Neftis_Neurons[12].value);
display.display();
Serial.println(adcTime);
digitalWrite(LED_BUILTIN, true);
delay(1000);
digitalWrite(LED_BUILTIN, false);
delay(500);
}
void Neftis_SetInputs(float inputs[])
{
for(int i = 0; i < NEFTIS_INPUT_LENGHT; i++)
{
Neftis_Neurons[i].value = inputs[i];
}
}
void Neftis_Run()
{
// for every neuron
for(int i = 0; i < NEFTIS_ANN_LENGHT; i++)
{
float sum = 0.0f;
for(int j = 0; j < Neftis_Neurons[i].nInputs; j++)
{
// sums the inputs
sum += Neftis_Synapses[Neftis_Neurons[i].indexStart + j].weight * Neftis_Neurons[Neftis_Synapses[Neftis_Neurons[i].indexStart + j].inputNeuron].value;
}
sum += Neftis_Neurons[i].bias;
// apply activation function if is not input neuron
if(Neftis_Neurons[i].isInput == false)
{
// >> Logistic
if(Neftis_Neurons[i].activationFunction == AF_Logistic){
Neftis_Neurons[i].value = (float) (1 / (1 + pow(NEFTIS_E, -sum)));
// >> TanH.
}
}
}
}
void Neftis_GetOutputs(float* outArray)
{
for(int i = 0; i < NEFTIS_OUT_LENGHT; i++)
{
outArray[i] = Neftis_Neurons[NEFTIS_ANN_LENGHT - NEFTIS_OUT_LENGHT + i].value;
}
}
The problem is, the screen don't show anything and the serial monitor shows strange values for the inputs, output and inference time, as show in image below.
But if I remove the lines
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
display.clearDisplay();
display.display();*/
and
display.clearDisplay();
display.setTextSize(1); // Normal 1:1 pixel scale
display.setTextColor(SSD1306_WHITE); // Draw white text
display.setCursor(1, 16); // Start at top-left corner
then the serial monitor shows the right values for inputs, output and elapsed time for inference.
Now, I modified this line of code from this:
Neftis_Neurons[i].value = (float) (1 / (1 + pow(NEFTIS_E, -sum)));
to this:
Neftis_Neurons[i].value = (float) (1 / (1 + pow(NEFTIS_E, -1.5)));
and then the screen works and shows the inference time. The question is simple, why the screen code is interfering with pow function and serial monitor? or pow function is interfering with screen and serial monitor code? By the way, I executed the same code on a Raspberry Pi Pico and works ok, no issues there.
Thank you very much, I hope you find the answer.
I followed the suggestion of CherryDT and posted my question on the Arduino forum and was answered in [https://forum.arduino.cc/t/why-this-adafruit-screen-code-interferes-with-this-other-code/1049580]this link1
You are running out of dynamic memory on the Uno, which causes unpredictable errors during run time.
This line allocates a screen buffer of 1024 bytes, which won't be shown in the memory usage report during compiling/uploading:
display.begin(SSD1306_SWITCHCAPVCC, 0x3C);
To save dynamic memory space, you can put your other data arrays in program memory using the PROGMEM keyword. Check the Arduino reference for usage.
I tried the same code but with a smaller ANN model and it worked.

Convert Byte array to string and than match it with string in arduino

I cannot able to match my serial monitor data to my string.
The way I am sending data to serial is data.getBytes() where data is a string and I have to keep it that way.
So now I have to convert that data to string and than match it to its equivalent string but I couldn't figure that out.
aduino code inside void loop() is:
if(Serial.available()){ // only send data back if data has been sent
byte msg = Serial.read();
byte plain[a.length()]; // String a = "2"
byte inString = a.getBytes(plain, a.length(), 0); // read the incoming data
if(inString == msg){
sevenSeg(0, 1, 1, 0, 1, 1, 1); // 2
delay(500);
}else{
sevenSeg(0, 0, 0, 1, 1, 0, 0); // 1
delay(500);
}
else{
sevenSeg(1, 1, 1, 1, 1, 1, 0); //0
}
All I end up with is displaying 1. Even though I am sending data to the serial monitor. Any help or ideas are greatly appreciated. Thanks.

Optimize code with predefined variables with same prefix

I'm well on my way on learning coding for Arduino.
For the following case I Googled my ass off, but can't find any helpful answer.
So, asking here. Maybe you can help me with some terminology to Google, or direct links where this is elaborated.
I want to compress the following code. The predefined colors have to be as they are.
All variables have the same prefix, namely COLOR_. Is there any way to compress the part that is in the setup?
See following link.
// Define the colors of remote control in RGB values
// R G B
#define COLOR_0 { 0, 0, 0}
#define COLOR_1 {255, 0, 0} // Red
#define COLOR_2 {255, 160, 25} // Orange
#define COLOR_3 {255, 255, 0} // Yellow
#define COLOR_4 {127, 255, 127} // Pink
#define COLOR_5 { 0, 255, 0} // Green
#define COLOR_6 { 0, 255, 255} // Cyan
#define COLOR_7 { 0, 127, 255} // Light blue
#define COLOR_8 { 0, 0, 255} // Blue
#define COLOR_9 {191, 0, 255} // light green
uint16_t RGB_565(uint8_t red, uint8_t green, uint8_t blue){
// 16-bit value to express the RGB565-color:
// |R|R|R|R|R|G|G|G|G|G|G|B|B|B|B|B|
uint16_t red_565 = red / 8;
uint16_t green_565 = green / 4;
uint16_t blue_565 = blue / 8;
uint16_t mixed_565 = (red_565 << 11) | (green_565 << 5) | blue_565;
return mixed_565;
}
void setup(){
// Convert the preset colors to a RGB565-value
const uint8_t tint_1[] = COLOR_1;
uint16_t color_1 = RGB_565(tint_1[0], tint_1[1], tint_1[2]);
const uint8_t tint_2[] = COLOR_2;
uint16_t color_2 = RGB_565(tint_2[0], tint_2[1], tint_2[2]);
const uint8_t tint_3[] = COLOR_3;
uint16_t color_3 = RGB_565(tint_3[0], tint_3[1], tint_3[2]);
const uint8_t tint_4[] = COLOR_4;
uint16_t color_4 = RGB_565(tint_4[0], tint_4[1], tint_4[2]);
// etc...
// This part should be able to be compressed
}
void loop(){
// Not relevant
}
What about
#define COLOR_1 255, 0, 0
Then simply call
RGB_565(COLOR_1);

Authentication after a read failure of a MIFARE card

An arduino and a mfrc522 rfid reader are easy to use to read and write mifare card.
My aim is to use the both key of the card in a sector, some blocks are readable with key A, and some are only readable by key B.
Setting properly the access bits allow this behaviour. So as to try it on the second sector (blocks 4 5 6 7), I set the access bits g0 [0 0 0], g1 [1 0 1], g2 [0 0 0], g3 [1 0 1] by writting the block 7 with {,0xF5,0xA5,0xA0,0x38,} cf. §8.7 of https://www.nxp.com/docs/en/data-sheet/MF1S50YYX_V1.pdf. Now the block 5 is not readable with keyA but with keyB (g1), and keyB is no more readable (g3). So when I authenticate with keyA an attempt to read the block 5 lead to an error. At this time the others authentications fail, and it is not possible to read the others blocks, though the access bits allow it.
I tried to read the second sector with key B for block 5 and keyA for the others code, it is working. But if I try to read with key A then with keyB in case of failure it is not working.
Extract of the code :
// The sector of interest is the second one : blocks 4 5 6 7
Serial.println("\nAuthenticate block 0x05 with key B");
for (i = 4; i < 8; i++) {
// Block 5 is readable with key B
status = readblock(i==5?MF1_AUTHENT1B:MF1_AUTHENT1A, i, i==5?keyB:keyA, serial);
if ( status == MI_ERR) {
Serial.print(" - Unable to read block nb. 0x");
Serial.println(i, HEX);
}
}
Serial.println("\nAuthenticate with key A then key B if failed");
for (i = 4; i < 8; i++) {
// Try to authenticate each block first with the A key.
status = readblock(MF1_AUTHENT1A, i, keyA, serial);
if ( status == MI_ERR) {
Serial.print(" - Try keyB - ");
status = readblock(MF1_AUTHENT1B, i, keyB, serial);
if ( status == MI_ERR) {
Serial.print(" - Unable to read block nb. 0x");
Serial.println(i, HEX);
}
}
}
readblock function (authentication and read)
byte readblock(byte mode, byte block, byte *key, byte *serial)
{
int j;
byte data[MAX_LEN];
byte status = MI_ERR;
// Try to authenticate the block first
status = nfc.authenticate(mode, block, key, serial);
if ( status == MI_OK) {
Serial.print("Authenticated block nb. 0x");
Serial.print(block, HEX);
// Reading block i from the tag into data.
status = nfc.readFromTag(block, data);
if (status == MI_OK) {
// If there was no error when reading; print all the hex
// values in the data.
Serial.print(" : ");
for (j = 0; j < 15; j++) {
Serial.print(data[j], HEX);
Serial.print(", ");
}
Serial.println(data[15], HEX);
} else
Serial.print(" - Read failed");
} else {
Serial.print("Failed authentication block nb. 0x");
Serial.print(block, HEX);
}
return status;
}
The result is
Authenticate block 0x05 with key B
Authenticated block nb. 0x4 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
Authenticated block nb. 0x5 : AB, CD, EF, 1, 23, 45, 67, 89, 98, 76, 54, 1A, 10, FE, DC, BA
Authenticated block nb. 0x6 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
Authenticated block nb. 0x7 : 0, 0, 0, 0, 0, 0, F5, A5, A0, 38, 0, 0, 0, 0, 0, 0
Authenticate with key A then key B if failed
Authenticated block nb. 0x4 : 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
Authenticated block nb. 0x5 - Read failed - Try keyB - Failed authentication block nb. 0x5 - Unable to read block nb. 0x5
Failed authentication block nb. 0x6 - Try keyB - Failed authentication block nb. 0x6 - Unable to read block nb. 0x6
Failed authentication block nb. 0x7 - Try keyB - Failed authentication block nb. 0x7 - Unable to read block nb. 0x7
So I would like to know if it is possible to attempt to read a block with the bad key and then go on reading the block with the othe rkey, and so on.
An explanation can be found in https://www.nxp.com/docs/en/application-note/AN1304.pdf p.24
Each time an Authentication operation, a Read operation or a Write operation fails, the MIFARE Classic or MIFARE Plus remains silent and it does not respond anymore to any commands. In this situation in order to continue the NDEF Detection Procedure the MIFARE Classic or MIFARE Plus needs to be re-activated and selected.
So you have to re-activate and select after failure, by adding these lines to your code for instance :
Serial.println("\nAuthenticate with key A then key B if failed");
for (i = 4; i < 8; i++) {
// Try to authenticate each block first with the A key.
status = readblock(MF1_AUTHENT1A, i, keyA, serial);
if ( status == MI_ERR) {
Serial.print(" - Try keyB - ");
/** RE ACTIVATE AND SELECT ------------------------------- **/
nfc.haltTag();
status = nfc.requestTag(MF1_REQIDL, data);
if (status == MI_OK) {
status = nfc.antiCollision(data);
memcpy(serial, data, 5);
nfc.selectTag(serial);
}
/** ------------------------------------------------------ **/
status = readblock(MF1_AUTHENT1B, i, keyB, serial);
if ( status == MI_ERR) {
Serial.print(" - Unable to read block nb. 0x");
Serial.println(i, HEX);
}
}
}

netlink_broadcast fail with return value -3

I can't broadcast netlink message to userspace by the following code. However, I can't find anything wrong. My userspace program can recieve broadcast message of other types, for example sock_fd=socket(PF_NETLINK, SOCK_RAW, NETLINK_KOBJECT_UEVENT);, but not my type SYSHOOK_NL_NUM.
I think that bugs hide in my kernel code. Can anyone figure out what's wrong? Thanks.
syshook_nl_sk = netlink_kernel_create(&init_net, SYSHOOK_NL_NUM, 1, NULL, NULL, THIS_MODULE);
skb = alloc_skb(NLMSG_SPACE(nl_send_len), GFP_ATOMIC);
if(!skb) {
error = -ENOMEM;
goto err;
}
nlh = (struct nlmsghdr *)skb->data;
nlh->nlmsg_len = NLMSG_SPACE(nl_send_len);
nlh->nlmsg_pid = 0;
nlh->nlmsg_flags = 0;
nlh = nlmsg_put(skb, 0, 0, 0, NLMSG_SPACE(nl_send_len) - sizeof (struct nlmsghdr), 0);
NETLINK_CB(skb).pid = 0;
NETLINK_CB(skb).dst_group = 1;
error = netlink_broadcast(syshook_nl_sk, skb, 0, 1, GFP_KERNEL);
Userspace code that receive broadcast messages from kernel.
sock_fd=socket(PF_NETLINK, SOCK_RAW, NETLINK_TEST);
// sock_fd=socket(PF_NETLINK, SOCK_RAW, 15);
if(sock_fd < 0) {
printf("create nl failed.\n");
return -1;
}
memset(&src_addr, 0, sizeof(src_addr));
memset(&msg, 0, sizeof(msg));
src_addr.nl_family = AF_NETLINK;
src_addr.nl_pid = 100; /* self pid */
/* interested in group 1<<0 */
src_addr.nl_groups = 1;
// setsockopt(sock_fd, SOL_SOCKET, SO_RCVBUF, &buffersize, sizeof(buffersize));
bind(sock_fd, (struct sockaddr*)&src_addr, sizeof(src_addr));
memset(&dest_addr, 0, sizeof(dest_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_name = (void *)&dest_addr;
msg.msg_namelen = sizeof(dest_addr);
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
char buf[1024] = {0};
printf("begin to recvmsg jiang \n");
int rcvlen;
while (1) {
/* Read message from kernel */
rcvlen = recv(sock_fd, &buf, sizeof(buf), 0);
// rcvlen = recvmsg(sock_fd, &msg, 0);
printf("--%d--%s\n",rcvlen, buf);
}
sudo make it works. Seems the code is OK.

Resources