Sending structures as packets using Send function in Socket programming

Hi,
I have created a socket using: SOCKET sock;
and would like to send a structure over to the reciever using the send command,but when i type the send command,I get an option of:
int socket(SOCKET s,const char* buf,int len,int flags)
but I would like to send a structure with a set of items.How do I implement this
Thanks



Answer this question

Sending structures as packets using Send function in Socket programming

  • jim rozak

    Be sure to keep struct member alignment in mind when you do this. Having different alignments in the sender and receiver will surely mess things up. You should also consider having a 1-byte alignment, for possibly lower overhead in the transfers. This latter part depends greatly on how your program will behave, though.

  • format1337

    I assume you meant send(). Just cast the structure instance to const char*. For example:

    struct MyStruct {
    int a;
    long b;
    };

    void test(SOCKET sock) {
    MyStruct inst;
    send(sock, (const char*)&inst, sizeof(inst), 0);
    }



  • DaveSimmons

    If I where to use this and send that struct from a Windows box to a Linux box, will the floating point number be OK Eg. Sending 70.98 in the struct – will it come out the other end as 70.98 or will the floating point number be interpreted differently due to the compiler

    Thanks,


  • Naolin

    EToreo wrote:

    Is this the best advice I ask because it seems like a shame to send all that data when you could just be sending 4 bytes to update a client’s floating point number.

    Thank you for the replies.

    Well yes. Unless you know *exactly* how the floats are binary represented on the target box, that's your best bet.



  • odv

    EToreo wrote:

    If I where to use this and send that struct from a Windows box to a Linux box, will the floating point number be OK Eg. Sending 70.98 in the struct – will it come out the other end as 70.98 or will the floating point number be interpreted differently due to the compiler

    It's likely to. You should send floating points as their string representation.



  • capitapicard

    "You should send floating points as their string representation."

    Is this the best advice I ask because it seems like a shame to send all that data when you could just be sending 4 bytes to update a client’s floating point number.

    Thank you for the replies.



  • akin_l

    It depends on what kind of hardware you have on linux. If it is 8086 derivative it should work
  • lachlanj

    Thank you for your message it was really helpful,
    i am having problem with casting const char * to struct now, Smile
    i know reading bytes into struct from a file, with fread but this seems different.


  • Tryin2Bgood

    Thank you very much!!


  • Sending structures as packets using Send function in Socket programming