Thursday, March 12, 2009

The world's smallest DNS server made smaller

After posting the tiny DNS server yesterday, I realized that this code was somewhat bloated. Going over the code this morning, I have managed to remove some bloat and have made the DNS server 17% smaller, resulting in this compact and efficient DNS server:

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

Note that, if an argument for the IP to give to DNS queries is not given, the program exits with a semi-random exit code instead of giving the IP 0.0.0.0 to all queries (I did it this way to remove some blot from the code), and that there is now a single compile-time warning when compiled with -Wall as a result; if this bothers you, you can place 10 bytes of bloat in the form of return 0; at the end of the program (before the final }).

Note also that this program violates Deadwood coding style standards because, among other reasons, a variable is declared after other actions are performed.

Usage is the same as the more bloated form of this program that I posted yesterday; compile the program and give it the name nanodns and run the program as something like nanodns 192.168.146.134 to give, say, the IP 192.168.146.134 as a reply to any DNS query sent on port 53 of any IP the machine has (and can bind to) when the program is started. Yes, I know, real programmers do not need documentation and can figure all this out just by looking at the above code. I apologize for making concessions for wanna-be programmers (I also have a social life, use Windows, and even have a girlfriend [1]).

OK, OK, tomorrow, I will talk about MicroDNS, which is a large, bloated form of the above program, including such unneeded bloat like comments, indentation, documentation, descriptive variable names, usage information if invoked incorrectly, and other bloat that real programmers do not need. In addition, MicroDNS has some bloat because you can optionally specify which IP the server binds to (if not specified, it binds to all IPs).

- Sam

[1] Took me nearly a year of work to find one; this is why Deadwood 2.1.01 was released in 2009 instead of 2008.