Aamir Khan
Aamir Khan

Reputation: 3031

Sending a structure over a socket

I'm trying to implement a a program to send a structure over a c++ socket from a client to a server.

What I have so far is working fine on my own computer (Both server and client on my own computer) but I suspect I may have trouble when running the server and client on different computers.

What I have so far is:

struct myStruct
{
    int whatever;
};

//Sender

myStruct obj;
obj.whatever = 123;
char *byteStream = (char *) &obj;

write(socketFD, byteStream, sizeof(myStruct));

//Receiver

char *byteStream = new char[sizeof(myStruct)];
read(socketFD, byteStream, sizeof(myStruct));

myStruct *received = (myStruct *) byteStream;
cout<<received->whatever;

The cout statement at ther receiver prints 123.

Upvotes: 2

Views: 1940

Answers (4)

mvp
mvp

Reputation: 116407

You should seriously consider some kind of serialization library. JSON is very popular and very easy to debug because it is essentially text format. Google protocol buffers are much more efficient, but requires more effort to make it work. There are also other similar libraries like Thrift.

Upvotes: 1

Bathsheba
Bathsheba

Reputation: 234865

That's fine for now as long as endianness and structure packing are preserved (once you have more than one data member in your struct), but, using sizeof(myStruct) will give you problems when you have data members in your structure that allocate heap memory.

I wouldn't rely on sizeof from the outset. Build a function to get the data size and use that.

Upvotes: 2

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137527

Different systems may use different byte order and structure padding. You need to be sure your structures are packed on both sides. You should generally always send multi-byte integers in network-order (big endian). Convert between byte orders with ntohl and friends.

Upvotes: 3

Reunanen
Reunanen

Reputation: 8031

This should work on different computers as long as the byte order is the same (e.g., both are PCs).

Upvotes: 4

Related Questions