0
votes

I want to send/receive structs containing float and int variables in client/server socket programs written in C++.

Earlier, the code was written in C, so I was simply sending them as follows:

//structure definition
struct {
    float a;
    float b;
    float c;
    float d[2];

}myStruct_;

//code to send struct
int slen = sizeof(client_sock)

if(recvfrom(sockFD, &myStruct_, sizeof(myStruct_), 0 ,(struct sockaddr *)&client_sock, &slen)<0) {
            printf("Failure while receiving data %d" , WSAGetLastError());
            getchar();
            exit(1);
}

But now in C++, this is giving me this error message:

error: cannot convert '(anonymous struct)*' to 'char *' for argument '2' to 'int recvfrom(SOCKET, char*, int, int, sockaddr*, int*)'

I tried to look for this error, and found out that I have to serialize the struct before sending, and later deserialize the same to get the exact structure. Could you suggest/or provide an example how to serialize and de-serialize it?

1
You can just cast it like this: (char *)&myStructOscar
if i cast it into (char *) then how do i get the original struct back at the receiver's end?Anmol Bhatia
At the receiving end you cast the address of an identical struct to char* and copy the receive buffer into that.Galik
"will the same thing work for float and int variables?" Maybe. Gotchas are endianness and the size of an integer being different on different platforms and compiler toolkits.user4581301
The problem with floats is they are platform/architecture specific so if you are sending them to a different platform/architecture you might do better sending text rather than binary.Galik

1 Answers

1
votes

The code you showed will work fine in C++ with a little tweaking.

In some platforms (like Linux), recvfrom() is defined as expecting a void* pointer to the memory buffer that it will fill in. In other platforms (like Windows), recvfrom() expects a char* pointer instead.

To get rid of the error, simply type-cast the buffer pointer (just like you do with the 5th parameter, where you are passing a sockaddr_in* pointer where a sockaddr* pointer is expected):

recvfrom(sockFD, (char*)&myStruct_, sizeof(myStruct_), 0, (struct sockaddr *)&client_sock, &slen);

Do the same thing when sending a struct:

sendto(sockFD, (char*)&myStruct_, sizeof(myStruct_), 0, (struct sockaddr *)&server_sock, &slen);