1

I'm working on a remoting control program. I need to send and receive multiple data at once. I use this solution:

struct PACKET
{
    int x;
    int y;
};

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

However, I'm considering if this is a safe way to do so. Should I find another solution?

user3366592
  • 439
  • 7
  • 23
  • 1
    As you can see in vsoftcos answer, there are alot of pitfalls. If you do not want to worry about them, there is [Google Protobuf](https://github.com/google/protobuf/) that takes care of many things for you. However it adds another compiler step for you to handle. – Slyps Jun 01 '15 at 22:21

1 Answers1

1

It is not safe, unless you can guarantee at least that your structure is a POD, which it is in your case, and that both platforms use the same endianness, which you don't know.

EDIT

There are some additional issues that may occur: alignment is one (the compiler may pad your structure with additional bits), then the data itself can be represented using different models. Thanks to @Andrew and @Slyps for the comments.

So after all it seems that unless you know exactly your data alignment/representation model/endianness on both platforms, you are not safe.

Community
  • 1
  • 1
vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • Well, you can still know about endianness if you control both endpoints of the connection. – Greg Hewgill Jun 01 '15 at 22:09
  • @GregHewgill yes, that's true, if you write a program for your own remote device. Edited it. – vsoftco Jun 01 '15 at 22:10
  • Not just endianness - data model and compiler specifics, too. A `long` in an ILP32 data model is different from a `long` in an LP64 data model. Different compilers and/or optimization options can also change the way a structure is laid out. – Andrew Henle Jun 01 '15 at 22:15
  • Alignment might also stab you in your back. [Link](https://msdn.microsoft.com/en-us/library/aa273913(v=vs.60).aspx)/[Link](https://gcc.gnu.org/onlinedocs/gcc/Structure-Packing-Pragmas.html) – Slyps Jun 01 '15 at 22:15
  • @Andrew, Slyps thanks for the comments. I was aware of alignment and forgot to mention. However I did not know that the data itself can be represented differently. – vsoftco Jun 01 '15 at 22:18
  • To clarify this a little, if you can be sure that both ends of the connection are running the exact same executable, then it is safe. – Harry Johnston Jun 03 '15 at 00:28