sending problem in BSD socket programming

sending problem in BSD socket programming

Post by Mafa » Tue, 20 Aug 2002 15:41:31



I'm writing a program to send the following data structure

struct sendData{
  int dataSize;
  long key;
  unsigned data };

I'm wonder that can I send it through a socket by using SEND(). If not,
what should i do ?? How to send a integer in the socket programe ??

Thanks.

 
 
 

sending problem in BSD socket programming

Post by Nils O. Sel?sd » Tue, 20 Aug 2002 16:08:57



> I'm writing a program to send the following data structure

> struct sendData{
>   int dataSize;
>   long key;
>   unsigned data };

> I'm wonder that can I send it through a socket by using SEND(). If not,
> what should i do ?? How to send a integer in the socket programe ??

you should be able to do that.
struct sendData myvar;
...

send(sock,&myvar,sizeof(myvar),0);

Just remeber you'll be in trouble if the other end dont have the same
endianness as yours -  man htons

 
 
 

sending problem in BSD socket programming

Post by Bjorn Rees » Tue, 20 Aug 2002 17:53:29



> Just remeber you'll be in trouble if the other end dont have the same
> endianness as yours -  man htons

Or if the other end uses a different size [1] or encoding [2] of the
primitive types, or a different alignment [3] or ordering [4] of the
elements in the struct.

In summary, do not exchange (e.g. through sockets or files) structs
without proper serialization.

[1] E.g. on some platforms a long is 32 bits wide, on others 64 bits.
[2] Besides endianess, the hardware could, theoretically, implement
    integers with floating-point number to save circuits. This can
    be done with what C99 refers to as "trap representation."
[3] E.g. some platforms will align longs to 32 bit boundaries, others
    to 64 bit boundaries.
[4] Optimizing compilers may rearrange elements within a struct to
    give a smaller memory footprint.