用C解码Websocket有效负载长度

时间:2013-08-13 23:49:16

标签: c websocket payload

size_t getPayloadLength(const unsigned char *inputFrame){
  size_t payloadLength = inputFrame[1] & 0x7F;

  if (payloadLength == 0x7E) {
    uint16_t payloadLength16b = 0;
    memcpy(&payloadLength16b, &inputFrame[2], 2);
    payloadLength = payloadLength16b;

  } else if (payloadLength == 0x7F) {
    uint64_t payloadLength64b = 0;
    memcpy(&payloadLength64b, &inputFrame[2], 8);
    payloadLength = (size_t)payloadLength64b;
  }

  return payloadLength;
}

但是这个方法当有效载荷是== 126或127时返回错误的结果(总是很大的数字)有人能发现错误吗?

我知道我发了250条消息。 这是我恢复转换为二进制的前5个字节:

[0] 10000001 
[1] 11111110 // & 0x7F = 126 -> so payload length is  byte 2  3 interpreted as 16 bit
[2] 00000000 //
[3] 11111010 // 0000000011111010 = 250 but my function returns 64000
[4] 10001001 

1 个答案:

答案 0 :(得分:1)

您错过了从网络字节顺序到主机字节顺序的值转换。二进制文件中6400011111010 00000000。您需要使用字节顺序转换例程。

    payloadLength = ntohs(payloadLength16b);

    payloadLength = (size_t)ntohll(payloadLength64b);

如果您的系统缺少ntohll的定义,则可以按照this question的建议答案进行操作。但是,可能的实现可能是:

uint64_t ntohll (uint64_t x) {
    const unsigned t = 1;
    if (*(const unsigned char *)&t) {
        x = ((uint64_t)ntohl(x & 0xffffffffU) << 32)
            | ntohl((uint32_t)(x >> 32));
    }
    return x;
}