Home > Software design >  Retrieving multiples values from a unsigned char in C
Retrieving multiples values from a unsigned char in C

Time:10-19

I have write in a unsigned char *, two int and send it via a socket in C. How can i retrieve those values from the receiver side.

Code:

unsigned char * request = malloc (8 * sizeof(unsigned char));

int index = htonl(rand() % 1000);
int size =  htonl(key_size);

memcpy(request, &ind,4);
memcpy(request 4, &size,4);

CodePudding user response:

You just reverse all those operations. Read from the socket into buffer, then use:

int index, size;

memcpy(&index, buffer, 4);
index = ntohl(index);
memcpy(&size, buffer 4, 4);

Note that all your code assumes that sizeof int == 4. It would be better to use int32_t to ensure that the variables are the expected size.

  • Related