Serialize/Deserializar struct for sending via sockets

Asked

Viewed 70 times

2

I have a struct that I would like to serialize/disallow to send in a connection via sockets using the function send and recover that struct with the function recv, what are the ways I can solve this problem? I am aware of the function htons but I haven’t figured out how to use it effectively in a struct.

Struct to Serialize/Deserialize

struct header
{
    uint32_t payload_len;
    uint32_t psecret;
    uint16_t step;
    uint16_t student_id;
};

typedef struct header Cabecalho;


struct packet
{
    Cabecalho* cabecalho;
    char* msg;
};

typedef struct packet Pacote;

In that case I need to send the struct packet to the network.

1 answer

0

First of all, whenever you travel through the network structures like the one you show you need to worry about the alignment of the fields of the structure. In this specific case nothing needs to be done, but it is something to keep in mind.

// ------------------------------

typedef struct Header
{
  uint32_t payload_len;
  uint32_t psecret;
  uint16_t step;
  uint16_t student_id;
} Header;

typedef struct Packet
{
  Header header;
  char* msg;
} Packet;

// ------------------------------

// este e' o header que sua aplicacao vai usar localmente
Header header;

// esta e' o pacote que vai ser enviado ou recebido pela rede
Packet packet;

// ------------------------------

// no envio

packet.header.payload_len = htonl(header.paylod_len);
packet.header.psecret     = htonl(header.psecret);
packet.header.step        = htons(header.step);
packet.header.student_id  = htons(header.student_id);

n = send(fd, &packet, ....);

// ------------------------------

// na recepcao

n = recv(fd, &packet, ....);

header.paylod_len = ntohl(packet.header.payload_len);
header.psecret    = ntohl(packet.header.psecret);
header.step       = ntohs(packet.header.step);
header.student_id = ntohs(packet.header.student_id);

// ------------------------------

Browser other questions tagged

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