我正在开发一个客户端/服务器程序,我的客户端必须向服务器发送消息.
示例消息C结构:
struct Registration { char multicastGroup[24]; pid_t clientPid; };
用于序列化struct的客户端代码段
struct Registration regn ; regn.clientPid = getpid(); strcpy(regn.multicastGroup,"226.1.1.1"); printf("PID:%d\n",regn.clientPid); printf("MG:%s\n",regn.multicastGroup); printf("Size:%d\n",sizeof(regn)); //Size is 28 data = (unsigned char*)malloc(sizeof(regn)); memcpy(data,®n,sizeof(regn)); printf("Size:%d\n",sizeof(data)); //Size is 4.
用于反序列化数据的服务器代码
if(recvfrom(sd,recvBuf,recvBufSize,(struct sockaddr*)&clientAddr,&len) < 0) { printf("Error receiving message from client\n"); } else { printf("Message received:%s\n",recvBuf); printf("Size :%d\n",strlen(recvBuf)); memcpy(®n,sizeof(regn)); printf("PID:%d\n",regn.clientPid); printf("MG:%s\n",regn.multicastGroup); }
将结构复制到unsigned char *后,数组的大小仅为4.
为什么数据没有完全复制到数组?
服务器无法从char数组重构结构.
请让我知道我做错了什么.