1

Getting into socket programming with C++, and I'd like to find a way to marshal a series of data types into a string of bytes to be sent over a network via a socket using UDP.

Here's the method header

char * Message::marshal( int &n)

and the series of data types I need to marshal are:

int int int int float  //need to be all marshaled into the same byte string

The length is saved to n, and the string of bytes is returned in a character array. I'd also like to know how to unmarshal that string of bytes as well.

The server I'm working on most likely doesn't have boost library, and is probably not updated to C++ 11. The last server I was in wasn't, so I'm going to assume they didn't update them yet.

One method of serializing I saw was using streams, but I saw something about non portability (I'm writing the source code in windows, and then I'll change a few things for unix and compile it on the unix server).

I need to use standard C++ library stuff as again I have no control over the server.

Delliardo
  • 175
  • 2
  • 3
  • 15
  • for integral types you have `htons`, `htonl`, `ntohs`, and `ntohl` for byte ordering. For doubles [the issue is a bit stickier](http://stackoverflow.com/questions/10616883/how-to-convert-double-between-host-and-network-byte-order). And for what reason are you taking an int by reference? – Ryan Haining Feb 10 '15 at 03:41
  • @RyanHaining, I do have the freedom to change that variable to a float instead of a double, and the reference will store the size of the byte string so that the calling object will have that for the socket to assemble the packet. I'm also updating the information with the variables that need to be marshaled. – Delliardo Feb 10 '15 at 03:48
  • If you're not just doing this for fun, you should look at [protobuf](https://code.google.com/p/protobuf/) – Ryan Haining Feb 10 '15 at 03:50
  • @RyanHaining, I have no control over what's installed on the server, so I need to use what C++ has by default. – Delliardo Feb 10 '15 at 03:52
  • @RyanHaining, if you have any code examples, that would be greatly appreciated. – Delliardo Feb 11 '15 at 21:18
  • `uint32_t nbo = htonl(some_uint32_var); write(sock, &nbo, sizeof nbo);` – Ryan Haining Feb 11 '15 at 21:37

1 Answers1

0

I eventually found this post that led me to a solution. Didn't bother converting double to network byte order since the client and server are on the same machine. And for UDP, make sure to cast the structure as a char*.

Community
  • 1
  • 1
Delliardo
  • 175
  • 2
  • 3
  • 15