title: Converting char* to struct
body: <p>In the code <a href="http://www.binarytides.com/packet-sniffer-code-c-linux/" rel="nofollow noreferrer">here</a>, there is a line:</p>
  
  <pre><code>struct iphdr * iph = (struct iphdr *)buffer;
  </code></pre>
  
  <p>in <code>ProcessPacket</code> function where <code>buffer</code> is of type <code>char*</code>. <code>buffer</code> has been given value by <code>recvfrom</code> in the main function. How is the simple string (<code>buffer</code>) converted to a structure and how is the data safely extracted?</p>
  
  <p><strong>iphdr:</strong></p>
  
  <pre><code>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 &lt;asm/byteorder.h&gt;"
      #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. */
  };
  </code></pre>