C socket for Linux (how to pass a struct?)

3

I have a client / server application and I need to transfer a struct to the server, but this is not working:

typedef struct{
   int pontos;
   int vidas;
   int flagReiniciar;
   int flagAcabar;
   int matriz[21][19];
} dados; 


send(sockfd,&bufferDados,sizeof(dados),0);
recv(sockfd,&bufferDados,sizeof(dados),0);

Is there any way to do this? or can not pass a struct via socket?

    
asked by anonymous 14.09.2015 / 07:04

1 answer

5

You can not pass a binary structure directly because the server machine can use a processor other than the client. Each processor organizes structures, and even numeric types, differently in memory.

The ideal would be to create a protocol, for example by converting the values to JSON or XML and interpreting on the other side. But it is possible to use binary structures, following some rules:

a) structures should be identified as attribute ( packed )) that tells the compiler that all values must be stuck, with no spacing for alignment. Each processor uses a different alignment, so completely shutting down the alignment removes a problem.

b) structures must use numeric types with defined size (uint32_t, int16_t, etc) because they are the same in any architecture. This ensures that the types and therefore the structures will have the same size regardless of processor or architecture.

c) you will need to convert all integer types to a common representation, using htons () and htonl () in the stream, and ntohl / ntohs () on the reception. The first functions convert the value to big endian (TCP / IP standard) and the second ones convert to the local endian. So, even if one processor is big endian and another little endian, they will understand each other.

d) It is a good idea to have two versions of each structure: one for program use, and another for network communication only. Only the second version needs to have the alignment turned off. You copy the data from one to the other by doing the conversions specified in (c).

An integer value converted with htonl () can no longer be used locally, otherwise it will be taken for the wrong value (eg Htons (1) "worth" 256 on an Intel). Keeping values converted to structures used exclusively for network transmission helps and avoid confusion.

    
14.09.2015 / 08:12