Possible Duplicate:
C - byte array to structure (dns query)
I have these structures:
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;
And I have a DNS query in a byte array buf
from recvfrom
. I am trying to get structure from byte array like this:
TdnsQuery* dnsQuery = (TdnsQuery*)buf;
When I tried to access qtype like this:
printf("%u", dnsQuery->querySection->question.qtype);
I get seg fault 11.
Can someone help me with these structures? What's wrong with them? I tried to add structure:
typedef struct udpPacket {
char header[8];
structr dnsQuery query;
}
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?
Edit: My structures now looks like this:
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;
I added parse function:
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;
}
and tried to parse:
TudpPacket udpPack = (TudpPacket)buf;
parse(udpPack.query.querySection.data, &(udpPack.query.querySection.question.qtype), &(udpPack.query.querySection.question.qclass));
printf("%u\n", udpPack.query.querySection.question.qtype);