Re: sending a struct over TCP
On Mar 27, 9:03 am, "Jack" <accpac...@hotmail.com> wrote:
Hi, All,
is it possible to send a struct using the the send function. Here is
what I mean
typedef struct{
int ID;
char name[20];
}sampleStruct;
int main(){
sampleStruct a;
//lets assume we have filled out our sin_family and etc. so
we'll have something like:
sd = socket (AF_INET, SOCK_STREAM, 0);
connect (sd, (struct sockaddr*) &socketChannel, sizeof(struct
sockaddr);
a.ID = 1;
a.name="Bob";
send(sd, (void*) a, sizeof(a), 0);
..
..
..
}
Is there anyway to make this work or do I need to make a char buffer
and write
buffer[100] = "1 Bob";
send(sd, (void*) buffer, strlen(buffer), 0);
Thanks
Dear Jack,
You can send it using the same send function without having another
char buffer.
since a is an object of your struct you need to give the address of
it.
i.e
send(sd, (void*)&a, sizeof(a), 0); will resolve your issue.
One thing you've to notice while dealing with structure variables.
the size of the structure will be aligned according the pack size you
are specifying. Normally the default alignment for the structure
members will be 4 bytes in size.
i.e if you declare
struct MyStruct
{
int a;
char buff[21]; //Oops I meant 20 letters for name and extra one
byte for null character
};
You might be expecting a size 25 bytes for this structure but if you
are giving alignment bytes 4, the size of the struct will be 28 bytes.
(24 for buff and 4 for variable a)
As per your code you will be sending some extra bytes because of the
alignment and you've to make sure that, at the client side too, you
are having same structure alignment. else you may face some unexpected
behavior.
You can specify the alignment using "#pragma pack" directive
#pragma pack(1) // alignment will be 1 byte you will get the exact
size of members
#pragma pack(2) // alignment will be 2 byte members will be aligned to
2 bytes
#pragma pack(4) // alignment will be 4 byte members will be aligned to
4 bytes
#pragma pack(8) // alignment will be 8 byte members will be aligned to
8 bytes
Normally this will be set to the wordlength of the processsor. i.e 4
bytes if you are using 32 bit architecture or 8 bytes if you are using
64 bit architecture.
and for strict size information we will use 1 byte alignment.