Over a million developers have joined DZone.

Find Primary MX Record

·
// 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
Topics:

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}