1
/* Copyright (c) 2009-2010 Sam Trenholme
5
* Redistribution and use in source and binary forms, with or without
6
* modification, are permitted provided that the following conditions
9
* 1. Redistributions of source code must retain the above copyright
10
* notice, this list of conditions and the following disclaimer.
11
* 2. Redistributions in binary form must reproduce the above copyright
12
* notice, this list of conditions and the following disclaimer in the
13
* documentation and/or other materials provided with the distribution.
15
* This software is provided 'as is' with no guarantees of correctness or
16
* fitness for purpose.
19
#include <sys/socket.h>
20
#include <netinet/in.h>
21
#include <arpa/inet.h>
29
/* We use a special SOCKET type for easier Windows porting */
32
/* Based on command-line arguments, set the IP we will bind to and the
33
IP we send over the pipe */
34
uint32_t get_ip(int argc, char **argv) {
38
/* Set the BIND ip and the IP we give everyone */
39
if(argc < 2 || argc > 3) {
41
"Usage: microdns 10.11.5.11 [{ip of microdns server}]\n"
46
/* Set the IP we give everyone */
47
ip = inet_addr(argv[1]);
50
/* Set the IP we bind to (default is "0", which means "all IPs") */
53
ip = inet_addr(argv[2]);
55
/* Return the IP we bind to */
59
/* Get port: Get a port locally and return the socket the port is on */
60
SOCKET get_port(uint32_t ip, char **argv, struct sockaddr_in *dns_udp) {
65
sock = socket(AF_INET,SOCK_DGRAM,0);
67
perror("socket error");
70
memset(dns_udp,0,sizeof(struct sockaddr_in));
71
dns_udp->sin_family = AF_INET;
72
dns_udp->sin_port = htons(53);
73
dns_udp->sin_addr.s_addr = ip;
74
if(dns_udp->sin_addr.s_addr == INADDR_NONE) {
75
printf("Problem with bind IP %s\n",argv[2]);
78
len_inet = sizeof(struct sockaddr_in);
79
if(bind(sock,(struct sockaddr *)dns_udp,len_inet) == -1) {
84
/* Linux kernel bug */
85
/* fcntl(sock, F_SETFL, O_NONBLOCK); */
90
int main(int argc, char **argv) {
94
socklen_t foo = sizeof(in);
95
struct sockaddr_in dns_udp;
96
uint32_t ip = 0; /* 0.0.0.0; default bind IP */
97
int leni = sizeof(struct sockaddr);
99
ip = get_ip(argc, argv);
100
sock = get_port(ip,argv,&dns_udp);
102
/* Now that we know the IP and are on port 53, process incoming
105
/* Get data from UDP port 53 */
106
len_inet = recvfrom(sock,in,255,0,(struct sockaddr *)&dns_udp,
108
/* Roy Arends check: We only answer questions */
109
if(len_inet < 3 || (in[2] & 0x80) != 0x00) {
113
/* Prepare the reply */
115
/* Make this an answer */
117
/* Send a SERVER FAIL */
118
in[3] &= 0xf0; /* Clear RCODE */
119
in[3] |= 0x02; /* Server fail */
123
sendto(sock,in,len_inet + 16,0, (struct sockaddr *)&dns_udp,