DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Find Primary MX Record

12.12.2008
| 5332 views |
  • submit to reddit
        // description of your code here

# Returns the highest priority MX record server for a domain or nil.
#
#   get_MX_server('mydomain.com') # => 'smtp.mydomain.com'
def get_MX_server(domain)
  require 'resolv'
  mx = nil
  Resolv::DNS.open do |dns|
    mail_servers = dns.getresources(domain, Resolv::DNS::Resource::IN::MX)
    return nil unless mail_servers and not mail_servers.empty?
    highest_priority = mail_servers.first
    mail_servers.each do |server|
      highest_priority = server if server.preference < highest_priority.preference
    end
    mx = highest_priority.exchange.to_s
  end
  return mx
end