0

I understand that the server address and port number should be stored in network byte order ( which is nothing, but stored in Big Endian format). However, I am not able to understand the following. If the two different machines have different endianity, then how will the message is not affected? Please throw some light on it. For sending number on socket, do we always need to do networkbyte ordering?

1
  • For sending number on socket, do we always need to do networkbyte ordering? Commented Feb 6, 2014 at 11:49

1 Answer 1

3

This problem appears not only in socket programming, but in any connections between different architecture machines. We convert socket addresses to BE to make them respective to socket protocol and be correctly recognized by network devices. Message endianess is only your responsibility. That's why developers notify that some data have to be Most Significant Byte first (MSB) or Less Significant Byte first (LSB).

Also, I have to calm you that this rule affects only multibyte variables (float, int etc.), chars and arrays of chars are not affected. Endianness set only order of bytes in value, not order of bits, so one byte values are same on both LE and BE architectures. To avoid any of endianness problems, set common endianness of your protocol (MSB or LSB) and convert all multibyte variables into byte arrays.

void int_to_arr(uint32_t a, uint8_t *b){
    b[0] = (a >> 24) & 0xff; //take only MSB
    b[1] = (a >> 16) & 0xff; //take third byte
    b[2] = (a >> 8) & 0xff; //take second byte
    b[3] = a & 0xff; //take LSB
}
void arr_to_int(uint8_t *a, uint32_t *b){
    *b = a[3]; //move LSB
    *b |= a[2] << 8; //add second byte
    *b |= a[1] << 16; //add thirs byte
    *b |= a[0] << 24; //add MSB
}

That's how you can have MSB presentation of your unsigned int in byte array.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.