Wednesday, March 11, 2009

The world's smallest usable DNS server

Sometimes, I get requests for MaraDNS to be able to always return a given IP for any query. While MaraDNS is able to do this (with csv2_default_zonefile), it is actually possible to have a much more compact DNS server do the same thing.

I am posting today in this blog a tiny DNS server that does just that. This DNS server always sends the same IP for any and all DNS queries it receives. This IP defaults to "0.0.0.0", but can be changed by supplying a different IP on the command line. I call this program "nanodns", and its source code is as follows:

/*Placed in the public domain by Sam Trenholme*/
#include <arpa/inet.h>
#include <string.h>
#include <stdint.h>
#define Z struct sockaddr
int main(int a,char **b){struct sockaddr_in d;
char q[512];socklen_t f=sizeof(q);uint32_t i=0;
char p[17]="\xc0\x0c\0\x01\0\x01\0\0\0\0\0\x04";
int s;if(a==2){i = inet_addr(b[1]);}i = htonl(i);
p[12]=i>>24;p[13]=(i&0xff0000)>>16;p[14]=(i&65280
)>>8;p[15]=i&255;s=socket(AF_INET,SOCK_DGRAM,0);
memset(&d,0,sizeof(d));d.sin_family = AF_INET;
d.sin_port = htons(53);bind(s,(Z *)&d,sizeof(d));
for(;;){i=recvfrom(s,q,255,0,(Z *)&d,&f);if(i<12
||(q[2]&128)){continue;}q[2]|=128;q[7]++;for(a=0;
a<16;a++) {q[i+a]=p[a];}sendto(s,q,i+16,0,(Z *)&d
,sizeof(Z));}}

To use this program, compile the above source and give it the name "nanodns". To specify the IP you want returned, specify this as the one argument to the program. For example, to always give the IP "192.168.146.132" to any DNS query received by the server, run this program as nanodns 192.168.146.132

This program binds to all addresses the machine running this program has on port 53 (the DNS port); I have a larger (and more readable) version of this program that allows one to change the IP one can bind to which I will put on my webpage and talk about tomorrow.

I will also discuss Deadwood's coding style in future installments of this blog. For example, the above code does not conform to Deadwood's coding style standards (but fits in this blog).