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

Asked

Viewed 294 times

3

I have a client/server application and need to transfer a struct to the server, but this way 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 that? or is there no way to pass a struct via socket?

  • Ahh, I read something about creating a protocol, which would be more interesting to me, but I have no idea how to do that.

1 answer

5


You cannot pass a binary structure directly because the server machine can use a different processor from the client. Each processor organizes structures, and even numerical 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 a few rules:

a) the structures shall be identified as attribute((packed)) which tells the compiler that all values must be glued together, with no spacing for alignment. Each processor uses a different alignment, so turning off the alignment completely removes a problem.

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

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

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

An integer value converted with htonl() or htons() can no longer be used locally, otherwise it is taken wrong (e.g. htons(1) "valley" 256 on an Intel computer). Keep the converted values in structures used exclusively for network transmission help and avoid confusion.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.