I'm still trying to learn my way through send and recv with sockets in C. Now, I have a struct that I want to send over the socket.
struct myPacket {
int a;
double b;
double c;
int d;
char e[80];
};
I have a client on a big-endian machine and a server on a little-endian machine. My goal at the moment is to be able to fill in the values of the struct using scanf (got that done) and then send the struct to the server and have the server print out the values for A,B,C,D, and E. I'm struggling in trying to find a way to serialize the struct and then deserialize it on the server side.
I found in another forum the suggestion to use memcpy to get it into an unsigned char array.
struct myPacket msg;
unsigned char buffer[sizeof(msg)];
memcpy(&buffer, &msg, sizeof(msg));
send(sockfd,buffer,sizeof(buffer),0);
I'm not sure how to undo this process on the server side, however. I tried this:
struct myPacket *msg;
struct myPacket theMsg;
retval = recv(clientfd, buffer, 112, 0);
msg = (struct myPacket *)&buffer;
theMsg = *msg;
And was able to printf the contents of theMsg.a successfully (after doing an ntohl(theMsg.a) to account for the byte order), however the rest of the contents were garbage (I am switching the byte order - still garbage).
I would appreciate some help!
Thanks,
--Dan