title: C - dns query to structure
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/13438969/c-byte-array-to-structure-dns-query">C - byte array to structure (dns query)</a>  </p>
  </blockquote>
  
  
  
  <p>I have these structures:</p>
  
  <pre><code>typedef struct dnsQuery {
    char header[12];
    struct dnsQuerySection *querySection;
  } TdnsQuery;
  
  typedef struct dnsQuerySection {
    unsigned char *name;
    struct dnsQueryQuestion *question;
  } TdnsQuerySection;
  
  typedef struct dnsQueryQuestion {
    unsigned short qtype;
    unsigned short qclass;
  } TdnsQueryQuestion;
  </code></pre>
  
  <p>And I have a DNS query in a byte array <code>buf</code> from <code>recvfrom</code>. I am trying to get structure from byte array like this:</p>
  
  <pre><code>TdnsQuery* dnsQuery = (TdnsQuery*)buf;
  </code></pre>
  
  <p>When I tried to access qtype like this:</p>
  
  <pre><code>printf("%u", dnsQuery-&gt;querySection-&gt;question.qtype);
  </code></pre>
  
  <p>I get seg fault 11. </p>
  
  <p>Can someone help me with these structures? What's wrong with them? I tried to add structure:</p>
  
  <pre><code>typedef struct udpPacket {
    char header[8];
    structr dnsQuery query;
  }
  </code></pre>
  
  <p>And mapped this structure from byte array but it didn't help. Can someone help me with these structures? How they should look like for DNS query with UDP protocol?</p>
  
  <p><strong>Edit:</strong> My structures now looks like this:</p>
  
  <pre><code> typedef struct {
        unsigned short qtype;
        unsigned short qclass;
   } dnsQueryQuestion;
  
   typedef struct {
  
        dnsQueryQuestion *question;
        unsigned char *data[0];
   } dnsQuerySection;
  
   typedef struct {
        char header[12];
        dnsQuerySection querySection[0];
   } dnsQuery;
  
   typedef struct udpPacket {
        char header[8];
        dnsQuery query[0];
   } TudpPacket;
  </code></pre>
  
  <p>I added parse function:</p>
  
  <pre><code>void parse(unsigned char *data, unsigned short *qtype, unsigned short *qclass) {
      int i = 0;
      while (data[i]) {
          int len = data[i];
          i += len + 1;
      }
      *qtype = (unsigned short) data[i+1];
      *qclass = (unsigned short) data[i+3];
      return;
  } 
  </code></pre>
  
  <p>and tried to parse:</p>
  
  <pre><code>TudpPacket udpPack = (TudpPacket)buf;
  parse(udpPack.query.querySection.data, &amp;(udpPack.query.querySection.question.qtype), &amp;(udpPack.query.querySection.question.qclass));
  printf("%u\n", udpPack.query.querySection.question.qtype);
  </code></pre>