Search code examples
csocketsunsigned

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

Solution

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

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

    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.