DNS Query Code in C with linux sockets

来源:互联网 发布:美剧黑中国 知乎 编辑:程序博客网 时间:2024/06/03 13:40

The Linux version has some changes. On Linux the dns server ips are stored in a file called /etc/resolv.conf.
So the get_dns_servers function will open this file and pickup the dns server ip addresses.

A typical /etc/resolv.conf file can look like this :

# Generated by NetworkManagernameserver 208.67.222.222nameserver 208.67.220.220

So the lines starting with nameserver can be picked up and broken into parts using strtok.

Rest of the code is very much similar to the winsock version. A udp socket is used to send a UDP packet and the response is analysed.

Code :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//DNS Query Program on Linux
//Author : Silver Moon (m00n.silv3r@gmail.com)
//Dated : 29/4/2009
 
//Header Files
#include<stdio.h> //printf
#include<string.h>    //strlen
#include<stdlib.h>    //malloc
#include<sys/socket.h>    //you know what this is for
#include<arpa/inet.h> //inet_addr , inet_ntoa , ntohs etc
#include<netinet/in.h>
#include<unistd.h>    //getpid
 
//List of DNS Servers registered on the system
chardns_servers[10][100];
intdns_server_count = 0;
//Types of DNS resource records :)
 
#define T_A 1 //Ipv4 address
#define T_NS 2 //Nameserver
#define T_CNAME 5 // canonical name
#define T_SOA 6 /* start of authority zone */
#define T_PTR 12 /* domain name pointer */
#define T_MX 15 //Mail server
 
//Function Prototypes
voidngethostbyname (unsigned char* , int);
voidChangetoDnsNameFormat (unsigned char*,unsignedchar*);
unsignedchar* ReadName (unsigned char*,unsignedchar*,int*);
voidget_dns_servers();
 
//DNS header structure
structDNS_HEADER
{
    unsignedshortid; // identification number
 
    unsignedcharrd :1; // recursion desired
    unsignedchartc :1; // truncated message
    unsignedcharaa :1; // authoritive answer
    unsignedcharopcode :4; // purpose of message
    unsignedcharqr :1; // query/response flag
 
    unsignedcharrcode :4; // response code
    unsignedcharcd :1; // checking disabled
    unsignedcharad :1; // authenticated data
    unsignedcharz :1; // its z! reserved
    unsignedcharra :1; // recursion available
 
    unsignedshortq_count; // number of question entries
    unsignedshortans_count; // number of answer entries
    unsignedshortauth_count; // number of authority entries
    unsignedshortadd_count; // number of resource entries
};
 
//Constant sized fields of query structure
structQUESTION
{
    unsignedshortqtype;
    unsignedshortqclass;
};
 
//Constant sized fields of the resource record structure
#pragma pack(push, 1)
structR_DATA
{
    unsignedshorttype;
    unsignedshort_class;
    unsignedintttl;
    unsignedshortdata_len;
};
#pragma pack(pop)
 
//Pointers to resource record contents
structRES_RECORD
{
    unsignedchar*name;
    structR_DATA *resource;
    unsignedchar*rdata;
};
 
//Structure of a Query
typedefstruct
{
    unsignedchar*name;
    structQUESTION *ques;
} QUERY;
 
intmain( intargc , char*argv[])
{
    unsignedcharhostname[100];
 
    //Get the DNS servers from the resolv.conf file
    get_dns_servers();
     
    //Get the hostname from the terminal
    printf("Enter Hostname to Lookup : ");
    scanf("%s", hostname);
     
    //Now get the ip of this hostname , A record
    ngethostbyname(hostname , T_A);
 
    return0;
}
 
/*
 * Perform a DNS query by sending a packet
 * */
