通过套接字发送和接收原始结构不安全吗?

Is it unsafe to send and receive raw structures through sockets?

我正在开发一个远程控制程序。我需要一次发送和接收多个数据。我使用这个解决方案:

struct PACKET
{
    int x;
    int y;
};

//...
PACKET p;
p.x = 10;
p.y = 5;
send(socket, (char*)&p, sizeof(PACKET), 0);

不过,我正在考虑这样做是否安全。我应该寻找其他解决方案吗?

这是不安全的,除非你至少可以保证你的结构是一个你不知道的POD, which it is in your case, and that both platforms use the same endianness

编辑

可能会出现一些其他问题:对齐是其中之一(编译器可能会用额外的位填充您的结构),然后数据本身可以使用不同的模型表示。感谢@Andrew 和@Slyps 的评论。

所以毕竟似乎除非你确切知道你在两个平台上的数据 alignment/representation model/endianness,否则你是不安全的。