Erlang: Finding my IP Address

We've been successfully using this function to get the first non-local IPv4 address:

local_ip_v4() ->
    {ok, Addrs} = inet:getifaddrs(),
    hd([
         Addr || {_, Opts} <- Addrs, {addr, Addr} <- Opts,
         size(Addr) == 4, Addr =/= {127,0,0,1}
    ]).

It can of course be changed to return IPv6 as well if that is what you want.


You should first understand that your host can have more than one unique IP address. In fact all {0,0,0,0}, {127,0,0,1} (hey! actually all 127.0.0.0/8 is your addresses) and {192,168,0,14} are all your valid IP addresses. Additionally if your host will have some other interfaces connected you'll get even more IP addresses. So you basically can't find a function that will get your the IP address you need.

Instead it is a well documented function in the inet module that will list interfaces each with its own IP address:

getifaddrs() -> {ok, Iflist} | {error, posix()}

Types:

Iflist = [{Ifname, [Ifopt]}]
Ifname = string()
Ifopt = {flag, [Flag]}
      | {addr, Addr}
      | {netmask, Netmask}
      | {broadaddr, Broadaddr}
      | {dstaddr, Dstaddr}
      | {hwaddr, Hwaddr}
Flag = up
     | broadcast
     | loopback
     | pointtopoint
     | running
     | multicast
Addr = Netmask = Broadaddr = Dstaddr = ip_address()
Hwaddr = [byte()]

Tags:

Erlang