开发者

Send struct over c sockets

I am b开发者_如何学运维uilding a UDP chat app. Is it safe sending C struct over c socket and on the other end memset received data? All data in struct is nullpaded with memset, so I assume the size of the struct is always constant. What problems may I encounter?

How are more experienced programmers approaching this?


Yes it is safe BUT we should caveat this first. You may run into a problem if you are passing it between disparate platforms and then you need to worry about byte ordering/packing (amongst a host of other issues possibly). That being said, if you don't know how to do any of this, then it is not safe to assume that you will reliably receive the struct in the same order you sent it.


However you do it, unit test the hell out of it. Compilers and platforms vary a lot on these points, so don't ever assume blindly that it is consistent.

Compilers may change struct alignment at their whim (for performance reasons, for example). Asking for some restrictions are generally compiler specific, though this one is supported by MSVC and gcc (through an extension)

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

This forces it to align on 1 byte boundaries, so no booleans.

If you want to be fully compliant, then serialize each field yourself. It really isn't all that much work.

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


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

This doesn't make a lot of sense. Objects always have a fixed size. "Nullpadding with memset" has nothing to do with it.

Is it safe sending C struct over c socket and on the other end memset received data?

No, not really.

Better to consider sending "data" rather than the exact, byte-wise, physical contents of an object in your memory.

What problems may I encounter?

  • Member padding
  • Data alignment
  • Type sizes
  • Endianness
  • Indirection — pointers to data rather than the data itself

How are more experienced programmers approaching this?

Best do serialisation properly.

Create a data format that your application will recognise no matter what machine it's on, and use that to represent your chat data.

  1. Sometimes for efficiency you have to design a binary format, and use clever, robust techniques to deserialise the information properly on the target machine, taking the above listed considerations into account.

  2. However, for simple work, you can just use human-readable text format. Can't really go wrong with that.


You have to be careful that your struct doesn't contain pointers (like char* strings). That applies when you store a std::string inside the struct as well, because the std::string has a pointer inside of it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