-1

Send struct with double pointer to struct over networkI have to send this huge structure that represents the directory structure over network. It looks like this:

typedef struct{
    char *name;
    int count;
    dir **subdir;
}dir;

I have to send this over network, which means I need to make a deep copy of this in a buffer and send it over TCP. I am pretty new to c and do not know how to make the copy of this whole hierarchy and especially how to reconstruct this on the other end. I am clear on how to handle network part. Please help.

MaxSteel
  • 259
  • 1
  • 6
  • 18
  • 1
    It needs to be _serialized_. That means you create a format by which the data can be completely recovered. With this structure there is no reason why you would need to fill a buffer before sending. You could just deliver chunks on-the-fly while doing a depth-first traversal of the structure. I am struggling to understand how you are having trouble with this idea when you can happily code networking logic in C. – paddy Feb 03 '16 at 04:21
  • Well, I've a framework in place to send and recv data. I am having difficulty in trying to understand how to deserialze data on the receiving end. – MaxSteel Feb 03 '16 at 04:23
  • 4
    You do the opposite of serializing, of course. If you have serialized your data, then perhaps you should show how you have done it. – paddy Feb 03 '16 at 04:25
  • 2
    [No need to invent it yourself](https://en.wikipedia.org/wiki/Comparison_of_data_serialization_formats), try protocol buffers or avro. – engineerC Feb 03 '16 at 04:48
  • It's curious that you have `int *name`. You'll need to know how long that array is, and send it over the wire one item at a time, with either a length before or an end indication after the data. (Note that C strings use an end indicator — a null byte.) The acronym that's often used TLV: type, length, value. Similarly with your matrix of directories — if that's what the `dir **subdir` represents; you'll need to encode the type of data that follows, with some way to tell when you've sent it all (either an up-front count or an end-of-data marker). Pointers can't usefully be sent directly. – Jonathan Leffler Feb 03 '16 at 05:10

1 Answers1

1

You can not send a pointer over the network because it is not real data. You need to send the real data that the pointer points to. On the sender's computer, you need a serialization method that converts the whole struct to a byte array and passes this byte array to the transmission framework (or TCP/IP stack).

On the other side (the receiver's computer), you need a de-serialization method that converts the received byte array to the original struct. In your case, I suggest that you study json-c, it will help. Serialize the whole struct by looping over every entry in dir and convert into a JSON string. It's quite easy because json-c will do the whole thing for you.

S Dao
  • 555
  • 4
  • 7