voidngethostbyname(unsigned char*host , intquery_type)
{
    unsignedcharbuf[65536],*qname,*reader;
    inti , j , stop , s;
 
    structsockaddr_in a;
 
    structRES_RECORD answers[20],auth[20],addit[20]; //the replies from the DNS server
    structsockaddr_in dest;
 
    structDNS_HEADER *dns = NULL;
    structQUESTION *qinfo = NULL;
 
    printf("Resolving %s" , host);
 
    s = socket(AF_INET , SOCK_DGRAM , IPPROTO_UDP); //UDP packet for DNS queries
 
    dest.sin_family = AF_INET;
    dest.sin_port = htons(53);
    dest.sin_addr.s_addr = inet_addr(dns_servers[0]); //dns servers
 
    //Set the DNS structure to standard queries
    dns = (structDNS_HEADER *)&buf;
 
    dns->id = (unsigned short) htons(getpid());
    dns->qr = 0; //This is a query
    dns->opcode = 0; //This is a standard query
    dns->aa = 0; //Not Authoritative
    dns->tc = 0; //This message is not truncated
    dns->rd = 1; //Recursion Desired
    dns->ra = 0; //Recursion not available! hey we dont have it (lol)
    dns->z = 0;
    dns->ad = 0;
    dns->cd = 0;
    dns->rcode = 0;
    dns->q_count = htons(1); //we have only 1 question
    dns->ans_count = 0;
    dns->auth_count = 0;
    dns->add_count = 0;
 
    //point to the query portion
    qname =(unsigned char*)&buf[sizeof(structDNS_HEADER)];
 
    ChangetoDnsNameFormat(qname , host);
    qinfo =(structQUESTION*)&buf[sizeof(structDNS_HEADER) + (strlen((constchar*)qname) + 1)]; //fill it
 
    qinfo->qtype = htons( query_type ); //type of the query , A , MX , CNAME , NS etc
    qinfo->qclass = htons(1); //its internet (lol)
 
    printf("\nSending Packet...");
    if( sendto(s,(char*)buf,sizeof(structDNS_HEADER) + (strlen((constchar*)qname)+1) + sizeof(structQUESTION),0,(structsockaddr*)&dest,sizeof(dest)) < 0)
    {
        perror("sendto failed");
    }
    printf("Done");
     
    //Receive the answer
    i = sizeofdest;
    printf("\nReceiving answer...");
    if(recvfrom (s,(char*)buf , 65536 , 0 , (structsockaddr*)&dest , (socklen_t*)&i ) < 0)
    {
        perror("recvfrom failed");
    }
    printf("Done");
 
    dns = (structDNS_HEADER*) buf;
 
    //move ahead of the dns header and the query field
    reader = &buf[sizeof(structDNS_HEADER) + (strlen((constchar*)qname)+1) + sizeof(structQUESTION)];
 
    printf("\nThe response contains : ");
    printf("\n %d Questions.",ntohs(dns->q_count));
    printf("\n %d Answers.",ntohs(dns->ans_count));
    printf("\n %d Authoritative Servers.",ntohs(dns->auth_count));
    printf("\n %d Additional records.\n\n",ntohs(dns->add_count));
 
    //Start reading answers
    stop=0;
 
    for(i=0;i<ntohs(dns->ans_count);i++)
    {
        answers[i].name=ReadName(reader,buf,&stop);
        reader = reader + stop;
 
        answers[i].resource = (structR_DATA*)(reader);
        reader = reader + sizeof(structR_DATA);
 
        if(ntohs(answers[i].resource->type) == 1) //if its an ipv4 address
        {
            answers[i].rdata = (unsigned char*)malloc(ntohs(answers[i].resource->data_len));
 
            for(j=0 ; j<ntohs(answers[i].resource->data_len) ; j++)
            {
                answers[i].rdata[j]=reader[j];
            }
 
            answers[i].rdata[ntohs(answers[i].resource->data_len)] = '\0';
 
            reader = reader + ntohs(answers[i].resource->data_len);
        }
        else
        {
            answers[i].rdata = ReadName(reader,buf,&stop);
            reader = reader + stop;
        }
    }
 
    //read authorities
    for(i=0;i<ntohs(dns->auth_count);i++)
    {
        auth[i].name=ReadName(reader,buf,&stop);
        reader+=stop;
 
        auth[i].resource=(structR_DATA*)(reader);
        reader+=sizeof(structR_DATA);
 
        auth[i].rdata=ReadName(reader,buf,&stop);
        reader+=stop;
    }
 
    //read additional
    for(i=0;i<ntohs(dns->add_count);i++)
    {
        addit[i].name=ReadName(reader,buf,&stop);
        reader+=stop;
 
        addit[i].resource=(structR_DATA*)(reader);
        reader+=sizeof(structR_DATA);
 
        if(ntohs(addit[i].resource->type)==1)
        {
            addit[i].rdata = (unsigned char*)malloc(ntohs(addit[i].resource->data_len));
            for(j=0;j<ntohs(addit[i].resource->data_len);j++)
            addit[i].rdata[j]=reader[j];
 
            addit[i].rdata[ntohs(addit[i].resource->data_len)]='\0';
            reader+=ntohs(addit[i].resource->data_len);
        }
        else
        {
            addit[i].rdata=ReadName(reader,buf,&stop);
            reader+=stop;
        }
    }
 
    //print answers
    printf("\nAnswer Records : %d \n" , ntohs(dns->ans_count) );
    for(i=0 ; i < ntohs(dns->ans_count) ; i++)
    {
        printf("Name : %s ",answers[i].name);
 
        if( ntohs(answers[i].resource->type) == T_A) //IPv4 address
        {
            long*p;
            p=(long*)answers[i].rdata;
            a.sin_addr.s_addr=(*p);//working without ntohl
            printf("has IPv4 address : %s",inet_ntoa(a.sin_addr));
        }
         
        if(ntohs(answers[i].resource->type)==5)
        {
            //Canonical name for an alias
            printf("has alias name : %s",answers[i].rdata);
        }
 
        printf("\n");
    }
 
    //print authorities
    printf("\nAuthoritive Records : %d \n" , ntohs(dns->auth_count) );
    for( i=0 ; i < ntohs(dns->auth_count) ; i++)
    {
         
        printf("Name : %s ",auth[i].name);
        if(ntohs(auth[i].resource->type)==2)
        {
            printf("has nameserver : %s",auth[i].rdata);
        }
        printf("\n");
    }
 
    //print additional resource records
    printf("\nAdditional Records : %d \n" , ntohs(dns->add_count) );
    for(i=0; i < ntohs(dns->add_count) ; i++)
    {
        printf("Name : %s ",addit[i].name);
        if(ntohs(addit[i].resource->type)==1)
        {
            long*p;
            p=(long*)addit[i].rdata;
            a.sin_addr.s_addr=(*p);
            printf("has IPv4 address : %s",inet_ntoa(a.sin_addr));
        }
        printf("\n");
    }
    return;
}
 
