Revision as of 13:23, 15 June 2007

Contents

Introduction

For the E-mail server I'm writing I had the simple requirement to lookup MX records from the DNS.
Erlang provides a small interface for performing DNS queries.
The modules you'll need to use are inet_db, inet_dns and inet_res.

Using The DNS Lookup Interface

Although it looks like there is a mechanism for querying the system nameservers, I couldn't figure
out how it works properly so I have to start by adding a nameserver to query from:

ok = inet_db:add_ns({192,168,0,10}).

This adds the given IP to the internal database of nameservers. (Note the Erlang convention
of IP addresses given as quadruples).

The next stage is to construct an appropriate query. Handily enough Erlang provides
a very simple interface. The header file is "kernel/src/inet_dns.hrl" and this
provides all of the macros and details required to do the lookup.

Use include_lib to add this:

-include_lib("kernel/src/inet_dns.hrl").

The query is extremely simple to achieve, just pass the domain and record type
to inet_res:nslookup/3.

This returns { ok, Result } on success or {error, Reason} on failure.

Result is actually a record, named #dns_rec in inet_dns.hrl. This record has
five fields, but for the purposes of this HowTo we are only interested in one,
the arlist field. This field is a list of resource entries. To do the MX lookup
I simply match on the record and list:

findmx/1 is a function which searches through the list of resources and filters
out the MX servers. We're basically interested in the host addresses
(for sending email to) so findmx/1 is very simple (and naive),
for this HowTo I'll simply return the first host found: