Palace Chan
Palace Chan

Reputation: 9213

Sending Big Endian formatted binary over the wire

I was multicasting something like this before:

struct Message
{
    char     cat[3];
    uint64_t foo;
    uint16_t bar;
} __attribute((packed));

Message MESSAGE;

int main(void)
{
    //every now and then
    memcpy(MESSAGE.cat, bla, 3);
    MESSAGE.foo = varA;
    MESSAGE.bar = varB - varC;

    sendto(fd, &MESSAGE, sizeof(MESSAGE), 0, &sockAddr, sizeof(sockAddr));
}

The claim on the receiver end is that they would get MESSAGE but foo and bar were scrambled even though cat was fine. And that they expect Big Endian for the integral values. So I changed my code to do this:

int main(void)
{
    //every now and then
    memcpy(MESSAGE.cat, bla, 3);
    MESSAGE.foo = bswap_64(varA);
    MESSAGE.bar = varB - varC;
    MESSAGE.bar = bswap_16(MESSAGE.bar);

    sendto(fd, &MESSAGE, sizeof(MESSAGE), 0, &sockAddr, sizeof(sockAddr));
}

and the claim is still the same. How is this possible? Big vs Little endian is binary, if it wasn't before it should be now. Or is there something wrong in the logic above?

Upvotes: 1

Views: 264

Answers (2)

Ed Heal
Ed Heal

Reputation: 60037

You need to look up http://linux.die.net/man/3/ntohl

Convert things into network order then reconstruct.

Upvotes: 1

AMADANON Inc.
AMADANON Inc.

Reputation: 5929

Try saving the packet to a file before sending it - That way you can examine it.

Upvotes: 0

Related Questions