Do I have to provide an actual numerical IP address to :gen_tcp.connect?

I have the following line in an elixir module:

{:ok, socket} = :gen_tcp.connect("my-appname-1842614232.us-east-1.elb.amazonaws.com", 4000, opts)

The error I am getting is: “evaluator process exited with reason: :badarg”

It worked fine when I had the line like this:

{:ok, socket} = :gen_tcp.connect({10, 247, 4, 104}, 4000, opts)

So my question is – do I have to use an actual IP address?

2 Likes

According to the documentation it has to be inet:hostname() which is string(), which in elixir means char_list, so your hostname has to be 'example.com'. Alternatively you can also use the c-sigil (~c[example.com])

7 Likes

notice the single quotes ' instead of double "

Generally when interacting directly with Erlang libs, they expect char lists

4 Likes

Thanks, @NobbZ – you’ve solved a problem of mine yet again!

You should mark this thread as solved so others can see the answer right away and see it as solved in the thread list. :slight_smile:

1 Like

Just small note that from Elixir 1.5 you should use String.to_charlist and previous version - to_char_list is deprecated.

1 Like

@NobbZ I actually looked in the docs and didn’t see this solution. Is it mentioned somewhere on this page: http://erlang.org/doc/man/gen_tcp.html ? Are these the docs you were referring to?

Yes, they are.

The spec of :gen_tcp.connect/3:

connect(Address, Port, Options) → {ok, Socket} | {error, Reason}

Types

  • Address = inet:socket_address() | inet:hostname()
  • [other types omitted since they are unimportant here]

inet:hostname() (which is :inet.hostname in elixir syntax) is defined as follows:

hostname() = atom() | string()

Erlangs string() type is equal to elixirs charlist type.

charlists can be created using the charlist literal, which is an single-quoted “string”. Also one can use the c and C sigils to create them, when one wants to be a little bit more explicit.

And as @PatNowak correctly tells, you can convert anything implementing List.Chars by passing it to Kernel.to_charlist/1

2 Likes

thanks - seems so obvious now.