Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

serialization - Send struct over socket in C

I am developing a client/server program and my client has to send messages to the server.

Sample message C structure:

struct Registration
{
char multicastGroup[24];
pid_t clientPid;
};

Client code snippet to serialize struct

struct Registration regn ;
regn.clientPid = getpid();
strcpy(regn.multicastGroup, "226.1.1.1");

printf("PID:%d
", regn.clientPid);        
printf("MG:%s
", regn.multicastGroup);
printf("Size:%d
", sizeof(regn));           //Size is 28

data = (unsigned char*)malloc(sizeof(regn));
memcpy(data, &regn, sizeof(regn));
printf("Size:%d
", sizeof(data));           //Size is 4.  

Server code to de-serialize data

if(recvfrom(sd, recvBuf, recvBufSize, 0, (struct sockaddr*)&clientAddr, &len) < 0)
{
       printf("Error receiving message from client
");
}
else
{
       printf("Message received:%s
", recvBuf);
       printf("Size :%d
", strlen(recvBuf));
       memcpy(&regn, recvBuf, sizeof(regn));
       printf("PID:%d
", regn.clientPid);
       printf("MG:%s
", regn.multicastGroup);
}

After copying the struct to unsigned char *, the size of the array is only 4.
Why is data not fully copied to the array?

The server is not able to reconstruct the struct from the char array.
Please let me know what am I doing wrong.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

sizeof(regn) gives size of your complete structure Registration, wheras sizeof(data) is size of pointer on your machine that is 4 bytes (data should be pointer of Registration type).

In expression:

memcpy(data, &regn, sizeof(regn));
        ^     ^
        |     value variable of struct type 
        is pointer

also notice in printf, . is used to access elements e.g. regn.multicastGroup.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...