15

I've got a struct:

typedef     struct {
    char            *typ;
    cid_t           cid;
    unsigned short  nbytes;
    char            *data;
} req_s; 

typedef     struct {
    char            *ip;
    unsigned short  pid;
} cid_t;

and I want to send it over a tcp socket. Is that possible? I've done it with:

req_s answer;
...

if( send(sock, (void*)&answer, sizeof(answer),0) < 0 ) {
    printf("send failed!\n");
}

...

recv ( socketDesc, (void*)&answer, sizeof(answer), 0) >= 0)

but if I want to read rout my struct answer I only get some hieroglyphs

or is there even a better way to send my data from client to server and back?

user1550036
  • 211
  • 1
  • 3
  • 9
  • You can send a struct, but since you have `char *` types, your strings won't automatically be sent, but the address of the string, yes. – AntonH Jul 11 '14 at 17:22
  • Big endian vs little endian? – Fiddling Bits Jul 11 '14 at 17:30
  • 3
    Don't use structs as network protocols. Use network protocols as network protocols. Design your protocol, in octets, and write yourself a library to send and receive it. Or use an existing one, such as DML, XDR, ... Using structs introduces at least six dependencies you may not even be aware of, and causes further problems like this one. – user207421 Jul 11 '14 at 21:33

2 Answers2

12

See here: Passing a structure through Sockets in C. However, in your case, you additionally have pointers inside your structure, so you will have to write contents of those pointers to the destination buffer, too.

Community
  • 1
  • 1
5

Sending pointers over a network connection is usually not going to work as the data they point to will not be copied across and even if it were it would probably reside at a different memory address. You need to serialize your structs to send them over a network connection.

Xavier Leclercq
  • 313
  • 2
  • 8