/*
 *
 * */
u_char* ReadName(unsigned char* reader,unsigned char* buffer,int* count)
{
    unsignedchar*name;
    unsignedintp=0,jumped=0,offset;
    inti , j;
 
    *count = 1;
    name = (unsigned char*)malloc(256);
 
    name[0]='\0';
 
    //read the names in 3www6google3com format
    while(*reader!=0)
    {
        if(*reader>=192)
        {
            offset = (*reader)*256 + *(reader+1) - 49152; //49152 = 11000000 00000000 ;)
            reader = buffer + offset - 1;
            jumped = 1; //we have jumped to another location so counting wont go up!
        }
        else
        {
            name[p++]=*reader;
        }
 
        reader = reader+1;
 
        if(jumped==0)
        {
            *count = *count + 1; //if we havent jumped to another location then we can count up
        }
    }
 
    name[p]='\0';//string complete
    if(jumped==1)
    {
        *count = *count + 1; //number of steps we actually moved forward in the packet
    }
 
    //now convert 3www6google3com0 to www.google.com
    for(i=0;i<(int)strlen((constchar*)name);i++)
    {
        p=name[i];
        for(j=0;j<(int)p;j++)
        {
            name[i]=name[i+1];
            i=i+1;
        }
        name[i]='.';
    }
    name[i-1]='\0';//remove the last dot
    returnname;
}
 
/*
 * Get the DNS servers from /etc/resolv.conf file on Linux
 * */
voidget_dns_servers()
{
    FILE*fp;
    charline[200] , *p;
    if((fp = fopen("/etc/resolv.conf", "r")) == NULL)
    {
        printf("Failed opening /etc/resolv.conf file \n");
    }
     
    while(fgets(line , 200 , fp))
    {
        if(line[0] == '#')
        {
            continue;
        }
        if(strncmp(line , "nameserver", 10) == 0)
        {
            p = strtok(line , " ");
            p = strtok(NULL , " ");
             
            //p now is the dns ip :)
            //????
        }
    }
     
    strcpy(dns_servers[0] , "208.67.222.222");
    strcpy(dns_servers[1] , "208.67.220.220");
}
 
/*
 * This will convert www.google.com to 3www6google3com
 * got it :)
 * */
voidChangetoDnsNameFormat(unsigned char* dns,unsigned char* host)
{
    intlock = 0 , i;
    strcat((char*)host,".");
     
    for(i = 0 ; i < strlen((char*)host) ; i++)
    {
        if(host[i]=='.')
        {
            *dns++ = i-lock;
            for(;lock<i;lock++)
            {
                *dns++=host[lock];
            }
            lock++;//or lock=i+1;
        }
    }
    *dns++='\0';
}

Compile

$ gcc dns.c

Output

$ ./a.out Enter Hostname to Lookup : www.google.comResolving www.google.comSending Packet...DoneReceiving answer...DoneThe response contains :  1 Questions. 6 Answers. 4 Authoritative Servers. 4 Additional records.Answer Records : 6 Name : www.google.com has alias name : www.l.google.comName : www.l.google.com has IPv4 address : 74.125.235.16Name : www.l.google.com has IPv4 address : 74.125.235.17Name : www.l.google.com has IPv4 address : 74.125.235.18Name : www.l.google.com has IPv4 address : 74.125.235.19Name : www.l.google.com has IPv4 address : 74.125.235.20Authoritive Records : 4 Name : google.com has nameserver : ns2.google.comName : google.com has nameserver : ns1.google.comName : google.com has nameserver : ns3.google.comName : google.com has nameserver : ns4.google.comAdditional Records : 4 Name : ns1.google.com has IPv4 address : 216.239.32.10Name : ns2.google.com has IPv4 address : 216.239.34.10Name : ns3.google.com has IPv4 address : 216.239.36.10Name : ns4.google.com has IPv4 address : 216.239.38.10

The same code can be used to fetch different kinds of dns records like Nameserver , MX , CNAME , SOA etc.


原创粉丝点击