1

I'm trying to get my IP address using Erlang.

I found this example from here: Erlang: Finding my IP Address

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

But it returns a value like this: {127,0,0,1}

I want it to return a value like this: "{127,0,0,1}" with double quotes ("") because I want to use re:replace to change , to ..

How can I do that?

Community
  • 1
  • 1
Mr. zero
  • 245
  • 4
  • 18

2 Answers2

14

If you want to convert the IP address to a string, you can use the function inet:ntoa/1:

> inet:ntoa({127, 0, 0, 1}).
"127.0.0.1"

As a bonus, it handles IPv6 addresses as well:

> inet:ntoa({0,0,0,0,0,0,0,1}).
"::1"
legoscia
  • 39,593
  • 22
  • 116
  • 167
4

The function returns the tuple because this is something that erlang code can handle natively. What you might want to do is transform this tuple to a string and then apply string operations. Details on how to do that can be found e.g. at Convert erlang terms to string, or decode erlang binary

Community
  • 1
  • 1
Christian
  • 58
  • 3