Search code examples
socketserlangelixirgen-tcp

erlang/elixir gen_tcp connect - not connecting but telnet wil


I have a (zebra) printer that I can telnet to:

jasongoodwin$ telnet 192.168.101.051 9100
Trying 192.168.101.51...
Connected to 192.168.101.051.
Escape character is '^]'.

Then I can send it some data from the console and it will print a label for me.

I can also connect and print from scala no problem:

def printZpl(zpl: String, ip: String, port: Int): Unit = {
  val clientSocket = new Socket(ip, port)
  val outToServer = new DataOutputStream(clientSocket.getOutputStream())
  outToServer.writeBytes(zpl)
  clientSocket.close()
}

But I can't seem to connect via elixir/erlang via gen_tcp:

opts = [:binary, active: false]
{:ok, socket} = :gen_tcp.connect('192.168.101.051', 9100, opts)

Iex just freezes and eventually times out. Works fine connecting to eg redis... I'm assuming there is some option or quality of this connection that causes it to fail from elixir/erlang?

I find the gen_tcp docs to be unhelpful - I tried a bunch of different params.


Solution

  • The issue is that the IP address had a preceeding 0

    {:ok, socket} = :gen_tcp.connect('192.168.101.051', 9100, opts)
    

    If I connect like so this works.

    iex(1)> opts = [:binary, active: false]
    [:binary, {:active, false}]
    iex(2)> {:ok, socket} = :gen_tcp.connect('192.168.101.51', 9100, opts)
    {:ok, #Port<0.1243>}