Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DNS client in C

I am currently working on a school project which asks me to implement a DNS client, without using any library functions.

I have got to the point where i send a DNS request and Receive the Reply. I'm getting stuck at the parsing of the reply. I receive the reply in a char* array and i want to convert it into some meaningful structure, from which i can parse the answer. I went through the RFC and i read about the packet structure, but implementing it in C is giving me problems.

Can anyone give me any examples, in C, or maybe in any other language that explains how this is done. Or any reference to a book is also fine.

Additional Details:

So, the following are the structures that i'm using.

struct result{
  int type;
  struct res_ip_cname ip_cname;
  struct res_error error;
  struct res_mx_ns mx_ns;
};

struct res_ip_cname{
  char* lst;
  int sec;
  char* auth_flag;
};

struct res_error{
  char * info;
};

struct res_mx_ns{
  char * name;
  unsigned short pref;
  int sec;
  char* auth_flag;
};

I have a char* buffer[], where im storing the response the i receive from the server. And, i need to extract information from this buffer and populate the structure result.

Thanks, Chander

like image 380
Chander Shivdasani Avatar asked Mar 05 '26 08:03

Chander Shivdasani


1 Answers

Your structures don't look like anything I recognise from the RFCs (yes, I've written lots of DNS packet decoding software).

Look at RFC 1035 in particular - most of the structures you need can be mapped directly from the field layouts show therein.

For example, you need a header (see s4.1.1):

struct dns_header {
     uint16_t     query_id;
     uint16_t     flags;
     uint16_t     qdcount;
     uint16_t     ancount;
     uint16_t     nscount;
     uint16_t     arcount;
};

Don't forget to use ntohs() to convert the wire format of these fields into your machine's native byte order. The network order is big-endian, and most machines these days are little-endian.

You'll need a "question" structure (see s4.1.2), and a generic "resource record" structure too (see s4.1.3).

Note however that the wire format of both of these starts with a variable length "label", which can also include compression pointers (see s4.1.4). This means that you can't in these cases trivially map the whole wire block onto a C structure.

Hope this helps...

like image 96
Alnitak Avatar answered Mar 08 '26 21:03

Alnitak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!