I have a struct that’s used in my internet application, which looks like:
struct query {
ushort trans_id;
ushort flags;
ushort opcode;
ushort content_length;
char content[512];
};
Basically, I’m just trying to take this structure and turn it into a “packet” to be sent. It must have the corresponding length and everything. So; if I could I would have like:
struct query q;
q.trans_id = 0x5544;
q.flags = 0x0000;
q.opcode = 0x0010;
q.content_length = 0x0001;
q.content[0] = '\0'; //I would want my packet to end up looking like this, when outputted to the socket:
//\x55\x44\x00\x00\x00\x10\x00\x01\x00
//and yes, it's going to be stored in a char buffer, but I'm not using any functions that will trim off any of the things past the null!
I feel like it’s a relatively simple question that can probably be answered by casting my data types, but I think it’s a bit harder than that.
I also did try using sprintf, but it would turn my nulls into actual 0s, so 0x0000 would become 2 ‘0’ ASCII characters!
You can indeed simply cast the pointer to your struct to a char *, such as:
If you want the packet size to trim the content of the query struct, you’ll have to calculate the difference (by using strnlen for example on the content and subtracting the difference)
EDIT: Alternatively for trimming you can do: