RubyDNS: Examples
Example 1: Creating a DNS server
RubyDNS is primarily for manipulating DNS requests. Here is an example of a very basic server:
#!/usr/bin/env ruby
require 'rubygems'
require 'rubydns'
$R = Resolv::DNS.new
Name = Resolv::DNS::Name
RubyDNS::run_server(:listen => [[:udp, "0.0.0.0", 5300]]) do
# For this exact address record, return an IP address
match("dev.mydomain.org", :A) do |transaction|
transaction.respond!("10.0.0.80")
end
match("80.0.0.10.in-addr.arpa", :PTR) do |transaction|
transaction.respond!(Name.create("dev.mydomain.org."))
end
# Default DNS handler
otherwise do |transaction|
transaction.passthrough!($R)
end
end
If you run this program, you can use dig to see the result of the manipulation:
$ dig @localhost -p 5300 dev.mydomain.org ; <<>> DiG 9.6.0-APPLE-P2 <<>> @localhost -p 5300 dev.mydomain.org ; (3 servers found) ;; global options: +cmd ;; Got answer: ;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 37994 ;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 0 ;; WARNING: recursion requested but not available ;; QUESTION SECTION: ;dev.mydomain.org. IN A ;; ANSWER SECTION: dev.mydomain.org. 16000 IN A 10.0.0.80 ;; Query time: 5 msec ;; SERVER: 127.0.0.1#5300(127.0.0.1) ;; WHEN: Thu Nov 5 22:28:08 2009 ;; MSG SIZE rcvd: 50Here is the output from the server running in debug mode:
$ ruby example-dns.rb I, [2009-11-05T22:27:53.887513 #1958] INFO -- : Starting server... D, [2009-11-05T22:28:08.777992 #1958] DEBUG -- : Receiving incoming query... D, [2009-11-05T22:28:08.778858 #1958] DEBUG -- : Searching for dev.mydomain.org A D, [2009-11-05T22:28:08.779126 #1958] DEBUG -- : Checking rule ["dev.mydomain.org", "A"]... D, [2009-11-05T22:28:08.779225 #1958] DEBUG -- : Resource type A matched D, [2009-11-05T22:28:08.779449 #1958] DEBUG -- : Query dev.mydomain.org matched dev.mydomain.org D, [2009-11-05T22:28:08.779912 #1958] DEBUG -- : Rule returned successfully D, [2009-11-05T22:28:08.780202 #1958] DEBUG -- : Sending result to ["AF_INET", 62305, "localhost", "127.0.0.1"]: D, [2009-11-05T22:28:08.780358 #1958] DEBUG -- : "<snip>"