Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C sockets send/recv buffer type

Tags:

c++

c

unix

sockets

I'm working with unix sockets, and I can send() and recv() data when my buffer is of type char (ie. sending and receiving strings). I used Beej's guide to sockets, and the examples used were for send'ing/recv'ing strings.

Now I want to send/recv data of different types in one message.
For example, say in one message I want to send an integer, a string, a double and a float. How should I go about doing this? More specifically, of what type should my message 'buffer' be?

The prototypes for send and recv:

int recv (int socket, void *buffer, size_t size, int flags)
int send (int socket, void *buffer, size_t size, int flags)

I don't have too much experience with C/C++ and pointers, so this is probably a noob question.

If anyone can guide me in the right direction, I'd really appreciate it. Thanks

like image 945
user2125465 Avatar asked Feb 17 '23 08:02

user2125465


1 Answers

Unless you are planning to send vast amounts of data (many kilobytes) and often (several packets per second), I would suggest that you translate your data to strings (aka "serialize the data") and pass it that way. It has several benefits:

  1. It's portable - works no matter what size an int or float or double is - or what the padding between fields are in the structure.
  2. It's easy to debug (you can just look at the data and say whether it is right or wrong)
  3. It doesn't matter what byte-order the sending/receiving machines are.

Sending binary data, on the other hand is complex, because you need to worry about the individual sizes of data fields and their internal representation (byte order, how a double is represnted in binary, padding of data fields within structures, can't pass pointers, etc, etc). The only benefit is that binary data is a little more compact. But that only matters if you have many kilobytes and/or send lots of packets every second.

like image 129
Mats Petersson Avatar answered Feb 23 '23 21:02

Mats Petersson