【问题标题】:openssl ssl_read sends read binary data into char*openssl ssl_read 将读取的二进制数据发送到 char*
【发布时间】:2013-12-29 17:22:01
【问题描述】:

我正在尝试使用 openssl 在 c 中编写 Apple Push Notification Server 提供程序(APNS 提供程序)。

到目前为止,我已经能够通过 ssl_write 成功发送通知,但有时可能会发生我发送的消息被拒绝(无论出于何种原因,令牌错误等)。当发生这种情况并且我尝试 ssl_write 时,我会写入 -1 个字节,然后 APNS 应该发回错误消息并关闭连接。

错误以二进制形式出现,由 6 个字节组成,如苹果文档中所述:Apple Documenatation

const int written= SSL_write(this->_ssl, buffer, bufferSize);   

int want =SSL_want(this->_ssl);

if(want == 2 ){ //2 means that ssl wants to read 
char bufferRead[6];        
SSL_read(this->_ssl,bufferRead,6);

//Some code that transfers bufferRead into a ASCII format

}

我想问你,我如何将这个二进制 bufferRead 转换成我可以读取和存储的东西,比如说 char* 或 std::string。转换后的输出应类似于“881234”...
我很感激我能得到的任何帮助。

Eran 的编辑解决方案:

   unsigned char command = bufferRead[0]; 
   unsigned char status = bufferRead[1]; 
   unsigned char c2 = bufferRead[2];
   unsigned char c3 = bufferRead[3];
   unsigned char c4 = bufferRead[4];
   unsigned char c5 = bufferRead[5];

int comInt = command;
int statusInt = status;

 int id = (c5 << 24) +
          (c4 << 16) +
          (c3 << 8) +
          (c2);

【问题讨论】:

    标签: c binary openssl apple-push-notifications


    【解决方案1】:

    您应该将缓冲区解析为 3 个参数。 自从我用 c 编程以来已经有一段时间了,但我认为你需要这样的东西:

    char command = bufferRead[0]; // should contain 8
    char status  = bufferRead[1]; // the type of the error - the most common being 8 (InvalidToken)
    int id = (bufferRead[2] << 24) + 
             (bufferRead[3] << 16) + 
             (bufferRead[4] << 8) + 
             (bufferRead[5]);
    

    【讨论】:

    • 您好,感谢您的快速回答。我也尝试过用各种方式解析缓冲区,但它似乎不起作用。使用您的解决方案,如果我使用 std::cout 打印出命令、状态、id,第一个两个不打印任何内容,并且 id 是 8 个数字(67108864)。我也很肯定 ssl_read 返回的 int 值为 6。
    • @Malisak 你如何打印前两个?如果您正在打印char 变量,您可能看不到任何内容,因为 ASCII 值 8 是不可打印的字符。也许您应该将其转换为 int。至于id,你期望的值是多少? id 应该是您之前发送给 Apple 的消息的 id(您是创建该 id 的人)。此外,您确定您正在设法读取 6 个字节吗?
    • 好的,我已经将第一个两个变量转换为 int 并且它有效,现在都按预期打印 8。至于 id,我之前已经设置为 1234 是的。为 ssl_write 构建消息格式的方法与前面提到的 APNS doc 中的几乎相同。 Ssl_read 以实际从 TLS/SSL 连接读取的字节数返回 6。我试着做 strlen(bufferRead) 并显示 4 ... 这很奇怪。
    • @Malisak 您得到的数字是 67108864,等于 1234 * 2^16。这意味着当您向 Apple 发送消息时,您正在翻转 ID 的高 16 位和低 16 位的顺序。您可以修复将消息发送给 Apple 的代码,或者在从响应中读取 id 时更改字节顺序([4][5][2][3] 而不是 [2][3][4 ][5].
    • 我尝试将顺序交换为以下内容:int id = (bufferRead[4] &lt;&lt; 24) + (bufferRead[5]) &lt;&lt; 16 + (bufferRead[2]) &lt;&lt; 8 + (bufferRead[3]);,结果 int id 为 0。我现在真的迷路了。
    猜你喜欢
    • 1970-01-01
    • 2014-01-08
    • 1970-01-01
    • 1970-01-01
    • 2017-11-14
    • 2012-09-10
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多