I'm making a program that communicate with certain patient monitor using C sockets. I'm using connection-less sockets (UDP) to communicate with the device. But there is endianness mis-match between my computer and device and so far I was doing this to get parse response from the patient monitor:
recvfrom(int socket, char *buffer, size_t length, int flags, struct sockaddr *address, socklen_t *address_len);
Then I was casting the buffer directly to structure and using the ntohs and ntohl to change the byte ordering, for example:
struct A * a = (struct A *)buffer; Struct A b; b.v1 = ntohs(a->v1); b.v2 = ntohl(a->v2);
After reading few examples over internet, I figured out that this may be wrong approach due to compiler dependent padding. But I'm not sure about it. I need simple way to un-marshall a buffer to a C structure with correct endiannes. The structure that I'm receiving can be of unpredictable length and little complex as well. I need fast and easy approach to do the un-marshalling.
I don't control sender. Sender is in network byte order. My question is only that:- Is is safe to cast a buffer to a structure and then use ntohs and ntohl on this casted structure to make host-byte order replica of this structure? Is it a fastest approach? If not, then what can be the fastest approach?