Sending struct over TCP (C-programming)

2019-04-13 22:40发布

I have a client and server program where I want to send an entire struct from the client and then output the struct member "ID" on the server.

I have done all the connecting etc and already managed to send a string through:

send(socket, string, string_size, 0);

So, is it possible to send a struct instead of a string through send()? Can I just replace my buffer on the server to be an empty struct of the same type and go?

7条回答
你好瞎i
2楼-- · 2019-04-13 23:16

Welll... sending structs through the network is kinda hard if you are doing it properly.

Carl is right - you can send a struct through a network by saying:

send(socket, (char*)my_struct, sizeof(my_struct), 0);

But here's the thing:

  • sizeof(my_struct) might change between the client and server. Compilers often do some amount of padding and alignment, so unless you define alignment explicitly (maybe using a #pragma pack()), that size may be different.
  • The other problem tends to be byte-order. Some machines are big-endian and others are little-endian, so the arrangement of the bytes might be different. In reality, unless your server or client is running on non-Intel hardware (which is probably not the case) then this problem exists more in theory than in practice.

So the solution people often propose is to have a routine that serializes the struct. That is, it sends the struct one data member at a time, ensuring that the client and server only send() and recv() the exact specified number of bytes that you code into your program.

查看更多
登录 后发表回答