Why am I getting an error in gen_tcp.listen/2?

Here is my code:

defmodule Server do
    def listen_for_con(ip_addr) do
        case :gen_tcp.listen(8000, [:binary, active: false, reuseaddr: true, ip: ip_addr]) do
            {:ok, server} -> IO.puts "Server is listening"
            {:error, reason} -> IO.puts "Error in :gen_tcp.listen: #{reason}"


Here is the error that I get when I try to run the code:

(exit) :badarg
(kernel 7.2) inet_tcp.erl:160: :inet_tcp.listen/2
server2.exs:3: Server.listen_and_accept/1
(elixir 1.11.2) lib/code.ex:931: Code.require_file/2

I do not know what is wrong with the arguments I am giving to the function.

It is a script and I run it as follows: elixir server.exs

Thanks in advance guys.

You need to specify the IP address as a 4- or 6-tuple, e.g. {127, 0, 0, 1}.

You can use inet:parse_address/1 to parse a human-readable address, just note that this is an Erlang API so it expects a charlist, e.g. :inet.parse_address('').


Thanks man, I tried to find out more about the erlang inet api but all I found was a page in the docs that losted all the functions names, do you mind recommending a resource that provides more info about the api ?

The official documentation is in the inet reference manual you found, and a small section of the kernel user guide. There’s also a chapter on sockets in the LYSE book, which may help you get started.

Both of these assume familiarity with Erlang syntax, which is often the case when you get to such lower-level APIs. There may be some Elixir-oriented blog posts out there, I don’t know…