基本的DNS服务器
RubyDNS可以用作一个灵活的DNS服务器,直接处理DNS查询请求或转交给上游DNS服务器。下面是做为基本DNS服务器的例子:
#!/usr/bin/env ruby
require 'rubygems'
require 'rubydns'
$R = Resolv::DNS.new
Name = Resolv::DNS::Name
IN = Resolv::DNS::Resource::IN
RubyDNS::run_server(:listen => [[:udp, "0.0.0.0", 5300]]) do
# For this exact address record, return an IP address
match("dev.mydomain.org", IN::A) do |transaction|
transaction.respond!("10.0.0.80")
end
match("80.0.0.10.in-addr.arpa", IN::PTR) do |transaction|
transaction.respond!(Name.create("dev.mydomain.org."))
end
# Default DNS handler
otherwise do |transaction|
transaction.passthrough!($R)
end
end
如果你运行这段程序,你可以用 dig
命令来查看操作结果:
$ 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: 50
这是服务器在debug模式下的输出:
$ 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>"