Send struct over socket in C

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

Example message structure C :

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

client code snippet for serializing structure

 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 for de-serializing 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 structure to unsigned char * size of the array will be 4. Why are the data not completely copied to the array?

The server cannot restore the structure from the char array.
Please let me know what I am doing wrong.

+7
c serialization client-server
source share
3 answers

sizeof(regn) gives the size of your full Registration structure, where sizeof(data) is the size of the pointer on your computer, which is 4 bytes ( data should be a pointer of type Registration ).

In the expression:

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

also noted in printf,. used to access items, for example. regn.multicastGroup .

+10
source share

While the code will work if you send and return the same destination computer, your client and server should ideally execute the host to convert over the network to the end, in order to maintain consistency when checking clientPid.

+3
source share

For portability reasons, it is advisable to serialize each element of the structure individually due to the specifics of the platform and the addition of the structure.

Here is an example of using Binn :

  binn *obj; // create a new object obj = binn_object(); // add values to it binn_object_set_int32(obj, "clientPid", getpid()); // assuming it is 32 bits binn_object_set_str(obj, "multicastGroup", "226.1.1.1"); // send over the network send(sock, binn_ptr(obj), binn_size(obj)); // release the buffer binn_free(obj); 

These are just 2 files (binn.c and binn.h), so it can be compiled into a project instead of being used as a shared library.

You might also need to use the message framework (also known as length cropping) in socket streams to avoid the collaboration of messages and fragmented messages.

0
source share

All Articles