Send struct over socket in C
Asked Answered
T

2

7

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\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, &regn, sizeof(regn));
printf("Size:%d\n", 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\n");
}
else
{
       printf("Message received:%s\n", recvBuf);
       printf("Size :%d\n", strlen(recvBuf));
       memcpy(&regn, recvBuf, sizeof(regn));
       printf("PID:%d\n", regn.clientPid);
       printf("MG:%s\n", 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.

Tonina answered 23/7, 2013 at 17:41 Comment(0)
M
10

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.

Messuage answered 23/7, 2013 at 17:43 Comment(5)
I want to send this data over the socket. Hence I am memcpy it to unsigned char*Tonina
@Tonina which function you use, if it takes size of data stored then you are to use sizeof(struct Registration)Messuage
@GrijeshChauhan In sendto() I replaced sizeof(data) with sizeof(regn) and it fixed the issue.Tonina
@sehe hey Sehe Thanks!, remember you :) you given a tricky answer that day in C++Messuage
@sehe Why int array[] = {}; is valid code ? I do not understand it ?Messuage
A
4

While the code will work if you send and recv on the same endian machine - your client and server should ideally perform a host to network endian conversion to maintain coherence when inspecting clientPid.

Arleanarlee answered 23/7, 2013 at 18:54 Comment(1)
Can you show how to perform htonl on a variable while sending?Tonina

© 2022 - 2024 — McMap. All rights reserved.