Host - Reverse IP DNS lookups

Super tiny and simple: I wrote this to support reverse lookups. E.g.:

iex(1)> Host.reverse_lookup(ip: "172.217.5.206")
{:ok, "lax28s10-in-f14.1e100.net"}

I made this because I’m writing a Phoenix web service which needs to make decisions based on the domain of the visitor. And so it needs the ability to determine the domain name from the request IP address.

Here’s the simple implementation:

def reverse_lookup(ip: ip) do
    {output, status} = System.cmd("host", [ip])

    case status do
      0 ->
        %{"domain" => domain} =
          Regex.named_captures(~r/domain name pointer (?<domain>.+)\.$/, output)

        {:ok, domain}

      _ ->
        {:error, output}
    end
  end
2 Likes

You may want to consider using Erlang’s built-in function instead, which saves you the trouble of spawning an external process:

iex(1)> :inet_res.gethostbyaddr({172, 217, 5, 206})
{:ok,
 {:hostent, 'lax28s10-in-f14.1e100.net', [], :inet, 4, [{172, 217, 5, 206}]}}

See the documentation here: http://erlang.org/doc/man/inet_res.html

OTP’s resolver can be a bit flaky (you can tune it using the inetrc configuration file: http://erlang.org/doc/apps/erts/inet_cfg.html), but it will likely perform better.

7 Likes