Send struct with double pointer to struct over network

时间:2016-02-03 04:14:40

标签: c unix struct deep-copy

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.

1 个答案:

答案 0 :(得分:1)

您无法通过网络发送指针,因为它不是真实数据。您需要发送指针指向的实际数据。在发送者的计算机上,您需要一个序列化方法,将整个结构转换为字节数组,并将此字节数组传递给传输框架(或TCP / IP堆栈)。

另一方面(接收者的计算机),您需要一个反序列化方法,将接收到的字节数组转换为原始结构。在您的情况下,我建议您学习json-c,这会有所帮助。通过循环dir中的每个条目并转换为JSON字符串来序列化整个结构。这很容易,因为json-c会为你完成整个事情。