1

I want to send two int64_t over UDP. To do this I store them in a four-element array, where:

  • [0] - lower 32 its of the first int64_t
  • [1] - higher 32 bits of the first int64_t
  • [2] - lower 32 bits of the second int64_t
  • [3] - higher 32 bits if the second int64_t

My code for sending:

int64_t from, to;

/* some logic here */

data[0] = htonl((int32_t) from);
data[1] = htonl((int32_t) (from >> 32));
data[2] = htonl((int32_t) to);
data[3] = htonl((int32_t) (to >> 32));

/* sending via UDP here */

My code for combining int32_t back to int64_t after receiving data via UDP:

int64_t from, to;
from = (int64_t) ntohl(data[1]);
from = (from << 32);
from = from | (int64_t) ntohl(data[0]);
to = (int64_t) ntohl(data[3]);
to = (to << 32);
to = from | (int64_t) ntohl(data[2]);

printf("received from = %" PRId64 "\n", from);
printf("received to = %" PRId64 "\n", to);

The first number (from) is always correct. However, what I get from the second printf is incorrect. What's more, it seems to be dependent on the first number. Example:

Sending:

  • from = 125,
  • to = 20.

Received:

  • from = 125,
  • to = 125.

Sending:

  • from = 1252,
  • to = 20.

Received:

  • from = 1252,
  • to = 1268.

What am I doing wrong? Is it the problem of conversion or sending over the network?

4

2 回答 2

6

There's a typo in your receiver code:

to = from | (int64_t) ntohl(data[2]);

should be

to = to | (int64_t) ntohl(data[2]);
于 2013-06-11T10:44:43.627 回答
2

Note that you're sending the 64-bit values backwards. htonl() makes sure the int32s are sent in the correct order, but RFC 1700 defines that the most significant octet of the field is to be transmitted first:

When a multi-octet quantity is transmitted the most significant octet is transmitted first.

于 2013-06-11T10:55:49.137 回答