### Start Ruby interactive shell (irb) Source: https://github.com/alexdalitz/dnsruby/wiki/Home Run the examples in Ruby's interactive shell. ```shell $ irb ``` -------------------------------- ### Install dnsruby gem Source: https://github.com/alexdalitz/dnsruby/wiki/Home Install the dnsruby gem from the command line before running the examples. ```shell $ gem install dnsruby ``` -------------------------------- ### Load system default resolvers Source: https://github.com/alexdalitz/dnsruby/wiki/Home Create a Resolver instance that uses the system's default resolvers. ```ruby res = Resolver.new ``` -------------------------------- ### Require and include Dnsruby Source: https://github.com/alexdalitz/dnsruby/wiki/Home Load the dnsruby library and include its namespace for the examples. ```ruby require 'rubygems' require 'dnsruby' include Dnsruby ``` -------------------------------- ### Create resolver with defined nameservers Source: https://github.com/alexdalitz/dnsruby/wiki/Home Create a Resolver using explicit nameservers (ns1.nic.uk and ns2.nic.uk) instead of the system defaults. ```ruby res = Resolver.new({:nameserver => ["ns1.nic.uk", "ns2.nic.uk"]}) ``` -------------------------------- ### Query A and MX records with default resolvers Source: https://github.com/alexdalitz/dnsruby/wiki/Home Use the resolver to query example.com for A (default) and MX records. The A query prints the answer; the MX query is sent but its output is not shown. ```ruby ret = res.query("example.com") # Defaults to A record print ret.answer # prints: example.com. 172789 IN A 208.77.188.166=> nil res.query("example.com", "MX") # Query the MX record ``` -------------------------------- ### Configure resolver and TSIG key for dynamic update Source: https://github.com/alexdalitz/dnsruby/wiki/Home Set up a Resolver for the validation server with DNSSEC disabled and create a TSIG key for signing. ```ruby res = Dnsruby::Resolver.new("ns0.validation-test-servers.nominet.org.uk") res.dnssec = false tsig = Dnsruby::RR.create({ :name => "rubytsig", :type => "TSIG", :key => "8n6gugn4aJ7MazyNlMccGKH1WxD2B3UvN/O/RA6iBupO2/03u9CTa3Ewz3gBWTSBCH3crY4Kk+tigNdeJBAvrw==", }) ``` -------------------------------- ### Prepare asynchronous query with Queue and Message Source: https://github.com/alexdalitz/dnsruby/wiki/Home Set up an asynchronous query: create a Queue, construct a Message for co.uk NS with RD bit set to false, and send it via send_async with a timeout of 1. ```ruby queue = Queue.new m = Message.new("co.uk", Types.NS) m.header.rd = false message_id = res.send_async(m, queue, 1) ``` -------------------------------- ### Full usage example Source: https://github.com/alexdalitz/dnsruby Complete example covering synchronous, non-raising, and asynchronous queries. Note the deprecated status and lack of retries. ```ruby require 'dnsruby' sr = Dnsruby::SingleResolver.new({:server => "8.8.8.8", :port => 53}) sr.packet_timeout = 2 # per-packet and total query timeout # Synchronous query (raises on error) begin response = sr.query("example.com", Dnsruby::Types.A) puts response.answerfrom rescue Dnsruby::ResolvError => e puts "Query failed: #{e}" end # Non-raising variants return [response, error] response, error = sr.query!("example.com") response, error = sr.send_message!(Dnsruby::Message.new("example.com")) # Asynchronous query q = Queue.new sr.send_async(Dnsruby::Message.new("example.com"), q, 42) _id, reply, err = q.pop ``` -------------------------------- ### Resolver constructor examples Source: https://github.com/alexdalitz/dnsruby Three ways to instantiate a resolver: with system defaults, with a hash of nameservers, or with a single nameserver string. The hash example uses a.iana-servers.net and b.iana-servers.net. ```ruby res = Dnsruby::Resolver.new # system defaults res = Dnsruby::Resolver.new({:nameserver => ["a.iana-servers.net", "b.iana-servers.net"]}) res = Dnsruby::Resolver.new("8.8.8.8") ``` -------------------------------- ### Apply TSIG signature and send update Source: https://github.com/alexdalitz/dnsruby/wiki/Home Apply the TSIG signature to the update, send it, and print whether the response was verified. ```ruby tsig.apply(update) response = res.send_message(update) print "TSIG response was verified? : #{response.verified?}\n" ``` -------------------------------- ### Usage example Source: https://github.com/alexdalitz/dnsruby Example showing how to create and inspect an A record using RR.create. ```APIDOC ## Usage example ### Description Example showing how to create and inspect an A record using RR.create. ### Request Example ```ruby rr = Dnsruby::RR.create("example.com. 86000 IN A 93.184.216.34") puts rr.type.string # "A" puts rr.address # 93.184.216.34 (IPv4) puts rr.ttl # 86000 puts rr.to_s # "example.com.\t86000\tIN\tA\t93.184.216.34" ``` ``` -------------------------------- ### Dnsruby::DNS constructor usage example Source: https://github.com/alexdalitz/dnsruby Example of creating a `Dnsruby::DNS` instance with a configuration Hash specifying a nameserver, search domain, and ndots value. ```ruby dns = Dnsruby::DNS.new({:nameserver => ["210.251.121.21"], :search => ["ruby-lang.org"], :ndots => 1}) ``` -------------------------------- ### Accessing header flags example Source: https://github.com/alexdalitz/dnsruby Shows how to set header flags on a DNS message and output the opcode string. ```ruby res = Dnsruby::Resolver.new msg = Dnsruby::Message.new("example.com") msg.header.rd = 1 # set recursion desired msg.header.qr = false puts msg.header.opcode.string # "Query" ``` -------------------------------- ### Dnsruby::DNS getresources usage example Source: https://github.com/alexdalitz/dnsruby Example of using `getresources` to fetch MX records for "ruby-lang.org" and print each exchange and preference. ```ruby dns = Dnsruby::DNS.new mx = dns.getresources("ruby-lang.org", 'MX') mx.each { |r| puts "#{r.exchange} #{r.preference}" } ``` -------------------------------- ### Configure resolver to sign all packets with TSIG Source: https://github.com/alexdalitz/dnsruby/wiki/Home Set the resolver's tsig attribute to the TSIG key so all packets are signed. ```ruby res.tsig = tsig.name, tsig.key ``` -------------------------------- ### Hosts usage example Source: https://github.com/alexdalitz/dnsruby Creates a Hosts resolver and prints the first address for 'localhost'. ```ruby h = Dnsruby::Hosts.new puts h.getaddress("localhost") ``` -------------------------------- ### Create dynamic update packet with Update Source: https://github.com/alexdalitz/dnsruby/wiki/Home Create a Dnsruby::Update for the zone and add an 'absent' prerequisite for a TXT record. ```ruby update = Dnsruby::Update.new("validation-test-servers.nominet.org.uk") # ... add stuff to the update update.absent("notthere.update.validation-test-servers.nominet.org.uk", 'TXT') ``` -------------------------------- ### Recursive query from root with Recursor Source: https://github.com/alexdalitz/dnsruby/wiki/Home Use Recursor to query recursively from the root. A static cache is built up, reducing packets sent per client query over time. ```ruby rec = Recursor.new ret = rec.query("uk-dnssec.nic.uk", "NS") ``` -------------------------------- ### Display default resolver server addresses Source: https://github.com/alexdalitz/dnsruby/wiki/Home Iterate over the resolver's single resolvers and print each server address. The output shows the server addresses (e.g., 192.168.1.1). ```ruby res.single_resolvers.each {|s| print "Server address : #{s.server}\n"} # Outputs: # Server address : 192.168.1.1 # Server address : 192.168.2.2 ``` -------------------------------- ### send_async usage example Source: https://github.com/alexdalitz/dnsruby Shows how to use send_async: create a Resolver and Queue, send a Message for NS records with query ID 1, then pop the result tuple [id, reply, error] and print the response or error. ```ruby res = Dnsruby::Resolver.new q = Queue.new res.send_async(Dnsruby::Message.new('example.com', Dnsruby::Types.NS), q, 1) # do other work... id, reply, error = q.pop if error puts "Error : #{error}" else puts "Got response from : #{reply.answerfrom}, #{reply.answerip}" end ``` -------------------------------- ### RRSet usage example - query and iterate A records Source: https://github.com/alexdalitz/dnsruby Shows how to query a domain, get A RRSets from the answer section, and print each RRSet. Uses Dnsruby::Resolver and Dnsruby::Types.A. ```ruby res = Dnsruby::Resolver.new ret = res.query("example.com") a_rrsets = ret.answer.rrsets(Dnsruby::Types.A) a_rrsets.each { |rrset| puts rrset.to_s } ``` -------------------------------- ### Complete update workflow example Source: https://github.com/alexdalitz/dnsruby Shows a full dynamic update: create an Update for example.com, add a prerequisite that the A RRset for foo.example.com does not exist, add two A records, send via Resolver, and handle success or failure. The reply's verified? method indicates DNSSEC validation status. ```ruby require 'dnsruby' update = Dnsruby::Update.new('example.com') update.absent('foo.example.com.', 'A') # prerequisite update.add('foo.example.com.', 'A', 86400, '192.168.1.2') update.add('foo.example.com.', 'A', 86400, '172.16.3.4') res = Dnsruby::Resolver.new({:nameserver => 'primary-master.example.com'}) begin reply = res.send_message(update) puts "Update succeeded, verified? #{reply.verified?}" rescue Dnsruby::ResolvError => e puts "Update failed: #{e}" end ``` -------------------------------- ### Usage example with trust anchor and DLV key Source: https://github.com/alexdalitz/dnsruby Shows adding a trust anchor, querying with a resolver, and loading the ISC DLV key. ```ruby require 'dnsruby' Dnsruby::Dnssec.add_trust_anchor(Dnsruby::RR.create({ :name => "uk-dnssec.nic.uk.", :type => Dnsruby::Types.DNSKEY, :flags => 257, :protocol => 3, :algorithm => 5, :key => "AQPJO6LjrCHhzSF9..." })) res = Dnsruby::Resolver.new("dnssec.nominet.org.uk") r = res.query("aaa.bigzone.uk-dnssec.nic.uk", Dnsruby::Types.DNSKEY) puts r.security_level # SECURE # Load the ISC DLV key dlv_key = Dnsruby::RR.create("dlv.isc.org. IN DNSKEY 257 3 5 BEAAAAPHMu/5...") Dnsruby::Dnssec.add_dlv_key(dlv_key) ``` -------------------------------- ### Usage examples: enumerate types and parse A record Source: https://github.com/alexdalitz/dnsruby Shows how to enumerate all implemented RR types and parse an A record. The A record example prints type string, address, TTL, and zone-file representation. ```ruby # Enumerate all implemented types Dnsruby::RR.implemented_rrs # => ["A", "AAAA", "AFSDB", ...] # Parse and inspect an A record rr = Dnsruby::RR.create("example.com. 86000 IN A 93.184.216.34") puts rr.type.string # "A" puts rr.address # 93.184.216.34 (IPv4) puts rr.ttl # 86000 puts rr.to_s # "example.com.\t86000\tIN\tA\t93.184.216.34" ``` -------------------------------- ### Pop asynchronous query result from queue Source: https://github.com/alexdalitz/dnsruby/wiki/Home Block on Queue#pop to retrieve the [id, reply, error] tuple. id should match the message_id from send_async; reply holds the best response; error should be nil in this example. ```ruby id, reply, error = queue.pop # id == message_id ``` -------------------------------- ### query_raw usage example Source: https://github.com/alexdalitz/dnsruby Shows two ways to call query_raw: with default :return strategy and with :raise strategy. ```ruby response, error = res.query_raw(Dnsruby::Message.new('example.com')) response = res.query_raw(Dnsruby::Message.new('example.com'), :raise) ``` -------------------------------- ### query usage examples Source: https://github.com/alexdalitz/dnsruby Examples of querying with default A/IN, explicit MX type, and an IPv4 address that triggers a PTR query. The response is a Dnsruby::Message. ```ruby res = Dnsruby::Resolver.new response = res.query('example.com') # A/IN response = res.query('example.com', Dnsruby::Types.MX) response = res.query('208.77.188.166') # IPv4 → PTR query ``` -------------------------------- ### query! usage example Source: https://github.com/alexdalitz/dnsruby Shows how to call query! and handle the returned error. The method returns [response, error] instead of raising. ```ruby response, error = res.query!("example.com") if error puts "failed: #{error}" end ``` -------------------------------- ### Dnsruby::Resolv class method usage example Source: https://github.com/alexdalitz/dnsruby Example of using the class method shortcuts `getaddress` and `getname` on `Dnsruby::Resolv` to resolve a hostname and reverse-lookup an IP address. ```ruby p Dnsruby::Resolv.getaddress("www.ruby-lang.org") p Dnsruby::Resolv.getname("210.251.121.214") ``` -------------------------------- ### Dnsruby::Section and RRSet usage examples Source: https://github.com/alexdalitz/dnsruby Shows how to use Section#rrsets and RRSet#add in practice. The first example queries a resolver and iterates over answer RRSets. The second example creates an RRSet and adds two A records. ```ruby res = Dnsruby::Resolver.new ret = res.query("example.com") a_rrsets = ret.answer.rrsets(Dnsruby::Types.A) a_rrsets.each { |rrset| puts rrset.to_s } rrset = Dnsruby::RRSet.new rrset.add(Dnsruby::RR.create("www.example.com 300 IN A 10.1.2.3")) rrset.add(Dnsruby::RR.create("www.example.com 300 IN A 10.1.2.4")) puts rrset.length # 2 ``` -------------------------------- ### Usage example: Dnsruby::Config.new Source: https://github.com/alexdalitz/dnsruby Shows typical indirect usage where Config is constructed internally by Resolver, DNS, and Update. This example creates a Config instance directly, triggers lazy parsing by accessing nameserver, and adds a higher-priority nameserver. ```ruby cfg = Dnsruby::Config.new puts cfg.nameserver # triggers lazy parse cfg.add_nameserver("8.8.8.8") # higher-priority nameserver ``` -------------------------------- ### Dnsruby.log and logger setup Source: https://github.com/alexdalitz/dnsruby Sets up a global Logger instance on STDOUT with level Logger::FATAL by default. Change the level with Dnsruby.log.level = Logger::INFO, or replace entirely with Dnsruby.log = new_logger (used by TheLog#set_logger). ```ruby @@logger = Logger.new(STDOUT) @@logger.level = Logger::FATAL def Dnsruby.log @@logger end ``` -------------------------------- ### Set a specific resolver for DNSSEC validation queries Source: https://github.com/alexdalitz/dnsruby/wiki/Home Create a Dnsruby::Resolver with a custom set of nameservers and assign it to Dnsruby::Dnssec.default_resolver to use those servers for validation queries. ```ruby res = Dnsruby::Resolver.new({:nameserver => ['192.168.1.1', '192.168.2.1']}) Dnsruby::Dnssec.default_resolver = res ``` -------------------------------- ### IXFR zone transfer example Source: https://github.com/alexdalitz/dnsruby Creates a ZoneTransfer with transfer_type IXFR, sets server and serial, transfers a zone, and prints delta details (start, end, adds, deletes). ```ruby zt = Dnsruby::ZoneTransfer.new zt.transfer_type = Dnsruby::Types.IXFR zt.server = "ns0.validation-test-servers.nominet.org.uk" zt.serial = 2007090401 deltas = zt.transfer("validation-test-servers.nominet.org.uk") deltas.each do |delta| puts "start=#{delta.start} end=#{delta.end} adds=#{delta.adds.length} deletes=#{delta.deletes.length}" end ``` -------------------------------- ### Default config loading: Config.default_config_hash, Config.parse_resolv_conf, Config.reset Source: https://github.com/alexdalitz/dnsruby These class methods handle loading and parsing resolv.conf-format configuration files. parse_resolv_conf reads a file and returns a Hash with keys :nameserver, :domain, :search, :ndots, and :port. Recognized keywords include port, nameserver, domain, search, and options ndots:N. Comments start with # or ;. default_config_hash falls back to platform-specific sources on Windows and handles JRuby Windows drive-letter paths. Config.reset re-marks the config as unconfigured. ```ruby def Config.default_config_hash(filename="/etc/resolv.conf") # :nodoc: def Config.parse_resolv_conf(filename) # :nodoc: def Config.reset ``` -------------------------------- ### Dnsruby::DNS.open usage example Source: https://github.com/alexdalitz/dnsruby Example usage of `Dnsruby::DNS.open` with a block. The block receives the DNS instance and prints the address for "www.ruby-lang.org". The instance is automatically closed after the block. ```ruby Dnsruby::DNS.open { |dns| puts dns.getaddress("www.ruby-lang.org") } ``` -------------------------------- ### Dnsruby::Recursor#hints= Source: https://github.com/alexdalitz/dnsruby Sets the root hint servers used to start recursion. Delegates to set_hints. If hints is nil, the default nameserver is queried for hints. ```APIDOC ## Dnsruby::Recursor#hints= ### Description Sets the root hint servers used to start recursion. Delegates to set_hints. If hints is nil, the default nameserver is queried for hints. ### Method hints= ### Signature ```ruby def hints=(hints) ``` ### Parameters - **hints** - Required - The root hint servers to use ``` -------------------------------- ### RR.create usage examples Source: https://github.com/alexdalitz/dnsruby Creates resource records from zone-format strings and a Hash. String inputs use new_from_string; Hash inputs use new_from_hash. ```ruby a = Dnsruby::RR.create("foo.example.com. 86400 A 10.1.2.3") mx = Dnsruby::RR.create("example.com. 7200 MX 10 mailhost.example.com.") txt = Dnsruby::RR.create('baz.example.com 3600 HS TXT "text record"') rr = Dnsruby::RR.create({:name => 'example.com', :type => 'MX', :ttl => 10, :preference => 5, :exchange => 'mx1.example.com'}) ``` -------------------------------- ### Accessing header flags Source: https://github.com/alexdalitz/dnsruby Example usage showing how to set and read header flags on a Message object. ```APIDOC ## Accessing header flags ### Description Example usage showing how to set and read header flags on a Message object. ### Example ```ruby res = Dnsruby::Resolver.new msg = Dnsruby::Message.new("example.com") msg.header.rd = 1 # set recursion desired msg.header.qr = false puts msg.header.opcode.string # "Query" ``` ``` -------------------------------- ### Message constructor usage examples Source: https://github.com/alexdalitz/dnsruby Shows three ways to create a Dnsruby::Message with different question parameters. The first uses defaults for type and class, the second specifies type 'AAAA', and the third specifies type PTR and class 'HS'. ```ruby Dnsruby::Message.new('example.com') ``` ```ruby Dnsruby::Message.new('example.com', 'AAAA') ``` ```ruby Dnsruby::Message.new('example.com', Dnsruby::Types.PTR, 'HS') ``` -------------------------------- ### Usage examples for CodeMapper subclasses Source: https://github.com/alexdalitz/dnsruby Shows constant-style access, case-insensitive construction, integer construction, and unknown-type support via TYPE### (RFC 3597). Instances compare and hash by code; == also matches on the string attribute. ```ruby Dnsruby::Types.A # => Types instance, code 1, string "A" Dnsruby::Types.new('a') # same, case-insensitive Dnsruby::Types.new(15) # MX Dnsruby::Classes.new('IN') # class IN Dnsruby::RCode.NXDOMAIN.code # 3 Dnsruby::Algorithms.ECDSAP256SHA256 # => code 13 # Unknown-class/type support (RFC 3597) Dnsruby::Types.typesbyval(Dnsruby::Types.typesbyname("TYPE65280")) # => "TYPE65280" ``` -------------------------------- ### Query with DNSSEC enabled Source: https://github.com/alexdalitz/dnsruby Example of querying with dnssec=true and printing the security level string, e.g. "SECURE". ```ruby res = Dnsruby::Resolver.new res.dnssec = true msg = res.query("example.com") puts msg.security_level.string # e.g. "SECURE" ``` -------------------------------- ### Recursor usage example with require Source: https://github.com/alexdalitz/dnsruby Shows requiring dnsruby, creating a Recursor, and using the query method to resolve rob.com.au. The commented recurse call is noted as not the implemented method; query is the documented public method. ```ruby require 'dnsruby' rec = Dnsruby::Recursor.new answer = rec.recurse("rob.com.au") # (query is the documented method) # equivalent public method: answer = rec.query("rob.com.au", Dnsruby::Types.A) answer.answer.each { |rr| puts rr } ``` -------------------------------- ### Using an Update (send_message) Source: https://github.com/alexdalitz/dnsruby Demonstrates the full workflow of creating an update message, adding prerequisites and records, and sending it via a Resolver. This is a usage example rather than a separate method. ```APIDOC ## Using an Update ### Description Example of constructing an update and sending it with a Resolver. ### Example ```ruby require 'dnsruby' update = Dnsruby::Update.new('example.com') update.absent('foo.example.com.', 'A') # prerequisite update.add('foo.example.com.', 'A', 86400, '192.168.1.2') update.add('foo.example.com.', 'A', 86400, '172.16.3.4') res = Dnsruby::Resolver.new({:nameserver => 'primary-master.example.com'}) begin reply = res.send_message(update) puts "Update succeeded, verified? #{reply.verified?}" rescue Dnsruby::ResolvError => e puts "Update failed: #{e}" end ``` ``` -------------------------------- ### AXFR zone transfer example Source: https://github.com/alexdalitz/dnsruby Creates a ZoneTransfer, sets server and transfer_type to AXFR, transfers a zone, and prints each RR. Uses a public validation server. ```ruby zt = Dnsruby::ZoneTransfer.new zt.server = "ns0.validation-test-servers.nominet.org.uk" zt.transfer_type = Dnsruby::Types.AXFR zone = zt.transfer("validation-test-servers.nominet.org.uk") zone.each { |rr| puts rr } ``` -------------------------------- ### Clear all trusted keys with Dnsruby::Dnssec.clear_trusted_keys Source: https://github.com/alexdalitz/dnsruby/wiki/Home Clears all trusted keys, which also stops DLV validation. ```ruby Dnsruby::Dnssec.clear_trusted_keys() ``` -------------------------------- ### add usage examples Source: https://github.com/alexdalitz/dnsruby Adds update records: an A record, an MX record, and a TXT record created via RR.create. The add method requires the zone class for RRs, otherwise raises ArgumentError. ```ruby update.add('foo.example.com', 'A', 86400, '192.168.1.2') update.add('example.com', Dnsruby::Types.MX, 86400, 10, 'mailhost.example.com') update.add(Dnsruby::RR.create("bar.example.com 300 IN TXT \"hi\"")) ``` -------------------------------- ### Recursor query usage example Source: https://github.com/alexdalitz/dnsruby Creates a Recursor and queries for NS records of uk-dnssec.nic.uk, then prints the security level of the response. ```ruby rec = Dnsruby::Recursor.new ret = rec.query("uk-dnssec.nic.uk", "NS") puts ret.security_level ``` -------------------------------- ### initialize(*args) Source: https://github.com/alexdalitz/dnsruby Creates a new SingleResolver instance. Accepts a hash of configuration keys, a String or Name for the server, or nil to use the first system nameserver. ```APIDOC ## initialize(*args) ### Description Creates a new SingleResolver instance. Accepts a hash of configuration keys, a String or Name for the server, or nil to use the first system nameserver. ### Method Constructor ### Parameters #### *args - **args** (Hash / String / Name) - Optional - Configuration hash or server name. See config keys below. Constructor keys: `:server`, `:port`, `:use_tcp`, `:no_tcp`, `:ignore_truncation`, `:src_address`, `:src_address6`, `:src_port`, `:udp_size`, `:persistent_tcp`, `:persistent_udp`, `:tsig`, `:packet_timeout`, `:recurse`. Unknown keys are logged and ignored. ### Request Example ```ruby sr = Dnsruby::SingleResolver.new({:server => "8.8.8.8"}) ``` ``` -------------------------------- ### Disable caching and validation for a message Source: https://github.com/alexdalitz/dnsruby/wiki/Home Configure a Message to skip cache checking/storing and DNSSEC validation, then send it with send_message. ```ruby m.do_caching = false m.do_validation = false res.send_message(m) ``` -------------------------------- ### send_message usage example Source: https://github.com/alexdalitz/dnsruby Shows how to call send_message and rescue ResolvError and ResolvTimeout. On error, error.response is set to the partial response when the error is a ResolvError. ```ruby res = Dnsruby::Resolver.new begin response = res.send_message(Dnsruby::Message.new('example.com', Dnsruby::Types.MX)) rescue Dnsruby::ResolvError # handle rescue Dnsruby::ResolvTimeout # handle end ``` -------------------------------- ### RRSet usage example - create and add A records Source: https://github.com/alexdalitz/dnsruby Creates an empty RRSet, adds two A records for the same name, and prints the length (2). Demonstrates the add method and length accessor. ```ruby rrset = Dnsruby::RRSet.new rrset.add(Dnsruby::RR.create("www.example.com 300 IN A 10.1.2.3")) rrset.add(Dnsruby::RR.create("www.example.com 300 IN A 10.1.2.4")) puts rrset.length # 2 ``` -------------------------------- ### present usage examples Source: https://github.com/alexdalitz/dnsruby Adds prerequisite records to the pre section. The three forms correspond to: name in use (type ANY), RRset exists (value independent), and RRset exists (value dependent, uses zone class). Returns the RR. ```ruby update.present('example.com') # name in use update.present('foo.example.com', 'A') # RRset exists update.present('foo.example.com', 'A', '192.168.1.2') # value dependent ``` -------------------------------- ### Disable validation for a specific Message Source: https://github.com/alexdalitz/dnsruby/wiki/Home Set msg.do_validation = false before sending a Message to prevent dnsruby from validating the response to that query. ```ruby msg.do_validation = false ``` -------------------------------- ### Creating Question objects with different parameters Source: https://github.com/alexdalitz/dnsruby Shows three ways to instantiate a Question: with explicit qtype, with defaults (A and IN), and with an IP address that automatically sets qtype to PTR for reverse lookup. ```ruby Dnsruby::Question.new('example.com', 'MX') Dnsruby::Question.new('example.com') # A, IN Dnsruby::Question.new('208.77.188.166') # PTR automatically ``` -------------------------------- ### Remove trust anchors with Dnsruby::Dnssec.clear_trust_anchors Source: https://github.com/alexdalitz/dnsruby/wiki/Home Removes only the trust anchors and the keys generated from them, leaving DLV keys and validation from the root intact. ```ruby Dnsruby::Dnssec.clear_trust_anchors() ``` -------------------------------- ### Send plain message without processing Source: https://github.com/alexdalitz/dnsruby/wiki/Home Send a Message with no pre- or post-processing: no EDNS headers, no header flag adjustments, no caching or validation. Useful for tools authors. ```ruby res.send_plain_message(Message.new("nic.uk")) ``` -------------------------------- ### Dnsruby::Resolv.initialize Source: https://github.com/alexdalitz/dnsruby Constructs a Resolv instance with a list of resolvers that respond to each_address and each_name. ```APIDOC ## Dnsruby::Resolv.initialize ### Description Constructs a Resolv instance with a list of resolvers that respond to each_address and each_name. ### Method Constructor ### Signature ```ruby def initialize(resolvers=[Hosts.new, DNS.new]) ``` ### Parameters - **resolvers** (Array) - Optional - Array of objects responding to `each_address` and `each_name`; defaults to `[Hosts.new, DNS.new]` ``` -------------------------------- ### Check Message security level for SECURE Source: https://github.com/alexdalitz/dnsruby/wiki/Home Use Message#security_level to check if a response has been validated as SECURE, meaning the chain of trust was correctly followed and all signatures check OK. ```ruby if (msg.security_level == Dnsruby::Message::SecurityLevel::SECURE) print "Response was validated OK\n" end ``` -------------------------------- ### Encode and decode a Message Source: https://github.com/alexdalitz/dnsruby Creates a Message for "example.com" with an A query, encodes it to wire format, and decodes it back into a Message. ```ruby msg = Dnsruby::Message.new("example.com", Dnsruby::Types.A) data = msg.encode decoded = Dnsruby::Message.decode(data) ``` -------------------------------- ### Configure ISC DLV repository with RR.create and Dnssec.add_dlv_key Source: https://github.com/alexdalitz/dnsruby/wiki/Home Adds ISC's DLV key to Dnsruby. Obtain the key string from ISC first. This method queries the DLV registry to get the ZSK from the KSK, and Dnsruby will validate responses against the DLV repository if it cannot validate from trust anchors. ```ruby dlv_key = RR.create("DLV_KEY_STRING_FROM_ISC") Dnssec.add_dlv_key(dlv_key) ``` -------------------------------- ### Configure a trust anchor with Dnsruby::RR.create and Dnsruby::Dnssec.add_trust_anchor Source: https://github.com/alexdalitz/dnsruby/wiki/Home Creates a DNSKEY trust anchor for the uk-dnssec.nic.uk DNSSEC test zone and adds it to Dnsruby. After this, Dnsruby attempts to validate responses from that zone or its children. ```ruby trusted_key = Dnsruby::RR.create({:name => "uk-dnssec.nic.uk.", :type => Dnsruby::Types.DNSKEY, :flags => 257, :protocol => 3, :algorithm => 5, :key=> "AQPJO6LjrCHhzSF9PIVV7YoQ8iE31FXvghx+14E+jsv4uWJR9jLrxMYm sFOGAKWhiis832ISbPTYtF8sxbNVEotgf9eePruAFPIg6ZixG4yMO9XG LXmcKTQ/cVudqkU00V7M0cUzsYrhc4gPH/NKfQJBC5dbBkbIXJkksPLv Fe8lReKYqocYP6Bng1eBTtkA+N+6mSXzCwSApbNysFnm6yfQwtKlr75p m+pd0/Um+uBkR4nJQGYNt0mPuw4QVBu1TfF5mQYIFoDYASLiDQpvNRN3 US0U5DEG9mARulKSSw448urHvOBwT9Gx5qF2NE4H9ySjOdftjpj62kjb Lmc8/v+z" }) Dnsruby::Dnssec.add_trust_anchor(trusted_key) ``` -------------------------------- ### Configure dnsruby to use a recursive nameserver for validation Source: https://github.com/alexdalitz/dnsruby/wiki/Home Set Dnsruby::Dnssec.do_validation_with_recursor to false to direct validation queries to the system default configured nameservers instead of performing them recursively. The default is to perform validation recursively. ```ruby Dnsruby::Dnssec.do_validation_with_recursor = false ``` -------------------------------- ### Change validation policy with Dnsruby::Dnssec.validation_policy Source: https://github.com/alexdalitz/dnsruby/wiki/Home Sets the validation policy to ROOT_THEN_LOCAL_ANCHORS, varying the precedence of search order. Separate key caches are maintained by each validator, allowing dynamic configuration. DLV validation is only performed once the DLV key has been added. ```ruby Dnsruby::Dnssec.validation_policy = Dnsruby::Dnssec::ValidationPolicy::ROOT_THEN_LOCAL_ANCHORS ``` -------------------------------- ### Dnsruby::DNS constructor definition Source: https://github.com/alexdalitz/dnsruby Defines the `initialize` method for `Dnsruby::DNS`. Accepts an optional `config_info` parameter that can be nil (platform default), a String (resolv.conf-format file), or a Hash with `:nameserver`, `:search`, and `:ndots` keys. Builds an internal `Config` and `Resolver`. Exposes `attr_reader :config` and `attr_accessor :do_caching` (default `true`). ```ruby def initialize(config_info=nil) ``` -------------------------------- ### Dnsruby::Resolv class method shortcuts Source: https://github.com/alexdalitz/dnsruby Defines class method shortcuts for `Dnsruby::Resolv` that delegate to a singleton instance. `instance` lazily creates one `Dnsruby::Resolv`. The other methods mirror the instance methods and operate on the shared instance. ```ruby def self.instance # lazily creates one Dnsruby::Resolv def self.getaddress(name) def self.getaddresses(name) def self.each_address(name, &block) def self.getname(address) def self.getnames(address) def self.each_name(address, &proc) ``` -------------------------------- ### Label#initialize Source: https://github.com/alexdalitz/dnsruby Creates a new Label. Raises ResolvError if the string exceeds the maximum label length. ```APIDOC ## Label#initialize ### Description Creates a new Label. Raises ResolvError if the string exceeds the maximum label length. ### Method initialize ### Parameters - `string` (String) - Required - The label string ### Raises - `ResolvError` - If the string exceeds `@@max_length` (default 63) ``` -------------------------------- ### Nameserver methods: nameserver, nameserver=, add_nameserver, Config.resolve_server, check_ns, single? Source: https://github.com/alexdalitz/dnsruby Methods for managing nameservers. nameserver triggers parsing and returns the nameserver list. nameserver= sets a validated nameserver, and add_nameserver prepends at higher priority. Config.resolve_server resolves a server name/address, and check_ns validates names. single? returns the first nameserver if exactly one exists, otherwise nil. Validation via check_ns accepts Name, String, IPv4, or IPv6; strings must parse as IP or name, otherwise ArgumentError is raised. ```ruby def nameserver # triggers parse; returns the nameserver list def nameserver=(ns) # sets (validated); nameservers must resolve to IPs def add_nameserver(ns) # prepends at higher priority; String or Array def Config.resolve_server(ns) # :nodoc: resolves a server name/address def check_ns(ns) # :nodoc: validation def single? # :nodoc: first nameserver if exactly one, else nil ``` -------------------------------- ### DNS / Resolv constructor configuration Source: https://github.com/alexdalitz/dnsruby Constructors for Dnsruby::DNS and Dnsruby::Resolv that accept configuration for nameservers, search domains, and ndots. DNS.new accepts nil, a file path, or a Hash; Resolv.new accepts an array of resolver-like objects. ```APIDOC ## Dnsruby::DNS.new(config_info=nil) ### Description Creates a DNS resolver with the given configuration. `config_info` can be `nil` (platform default), a `String` path to a file in `/etc/resolv.conf` format, or a `Hash` with keys `:nameserver`, `:search`, `:ndots`. ### Parameters #### config_info - `nil` - Use platform default (`/etc/resolv.conf`) - `String` - Path to a file in `/etc/resolv.conf` format - `Hash` - Keys: `:nameserver`, `:search`, `:ndots` ### Example ```ruby dns = Dnsruby::DNS.new({:nameserver => ['210.251.121.21'], :search => ['ruby-lang.org'], :ndots => 1}) ``` ## Dnsruby::DNS.open(*args) ### Description Opens a DNS resolver with the same configuration options as `DNS.new`. ## Dnsruby::Resolv.new(resolvers=[Hosts.new, DNS.new]) ### Description Creates a Resolv instance with an array of resolver-like objects implementing `each_address` / `each_name`. ``` -------------------------------- ### Dnsruby::Config#initialize Source: https://github.com/alexdalitz/dnsruby Creates a new Config instance. Sets up a mutex and marks the configuration as unconfigured, triggering lazy parsing on first access. ```APIDOC ## Dnsruby::Config#initialize ### Description Creates a new Config instance. Sets up a mutex and marks the configuration as unconfigured, triggering lazy parsing on first access. ### Method initialize ### Endpoint Dnsruby::Config#initialize ### Parameters None ### Response No return value. ``` -------------------------------- ### Run rake test with bundle exec Source: https://github.com/alexdalitz/dnsruby/blob/master/README.md Preface the rake test command with bundle exec to ensure the gem versions specified in Gemfile.lock are used at runtime, especially when encountering errors with rake test tasks. ```bash bundle exec rake test ``` -------------------------------- ### recursion_callback accessors Source: https://github.com/alexdalitz/dnsruby Allows installing a callback invoked during recursion. ```ruby def recursion_callback=(sub) def recursion_callback ``` -------------------------------- ### Constructor signature for Dnsruby::Question Source: https://github.com/alexdalitz/dnsruby Defines the initializer for a Question object. Requires a qname (String, Name, IPv4, or IPv6) and optionally accepts qtype and qclass. Raises ArgumentError if qname is nil. If qtype is omitted and the name is an IP address, qtype is set to Types.PTR for reverse lookup. The name is stored as an absolute Name. ```ruby def initialize(qname, qtype = :not_provided, qclass = :not_provided) ``` -------------------------------- ### Dnsruby::Recursor#recursion_callback= Source: https://github.com/alexdalitz/dnsruby Allows installing a callback invoked during recursion. ```APIDOC ## Dnsruby::Recursor#recursion_callback= ### Description Allows installing a callback invoked during recursion. ### Method recursion_callback= ### Signature ```ruby def recursion_callback=(sub) ``` ### Parameters - **sub** - Required - The callback to invoke during recursion ``` -------------------------------- ### Hosts constructor signature Source: https://github.com/alexdalitz/dnsruby Initializes a Hosts resolver with an optional filename; the file is lazy-loaded and cached. ```ruby def initialize(filename = DefaultFileName) ``` -------------------------------- ### Accessing question attributes from a Message Source: https://github.com/alexdalitz/dnsruby Shows how to retrieve the first question from a Dnsruby::Message and print its qname and qtype. The qname is output as 'example.com' and qtype as 'A'. ```ruby msg = Dnsruby::Message.new("example.com", Dnsruby::Types.A) q = msg.question[0] puts q.qname.to_s # "example.com" puts q.qtype.string # "A" ``` -------------------------------- ### hints= and class hint methods Source: https://github.com/alexdalitz/dnsruby hints= sets root hint servers, delegating to set_hints. set_hints configures resolver nameservers and rebuilds @@hints from root zone NS records. add_to_hints registers an NS RR's name and address into the hints cache. ```ruby def hints=(hints) def Recursor.set_hints(hints, resolver) def Recursor.add_to_hints(hints, rr) ``` -------------------------------- ### SingleResolver constructor options Source: https://github.com/alexdalitz/dnsruby Constructor for Dnsruby::SingleResolver that accepts a Hash of configuration options. Defaults match Resolver constants, with some methods not available on this class. ```APIDOC ## Dnsruby::SingleResolver.new(*args) ### Description Creates a SingleResolver instance with the given options. Accepts a Hash with keys: `:server`, `:port`, `:use_tcp`, `:no_tcp`, `:ignore_truncation`, `:src_address`, `:src_address6`, `:src_port`, `:udp_size`, `:persistent_tcp`, `:persistent_udp`, `:tsig`, `:packet_timeout`, `:recurse`. Defaults match the `Resolver` constants. ### Parameters #### Hash Options - `:server` - Defaults to the first system-configured nameserver. - `:port` - `:use_tcp` - `:no_tcp` - `:ignore_truncation` - `:src_address` - `:src_address6` - `:src_port` - `:udp_size` - `:persistent_tcp` - `:persistent_udp` - `:tsig` - `:packet_timeout` - `:recurse` ### Notes - `retry_times=` and `retry_delay=` raise `NoMethodError` on this class. - `packet_timeout=` also sets `query_timeout`; `query_timeout` is aliased to `packet_timeout`. ``` -------------------------------- ### server / server= Source: https://github.com/alexdalitz/dnsruby Gets or sets the current nameserver address. The setter resolves the given server and rebuilds the internal PacketSender. ```APIDOC ## server / server= ### Description Gets or sets the current nameserver address. The setter resolves the given server and rebuilds the internal PacketSender. ### Method Accessor ### Parameters #### server= - **s** (String) - Required - The server address to set. ### Response #### server Returns the current nameserver address (String). ``` -------------------------------- ### to_s and == method signatures Source: https://github.com/alexdalitz/dnsruby Declares the to_s and equality methods. to_s renders the question in a standard format with qname, qclass, and qtype. == compares qname, qtype, and qclass, coercing the other's class. ```ruby def to_s def ==(other) ``` -------------------------------- ### get_ready: Dnsruby::Config#get_ready Source: https://github.com/alexdalitz/dnsruby Forces config parsing if not yet configured. This method is idempotent and is used internally by the resolver. ```ruby def get_ready ``` -------------------------------- ### Dnsruby::Resolv constructor definition Source: https://github.com/alexdalitz/dnsruby Defines the `initialize` method for `Dnsruby::Resolv`. `resolvers` is an Array of objects responding to `each_address` and `each_name` (typically `Hosts` and `DNS`). Defaults to `[Hosts.new, DNS.new]`. ```ruby def initialize(resolvers=[Hosts.new, DNS.new]) ``` -------------------------------- ### RR.find_class / RR.get_class Source: https://github.com/alexdalitz/dnsruby Internal methods to find or get the RR class for a given type and class value. Marked as :nodoc:. ```APIDOC ## RR.find_class / RR.get_class ### Description Internal methods to find or get the RR class for a given type and class value. Marked as :nodoc:. ### Method `RR.find_class(type_value, class_value)` / `RR.get_class(type_value, class_value)` ### Parameters - `type_value` - Required - The type value. - `class_value` - Required - The class value. ``` -------------------------------- ### subdomain_of? example Source: https://github.com/alexdalitz/dnsruby Demonstrates subdomain_of? behavior: returns true when the name is a subdomain of the given domain, false when equal or not a subdomain. ```ruby domain = Dnsruby::Name.create("y.z") p Dnsruby::Name.create("w.x.y.z").subdomain_of?(domain) #=> true p Dnsruby::Name.create("x.y.z").subdomain_of?(domain) #=> true p Dnsruby::Name.create("y.z").subdomain_of?(domain) #=> false ``` -------------------------------- ### Dnsruby::ZoneTransfer::Delta Source: https://github.com/alexdalitz/dnsruby Represents a single IXFR delta, containing the starting and ending serial numbers, plus arrays of added and deleted RRs. ```APIDOC ## ZoneTransfer::Delta ### Description Represents a single IXFR delta, containing the starting and ending serial numbers, plus arrays of added and deleted RRs. ### Attributes - **start** (Integer) - Starting serial - **end** (Integer) - Ending serial - **adds** (Array of RRs) - RRs added - **deletes** (Array of RRs) - RRs deleted ### Methods - `initialize` - Initializes with empty adds and deletes arrays - `to_s` - Returns a string representation ```