0
votes

I have the following 4-bytes aligned struct data (no padding at all) that is copied to a unsigned char * buffer before being sent over a TCP socket. The sender machine is a Little Endian system, the receiver is a Big Endian system.

typedef struct {
    unsigned short  a;
    unsigned short  b;
} Struct;
Struct s;
s.a = 1;
s.b = 2;
...
memmcpy (buf, (unsigned char *)&s, sizeof (Struct));
write (sockfd, buf, sizeof(Struct));

On the sender system, I imagine s.a to be represented in memory like 01 00 and s.b 02 00, thus the stream that is sent out is 01 00 02 00. I assume that in this case the sender is sending little endian byte order over the network and not network byte order.

Since the receiver is a Big Endian sytem, my question is:

  1. The sender should send in network byte order (having to call htons on s.a and s.b)
  2. Or the receiver should handle this, by calling ntohs?
1

1 Answers

1
votes

There isn't a single answer to this question, and there are precedents for both:

  • Most Internet protocols use network byte-order, which means a single code-path on each end, but may require unnecessary byte-swapping when two little-endian machines communicate.

  • CORBA IIOP sends in host byte-order, along with a flag to indicate which order that is - clients must be able to swap endianness if the flag is different from their own native order.

In your case, given that you know the hosts are of different endianness, I recommend you specify your protocol to use network byte order - you'll surprise fewer people that way.