Reputation: 1491
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;
}
But this method when payload is == 126 or 127 return wrong result (always enormous number) someone can spot the error?
I know i've sent a message of 250 char. This are the first 5 byte I revive converted to binary:
[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
Upvotes: 1
Views: 897
Reputation: 70492
You are missing the conversion of your values from network byte order to host byte order. 64000
is 11111010 00000000
in binary. You need to use the byte order conversion routines.
payloadLength = ntohs(payloadLength16b);
payloadLength = (size_t)ntohll(payloadLength64b);
If your system lacks a definition for ntohll
, you can follow the suggested answers to this question. But, a possible implementation might be:
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;
}
Upvotes: 1