I have a c++ socket program where there are two processes. The server process and client process. The client registers with the server and listens on a port for any message from server.
I have defined a "char *buffer" which will have my message. The message size is say 59000 Bytes. Now before transmitting the message i am adding the message size at the beginning of the buffer,
size=htonl(59000)
Buffer= size + <Actual Message>
so that client process when ever it gets a message it reads first two bytes to get size first, knows the size of message transmitted and then it reads the complete message from the socket. This is done as below
59000 in binary format is 00000000 00000000 11100110 01111000
htonl(59000) in binary format is 01111000 11100110 00000000 00000000
I used memcpy to copy this size to charcter buffer.
memcpy(buffer, &size, 4) <since size of int is 4>
After transmitting the message at client when i read the first two bytes i get the size as zero. But if i read the next two bytes i get the correct size that is 59000. The way i am reading the message size at client is as mentioned below
int messageSize=0;
memcpy(&messageSize, buffer, 2 );
Can some one please explain me why the message size is stored in the second two bytes and not in the first two bytes.
I would be very grateful to you if you can help me. I have been trying to understand this from quite some time.
int.sizeof(int)?