Hey. I want to make a packet structure, something like

struct Packet {
  int cmd; /* command */
  int len; /* length of body */
  char body[30]; /* body (should be length of len though, might use std::string) */
};

Now, if I recieve some data thru a socket (I'm using some socket class based on Winsock2 and for the client SDL_net) read data (command, length & body) into a Packet structure?

Basically I'm wanting the socket stream to look like cmd len body for example 0x01 0x05 hello , but I don't know how I'd parse that into a Packet structure.

anyone? it shouldn't be too hard...

copy your packet struct into a char buffer on the send side then send the buffer:

char buffer[512];
Packet packet;

//populate packet struct

memcpy(&buffer, (char*)&packet, sizeof(packet));

//send buffer

Then just do the reverse on the receive side.

Packet packet;

//receive buffer

memcpy(&packet, buffer, sizeof(buffer));

Is this what you were asking?

Yeah (thanks), but the problem is I don't know how I'd recieve them.

I don't really need to throw them in a Packet struct; I just need to parse out a command / body. I need a way to parse out cmd len body from the socket stream and deal with it in my code.

It really doesn't matter - right now I'm using strings & newlines to send data thru a socket, I just want a better protocol.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.