开发者

Passing int via winsocks send

How could it be possible to send int (not using third party libraries) via windows sockets Send: it requires (const char *) as parameter.

My attempt was to send int like this:

unsigned char * serialize_int(unsigned char *buffer, int value)
{
  /* Write big-endian int value into buffer; assumes 32-bit int and 8-bit char. */
  buffer[0] = value >> 24;
  buffer[1] = value >> 16;开发者_如何学运维
  buffer[2] = value >> 8;
  buffer[3] = value;
  return buffer + 4;
}

but Send() wants (const char *). I'm stuck...


Ah, this is easily fixed. The compiler wants a char* (ignore const for now), but you're passing an unsigned char*, and the only real difference is how the compiler interprets each byte when manipulated. Therefore you can easily cast the pointer from unsigned char* to char*. This way:

(char*)serialize_int(...)


const int networkOrder = htonl(value);

const result = send(socket, reinterpret_cast<const char *>(&networkOrder), sizeof(networkOrder), 0);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