Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a DNS TXT record in Ruby

Tags:

ruby

dns

I need to get the txt field from the DNS record.
Is there any ruby api to do something like this?

nslookup -q=txt xxxx.com
like image 883
anusuya Avatar asked May 26 '10 13:05

anusuya


People also ask

What is TXT in DNS record?

TXT records are a type of Domain Name System (DNS) record that contains text information for sources outside of your domain. You add these records to your domain settings. You can use TXT records for various purposes. Google uses them to verify domain ownership and to ensure email security.


1 Answers

Use the Ruby stdlib Resolv::DNS library without installing a gem:

require 'resolv'
txt = Resolv::DNS.open do |dns|
  records = dns.getresources("_dmarc.yahoo.com", Resolv::DNS::Resource::IN::TXT)
  records.empty? ? nil : records.map(&:data).join(" ")
end
#=> "v=DMARC1; p=reject; sp=none; pct=100; rua=mailto:[email protected], mailto:[email protected];"

getresources returns an array of instances of the requested record class name (Resolv::DNS::Resource::IN::TXT). Here, I return nil if the TXT record(s) or the host name were not found, otherwise I map over the records, call data to get the values, then join them together.

Any DNS record type [TXT, NS, CNAME, MX, ...] can be queried as well by replacing TXT in the above example.

TXT records are "unstructured" and used for enhanced data for the hostname such as SPF, DKIM, DMARC configurations. In practice, there may be only one TXT record, but the RFC doesn't say how many there can be.

Read the docs at: http://www.ruby-doc.org/stdlib-2.1.1/libdoc/resolv/rdoc/index.html

like image 60
Allen Avatar answered Sep 18 '22 20:09

Allen