I'm a little confused regarding data alignment. On x86, we typically take alignment for granted. However, I'm programming on a system that is very strict and will error out if I try to access unaligned data.
Heres my problem:
First, I'm going to show you some structs I have:
struct sniff_ethernet {
u_char ether_dhost[6]; /* Destination host address */
u_char ether_shost[6]; /* Source host address */
u_short ether_type; /* IP? ARP? RARP? etc */
};
struct sniff_ip {
u_char ip_vhl; /* version << 4 | header length >> 2 */
u_char ip_tos; /* type of service */
u_short ip_len; /* total length */
u_short ip_id; /* identification */
u_short ip_off; /* fragment offset field */
u_char ip_ttl; /* time to live */
u_char ip_p; /* protocol */
u_short ip_sum; /* checksum */
struct in_addr ip_src,ip_dst; /* source and dest address */
};
I'm dealing with pcap. Pcap will return a pointer to a data packet to me:
u_char *packet;
Lets pretend the packet is a couple hundred bytes. What I typically do is cast that packet to several struct pointers, so I can access the data directly.
struct sniff_ethernet *seth = (struct sniff_ethernet *) packet;
struct sniff_ip *sip = (struct sniff_ip *) (packet + 14); // 14 is the size of an ethernet header
Ok. So everything looks great right? On x86, everything appears to work right. On any other archetecture that has strict alignment, I have issues when accessing some values and it will typically result in a sigbus. For example:
sip->ip_len = 0x32AA;
or
u_short val = sip->ip_len;
results in an error. I'm guessing its because it's misaligned in memory from the cast. Whats typically the best way to handle this when doing these kind of casts?