write(fd,&a, sizeof(a)); incorrect at least not portable, as the C compiler can inject padding between elements to ensure proper alignment. sizeof(typedef struct a) doesn't even make sense.
How you should send data depends on the characteristics of your protocol. In particular, protocols define a variety of ways to send strings. As a rule, it is most safe to send struct elements individually; either a few calls to write, or writev(2) . For example, to send
struct { uint32_t a; uint16_t b; } foo;
over a network where foo.a and foo.b already have the correct endianness, you would do something like:
struct iovec v[2]; v[0].iov_base = &foo.a; v[0].iov_len = sizeof(uint32_t); v[1].iov_base = &foo.b; v[1].iov_len = sizeof(uint16_t); writev(fp, v, 2);
source share