Send struct over c sockets

I am creating a UDP chat application. Is it safe to send C struct over c socket and the received memset data at the other end? All data in the struct is ignored with memset, so I assume that the size of the structure is always constant. What problems can I encounter?

How do more experienced programmers approach this?

+4
source share
4 answers

Yes, it is safe, but we must warn this first. You may run into a problem if you pass it between disparate platforms, and then you need to worry about ordering / packing bytes (possibly due to many other problems). If you do not know how to do this, it is unsafe to assume that you will reliably receive a struct in the same order that you sent it.

+6
source

However, you do this, unit test damn it. Compilers and platforms are very different at these points, so never blindly allow them to be consistent.

Compilers can change the alignment of the structure at their whim (for example, for performance reasons). Setting some restrictions is usually specific to the compiler, although this one is supported by MSVC and gcc (via extension)

 #pragma pack(push, 1) struct Foo { // .. }; #pragma pack(pop) 

This forces it to align 1 byte, so there are no boolean elements.

If you want to be fully compatible, serialize each field yourself. It really doesn't work that much.

You will also have to deal with content, as others have mentioned.

+5
source

All data in the struct is ignored with memset, so I assume that the size of the structure is always constant.

It doesn’t make much sense. Objects always have a fixed size. "Nullpadding with memset" has nothing to do with it.

Is sending a C-structure via a c-socket safe and the received data is accepted on the other end?

No, not at all.

It is better to consider sending "data" rather than the exact, byte-muddy physical content of the object in your memory.

What problems can I encounter?

  • Fill Item
  • Data alignment
  • Typical sizes
  • Byte order
  • Direction - pointers to data, not data itself

How do more experienced programmers approach this?

Serialization is best.

Create a data format that your application will recognize no matter what machine it runs on, and use this to represent chat data.

  • Sometimes, for efficiency, you need to create a binary format and use smart, reliable methods to deserialize information on the target computer, given the above considerations.

  • However, for simple operation, you can simply use a text format for human reading. This is actually not the case.

+3
source

You must be careful that your structure does not contain pointers (e.g. char* strings). This applies when you store std::string inside a structure, since std::string has a pointer inside it.

+1
source

Source: https://habr.com/ru/post/1368977/


All Articles