c - 在网络字节顺序上使用结构时得到错误的字节顺序

标签 c network-programming

我正在编写 C 代码,以便使用 Windows(codeblocks IDE)x64 intel PC 中的 GCC C 编译器从写入网络字节顺序的二进制文件中读取数据。

数据字节如下:

 00 16 54 43 41 54 20 20 00 AA 00 00 00 00 00 00 B8 60 41 42 43 00 00 17

我的代码是:

#define SWAPPED(num) ((num>>8) | (num<<8))

struct  trd_t {
    unsigned short   length;     // First 2 bytes in the input data
    char    type;                // next 1 byte
    char    symbol[5];           // next 5 bytes
    unsigned short   trd_size;   // next 2 bytes
    uint64_t    trd_price;       // next 8 bytes
}; __attribute((packed))__;  // <--- EDIT: I tried this packed, but does not give right values either.

main ()
{
     struct trd_t *trd;
     unsigned char *buffer;
     unsigned short len;
     unsigned char type;
     ...
     buffer = (unsigned char*) malloc(pkt_len);
     fread(buffer, pkt_len, 1 , fp)
     trd = (struct trd_t *) buffer;
     len = SWAPPED(trd->length);
     if (trd->type == 'T') {
       ....
     }
     ...

转换 (struct trd_t *)buffer 后,所有前几个结构元素都捕获了正确的数据,例如长度、类型、符号和 trd_size。 然而,trd_price 是错误的。
我期望它捕获“00 00 00 00 00 00 B8 60” 但是,它捕获“B8 60 41 42 43 00 00 17”

我尝试使用“attribute((packed));”在结构上,但它也没有帮助。

有什么想法吗?

最佳答案

如果您发现一个与您可能碰巧在某处找到的某些二进制数据完全匹配的 struct 布局,这或多或少纯粹是运气(并且可能会在编译器的下一个版本中崩溃)。

C 不对结构成员对齐或填充做出任何保证,尽管packed可能有所帮助。

您应该将文件内容分段读取到适当大小的字节缓冲区中,并从那里提取您的 struct 成员。

关于c - 在网络字节顺序上使用结构时得到错误的字节顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39766990/

相关文章:

c++ - 我可以将accept()与IOCP一起使用吗?

c - 在c代码的非阻塞设计中选择

c++ - OpenCV:我们需要删除 CvPoint 吗?如何删除?

c - 如何在 C 中将 UTC 时间转换为本地时间?

无法通过教程草图将数据从arduino mega上传到Cosm

java - 使用异步任务将大字符串从 Android 发送到 Servlet

c# - 识别 HTTP 响应来自的 NIC

c - isdigit() 问题; - scanf 验证器

交换 scanf() 调用时 C 程序未完全执行

python - 将连接的 SSL 套接字传递给另一个进程