Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Retrieving multiples values from a unsigned char in C

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);

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading