1

i have this struct:

typedef struct
{
   auth_header header; // another struct
   uint8_t action;
   uint8_t priv_lvl;
   uint8_t authen_type;
   uint8_t service;
   uint8_t user_len;
   uint8_t port_len;
   uint8_t rem_addr_len;
   uint8_t data_len;
   char *user;
   char *port;
   char *rem_addr;
   char *data;

} auth_start;

and i want to create a buffer and insert the data in it so i can send this data to my server.

  1. im not sure of what type the buffer needs to be (uint8_t/char/auth_start).
  2. im not sure how should i do it, should i copy every field 1 by 1 with memcpy() ? or is there another way?

thanks ! :)

1 Answer 1

1

I'm not sure of what type the buffer needs to be

Any byte type will do. uint8_t is a good choice, considering the types of non-pointer fields in your struct are all uint8_t.

I'm not sure how should i do it, should i copy every field one by one with memcpy()

First, you need to figure out how much memory your buffer needs. The you allocate that memory, and copy non-pointer portion with assignments. Finally, you memcpy the data fron the four pointers:

auth_start s = ...
// Add 8 for the initial 8 members
uint8_t *buf = malloc(8+s.user_len+s.port_len+s.rem_addr_len+s.data_len);
uint8_t p = buf;
// Copy the initial fields
*p++ = s.action;
*p++ = s.priv_lvl;
... // And so on for the remaining members
// Copy pointer-based members
memcpy(p, s.user, s.user_len);
p += s.user_len;
memcpy(p, s.port, s.port_len);
p += s.port_len;
... // And so on for the remaining pointer members
Sign up to request clarification or add additional context in comments.

2 Comments

thanks alot! and how do i check if the buffer is good ? i need to reset p to the start of auth and print it in a loop ?
@phantttom the actual pointer is buf, not p. Reset p back to buf if you want to process the next struct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.