简体   繁体   中英

Casting char array to struct pointer

I am trying to understand the following casting from this code

char out_packet_buffer[4500] ;  
struct ip6_hdr *iphdr ;

iphdr = (struct ip6_hdr *) &out_packet_buffer[0]; 

Is my understanding correct that the member variables of the struct iphdr are stored in char array out_packet_buffer? Later in the code, out_packet_buffer is never used. Instead, iphdr is memcpyied to an uint8_t memory location (ether_frame). But iphdr is not uint8_t.

I'd appreciate any guidance for me to understand what is happening here.

Thanks

Is my understanding correct that the member variables of the struct iphdr are stored in char array out_packet_buffer?

Kind of. What happens in this casting is that we start "looking" at the memory chunk that starts from &out_packet_buffer[0] (or just out_packet_buffer ) as a struct ip6_hdr instead of a char[] .

Any later usage of iphdr is using the same memory, but splits it into struct ip6_hdr members instead of into char

As @Christian Gibbons said, I also think this violates strict aliasing which is UB

It looks like the code is preparing a packet for transmission over a network. The packet will consist of a header and a payload. The whole packet is, presumably, stored in out_packet_buffer. The ip6_header structure is the first few bytes of this, the data payload follows after. Using a structure for the header makes the code more readable but there'll probably be a "structure order to network order" function just before it's sent to a socket.

In any case, the data packet is just a sequence of bytes, so casting it to any 8-bit type is feasible

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM