Variable sized packet structs with vectors

Posted by Rev316 on Stack Overflow See other posts from Stack Overflow or by Rev316
Published on 2010-03-07T08:59:46Z Indexed on 2010/03/08 5:21 UTC
Read the original article Hit count: 345

Filed under:
|
|

Lately I've been diving into network programming, and I'm having some difficulty constructing a packet with a variable "data" property. Several prior questions have helped tremendously, but I'm still lacking some implementation details. I'm trying to avoid using variable sized arrays, and just use a vector. But I can't get it to be transmitted correctly, and I believe it's somewhere during serialization.

Now for some code.

Packet Header

class Packet {

    public:         
        void* Serialize();
        bool Deserialize(void *message);

        unsigned int sender_id;
        unsigned int sequence_number;
        std::vector<char> data;
};

Packet ImpL

typedef struct {
    unsigned int sender_id;
    unsigned int sequence_number;
    std::vector<char> data;
} Packet;

void* Packet::Serialize(int size) {
    Packet* p = (Packet *) malloc(8 + 30);
    p->sender_id = htonl(this->sender_id);
    p->sequence_number = htonl(this->sequence_number);
    p->data.assign(size,'&'); //just for testing purposes
}

bool Packet::Deserialize(void *message) {
   Packet *s = (Packet*)message;
   this->sender_id = ntohl(s->sender_id);
   this->sequence_number = ntohl(s->sequence_number);
   this->data = s->data;
}

During execution, I simply create a packet, assign it's members, and send/receive accordingly. The above methods are only responsible for serialization. Unfortunately, the data never gets transferred.

Couple of things to point out here. I'm guessing the malloc is wrong, but I'm not sure how else to compute it (i.e. what other value it would be). Other than that, I'm unsure of the proper way to use a vector in this fashion, and would love for someone to show me how (code examples please!) :)

Edit: I've awarded the question to the most comprehensive answer regarding the implementation with a vector data property. Appreciate all the responses!

© Stack Overflow or respective owner

Related posts about c++

Related posts about network-programming