windows - Linux 客户端和 Windows 服务器之间的套接字 "recv"函数中的结构困惑,适用于 Windows

标签 windows linux sockets struct cross-platform

我得到了这样的客户端和服务器结构:

{
   char type;
   int payloadLen;
   char fileName[50];
   int fileIndex;
   int blockOffset;
   int blockLen;
   char streamingData[MAX];
   int h264fileLayer;
 }

在客户端中我接收到类似的数据

memset(&data_recevied, 0, sizeof(data_received);
recv(sockfd, (char *)&data_received, sizeof(data_received), 0);

我用它来接收从服务器发送的文件,前几个文件一切正常,然后它坏了,当它坏了时我检查了结构,它接收到的结构似乎一团糟,fileIndex 也太乱了很大,但是客户端程序在带有 winsock lib 的 Windows 中运行良好,完全没有损坏。

我认为这与跨平台有关,也许我遗漏了什么,真的可以在这里使用帮助,谢谢

最佳答案

在程序之间发送这种结构不是个好主意。运气好的话可能会奏效。

有几个原因可能导致该问题:

  1. 发送方使用与接收方不同的对齐方式
  2. int 的大小在不同的系统中可以不同
  3. 字节顺序可以不同。如果两个程序都在 PC 上运行,那么字节顺序不是问题。

您可以尝试使用以下方式删除填充(对齐):

Linux:

typedef struct 
{    
    char type;    
    int payloadLen;   
    ...
}  __attribute__ ((packed)) my_type_t;

Windows :

#pragma pack(push, 1)

typedef struct 
{    
    char type;    
    int payloadLen;   
    ...
} my_type_t;

#pragma pack(pop)

如果仍然有问题,则使用 int32_t(或其他一些固定大小的类型)代替 int。

关于windows - Linux 客户端和 Windows 服务器之间的套接字 "recv"函数中的结构困惑,适用于 Windows,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8503502/

相关文章:

c - Linux 与 Windows 上的 printf

windows - 如何调试使用 squirrel 打包的 electron 应用程序在某些计算机上无法启动

windows - 在 Windows 7 中断开共享时如何避免 12 秒延迟?

ruby - 在 Linux Mint 17 上安装 Ruby on Rails

python - 在MQL5中接受Python生成的套接字的输出

python - Windows + virtualenv + pip + NumPy(安装 NumPy 时出现问题)

php - 服务器上永远运行的进程

ptrace 是否可以导致被跟踪进程在不访问可执行系统调用指令的情况下执行系统调用?

c++ - 帮助在 Visual C++ Express 中进行链接

sockets - 服务器和客户端之间成功的 TCP 连接