Converting char* to struct

Deepesh Choudhary

In the code here, there is a line:

struct iphdr * iph = (struct iphdr *)buffer;

in ProcessPacket function where buffer is of type char*. buffer has been given value by recvfrom in the main function. How is the simple string (buffer) converted to a structure and how is the data safely extracted?

iphdr:

struct iphdr {
    #if defined(__LITTLE_ENDIAN_BITFIELD)
        __u8    ihl:4,
                version:4;
    #elif defined (__BIG_ENDIAN_BITFIELD)
        __u8    version:4,
                ihl:4;
    #else
        #error  "Please fix <asm/byteorder.h>"
    #endif
         __u8   tos;
         __u16  tot_len;
         __u16  id;
         __u16  frag_off;
         __u8   ttl;
         __u8   protocol;
         __u16  check;
         __u32  saddr;
         __u32  daddr;
         /*The options start here. */
};
babon

The first thing to understand is that the bits on memory stay exactly the same irrespective of the cast (struct iphdr *). Just that you are now saying that buffer is now to be treated as a pointer to struct iphdr instead of what it was before. You are just telling the compiler to look at the bits with a different pair of glasses and hence interpret accordingly. The compiler suddenly sees that buffer has become a struct iphdr *. And says "OK" that's all. What's important is you know exactly what buffer is and cast it to the proper type.

If you wanted, you could have type-casted buffer to int * (or any other pointer type) and the compiler would have said nothing. Although you would have problems later on.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related