我试图通过 TCP 套接字发送一个结构数组,方法是将它作为字节数组(char*)发送,然后在接收端将其转换回原始结构类型。
该结构包含照片的数据,如下所示:
struct photo{ //List that will store photo information
uint32_t id_photo;
char *file_name;
struct keyword * key_head;
struct photo * next;
};
然后我像这样发送它:
photolist p_list[photocount];//Photo count = nº of elements to be sent
for(int i = 0; i<photocount; i++){
p_list[i]=*aux;
p_list[i].key_head = NULL;
aux = aux->next;
}
//Sending list of photos to the new peer
buff = malloc(sizeof(photolist)*photocount);
memcpy(buff, p_list, sizeof(photolist)*photocount);
nbytes = send(fd, buff, sizeof(photolist)*photocount, 0);
最后我像这样收到它(数组的元素数量之前已成功接收):
buff = (char *) malloc(sizeof(photolist)*photosize);
nbytes = recv(sock_fd_server, buff, sizeof(photolist)*photosize, 0);
if(nbytes == -1){
perror("Reciving");
exit(-1);
}
photolist testlist[photosize];
memcpy(testlist, buff, sizeof(photolist)*photosize);
但是,当我在收到结构元素后尝试打印它时,会发生分段错误。我在发送之前和接收之后打印了缓冲区,只是为了查看数据是否相同,并且确实如此,所以我不知道我做错了什么。任何帮助将不胜感激,并提前致谢!
您还没有提供 photolist 的定义但是如果您要发送类似的结构
struct photo{ //List that will store photo information
uint32_t id_photo;
char *file_name;
struct keyword * key_head;
struct photo * next;
};
从客户端到服务器并file_name
在服务器上访问它不会工作,因为 file_name 包含来自客户端程序的地址它在服务器程序中无效
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句