Check host port availability

Using Sockets, the connect function serves to establish a connection through a TCP socket

connect([host], port::Integer) -> TCPSocket

only problem is, if the host is not listening through this port, trying to connect will result in an error

julia> connect(5000)
ERROR: IOError: connect: connection refused (ECONNREFUSED)
 [1] wait_connected(::TCPSocket) at D:\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.4\Sockets\src\Sockets.jl:520
 [2] connect at D:\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.4\Sockets\src\Sockets.jl:555 [inlined]
 [3] connect at D:\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.4\Sockets\src\Sockets.jl:541 [inlined]
 [4] connect(::Int64) at D:\buildbot\worker\package_win64\build\usr\share\julia\stdlib\v1.4\Sockets\src\Sockets.jl:537
 [5] top-level scope at REPL[2]:100:

Is there any form to check if the port is available before trying to connect? More specifically, is there a way (appart from a while-try-catch-loop) for the client to wait for the availability of the host? Simmilarly to how accept(listen(5000)) waits for a client to connect.

I think try/catch is your only option, even if there was a way to check availability, without some sort of atomic “check/listen” or “check/reserve” operation there would be a race condition between checking availability and actually listening, so you would always have to handle the listen throwing an exception.

1 Like